forge-openclaw-plugin 0.2.20 → 0.2.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{board-DGbXWEuu.js → board-_C6oMy5w.js} +2 -2
- package/dist/assets/{board-DGbXWEuu.js.map → board-_C6oMy5w.js.map} +1 -1
- package/dist/assets/index-B4A6TooJ.js +63 -0
- package/dist/assets/index-B4A6TooJ.js.map +1 -0
- package/dist/assets/index-D6Xs_2mo.css +1 -0
- package/dist/assets/{motion-B5Qoz2Ci.js → motion-D4sZgCHd.js} +2 -2
- package/dist/assets/{motion-B5Qoz2Ci.js.map → motion-D4sZgCHd.js.map} +1 -1
- package/dist/assets/{table-D_iurDQu.js → table-BWzTaky1.js} +2 -2
- package/dist/assets/{table-D_iurDQu.js.map → table-BWzTaky1.js.map} +1 -1
- package/dist/assets/{ui-D5QUYUq4.js → ui-BzK4azQb.js} +2 -2
- package/dist/assets/{ui-D5QUYUq4.js.map → ui-BzK4azQb.js.map} +1 -1
- package/dist/assets/vendor-De38P6YR.js +729 -0
- package/dist/assets/vendor-De38P6YR.js.map +1 -0
- package/dist/assets/{viz-BD9WSxHz.js → viz-C6hfyqzu.js} +2 -2
- package/dist/assets/{viz-BD9WSxHz.js.map → viz-C6hfyqzu.js.map} +1 -1
- package/dist/index.html +8 -8
- package/dist/server/app.js +301 -19
- package/dist/server/health.js +82 -21
- package/dist/server/managers/platform/background-job-manager.js +103 -8
- package/dist/server/managers/platform/llm-manager.js +91 -5
- package/dist/server/managers/platform/openai-responses-provider.js +683 -70
- package/dist/server/repositories/diagnostic-logs.js +243 -0
- package/dist/server/repositories/wiki-memory.js +595 -62
- package/dist/server/types.js +56 -0
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/server/migrations/023_diagnostic_logs.sql +28 -0
- package/skills/forge-openclaw/SKILL.md +14 -0
- package/dist/assets/index-4-1WI9i7.css +0 -1
- package/dist/assets/index-BZbHajNK.js +0 -63
- package/dist/assets/index-BZbHajNK.js.map +0 -1
- package/dist/assets/vendor-KARp8LAR.js +0 -706
- package/dist/assets/vendor-KARp8LAR.js.map +0 -1
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
var Wc=Object.defineProperty;var Gc=(t,s,i)=>s in t?Wc(t,s,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[s]=i;var Ai=(t,s,i)=>Gc(t,typeof s!="symbol"?s+"":s,i);import{J as Hc,g as Xc,j as e,r as c,K as Kn,S as Jc,Q as Yc,L as Vc,M as Un,N as Zc,O as em,T as Qn,U as tm,V as sm,W as Oa,X as ht,Y as dt,Z as Ro,$ as yi,a0 as Gi,a1 as Wn,a2 as Gn,a3 as Hn,a4 as zo,a5 as Fa,a6 as us,a7 as Xn,a8 as Gs,a9 as im,aa as am,ab as mt,ac as qo,ad as ji,ae as ot,af as Ze,ag as ve,ah as Ae,ai as Zt,aj as ya,ak as Jn,al as nm,am as ka,an as Mn,ao as vt,a as Bo,ap as Sa,aq as rm,ar as Cs,as as lm,at as om,au as Hi,av as ps,aw as We,ax as Ko,ay as Uo,az as Ni,aA as dm,aB as cm,aC as pe,aD as ge,aE as mm,aF as hm,aG as ki,aH as um,aI as pm,aJ as xm,aK as gm,aL as Le,aM as bm,aN as fm,aO as Ks,aP as Yn,aQ as ft,aR as Wt,aS as wm,aT as Qo,aU as ys,aV as Bi,aW as vm,aX as bt,aY as Wo,aZ as ym,a_ as ja,a$ as rs,b0 as Wr,b1 as Us,b2 as Go,b3 as Hs,b4 as Ho,b5 as Gr,b6 as Vn,b7 as jm,b8 as Nm,b9 as km,ba as Sm,bb as _a,bc as Si,bd as Hr,be as Cm,bf as Qs,bg as Im,bh as Xo,bi as Tm,bj as Pm,bk as Mm,bl as En,bm as Em,bn as Am,bo as Lm,bp as Dm,bq as Jo,br as Yo,bs as Vo,bt as Zo,bu as An,bv as $m,bw as Om,bx as Fm,by as _m,bz as Rm,bA as zm,bB as qm,bC as Bm,bD as Km,bE as Um,bF as ed,bG as Qm,bH as Wm,bI as Gm,bJ as Hm,bK as Ca,bL as Xm,bM as Jm,bN as Ym,bO as Ia,bP as Vm,bQ as td,bR as Zm,bS as eh,bT as th,bU as Xr,bV as sh,bW as ih,bX as ah,bY as nh,bZ as Zn,b_ as en,b$ as rh,c0 as lh,c1 as Jr,c2 as sd,c3 as oh,c4 as dh,c5 as ch,c6 as mh,c7 as hh,c8 as uh,c9 as De,ca as tn,cb as ph,cc as xh,H as gh,cd as bh,ce as fh}from"./vendor-De38P6YR.js";import{R as Lt,P as Dt,O as $t,C as Ot,T as Rt,D as Gt,a as _t,b as wh}from"./ui-BzK4azQb.js";import{m as wt,A as Ta,u as vh}from"./motion-D4sZgCHd.js";import{c as yh,u as jh,f as Yr,g as Nh}from"./table-BWzTaky1.js";import{R as id,A as kh,X as ad,Y as nd,c as Vr,B as Sh,e as Ch}from"./viz-C6hfyqzu.js";import{u as rd,a as ld,D as od,S as Ln,v as Dn,b as Ih,p as Th,c as Ph,P as dd,d as cd,e as md,C as hd,f as Mh,g as Eh}from"./board-_C6oMy5w.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const r of a)if(r.type==="childList")for(const l of r.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&n(l)}).observe(document,{childList:!0,subtree:!0});function i(a){const r={};return a.integrity&&(r.integrity=a.integrity),a.referrerPolicy&&(r.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?r.credentials="include":a.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function n(a){if(a.ep)return;a.ep=!0;const r=i(a);fetch(a.href,r)}})();function re(...t){return Hc(Xc(t))}function er(t){return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(t))}function tr({className:t,tone:s="primary"}){return e.jsx("span",{"aria-hidden":"true",className:re("inline-block size-4 rounded-full border border-white/14 border-t-transparent bg-[conic-gradient(from_180deg_at_50%_50%,rgba(255,255,255,0.02),rgba(255,255,255,0.34),rgba(255,255,255,0.02))] align-middle motion-safe:animate-spin",s==="primary"&&"shadow-[0_0_0_1px_rgba(192,193,255,0.22)]",s==="subtle"&&"opacity-80 shadow-[0_0_0_1px_rgba(255,255,255,0.08)]",s==="psyche"&&"shadow-[0_0_0_1px_rgba(110,231,183,0.2)]",t)})}function Ah(){return{common:{actions:{cancel:"Cancel",close:"Close",create:"Create",edit:"Edit",inspect:"Inspect",open:"Open",refresh:"Refresh",retry:"Retry",save:"Save",reset:"Reset filters",view:"View"},labels:{loading:"Loading",backgroundActivity:"Background activity",syncInProgress:"Sync in progress",connectionState:"Connection state",errorCode:"Error code: {code}",noDate:"No date",noProject:"No project linked",noGoal:"No life goal linked",noExecutionNote:"No execution note attached yet.",noRunNote:"No run note recorded.",released:"Released",stable:"Stable",timedOut:"Timed out",waiting:"Waiting",today:"Today"},enums:{taskStatus:{backlog:"Backlog",focus:"Focus",in_progress:"In progress",blocked:"Blocked",done:"Done"},priority:{critical:"Critical",high:"High",medium:"Medium",low:"Low"},effort:{marathon:"Marathon",deep:"Deep",light:"Light"},energy:{high:"High",steady:"Steady",low:"Low"},projectStatus:{active:"Active",paused:"Suspended",completed:"Finished"},goalHorizon:{quarter:"Quarter",year:"Year",lifetime:"Lifetime"}},shell:{appName:"The Kinetic Forge",appMark:"FORGE",more:"More",command:"Command",moreRoutesEyebrow:"More routes",moreRoutesTitle:"Move through Forge",moreRoutesDescription:"Use this sheet for secondary destinations so the bottom bar stays clean and easy to use.",loadingEyebrow:"Forge shell",loadingTitle:"Loading Forge",loadingDescription:"Checking your operator session and loading your latest snapshot.",sessionEyebrow:"Forge operator session",stateEyebrow:"Forge state",settled:"Up to date",savingOne:"Saving {count} change",savingOther:"Saving {count} changes",refreshingOne:"Refreshing {count} view",refreshingOther:"Refreshing {count} views",collapseSidebar:"Collapse sidebar",expandSidebar:"Expand sidebar",rail:{taskBackToKanban:"Back to Kanban",taskOpenToday:"Open Today",projectAll:"All projects",projectGoals:"Goal architecture",goalAll:"All goals",goalProjects:"Active projects",psycheHub:"Psyche hub",psycheReports:"Reports",overview:"Overview",today:"Today"},momentum:{title:"Momentum",streak:"Streak",xp:"XP",momentum:"Momentum",streakBadgeOne:"{count} day streak",streakBadgeOther:"{count} day streak",weeklyXp:"{count} weekly XP",liveMomentum:"{count}% momentum",psycheMode:"Psyche active"}},routeLabels:{overview:"Overview",goals:"Goals",habits:"Habits",projects:"Projects",strategies:"Strategies",preferences:"Preferences",calendar:"Calendar",sleep:"Sleep",sports:"Sports",kanban:"Kanban",today:"Today",notes:"Notes",wiki:"Wiki",psyche:"Psyche",activity:"Activity",insights:"Insights",review:"Review",settings:"Settings"},routeDetails:{overview:"See priorities, momentum, and recent evidence in one place.",goals:"Keep long-term direction connected to day-to-day work.",habits:"Track recurring commitments and recurring slips with explicit XP consequences.",projects:"Track the initiatives currently moving your goals forward.",strategies:"Plan the directed path from current work to the end state.",preferences:"Model taste, compare tradeoffs, and inspect preference evidence by context.",calendar:"Sync provider calendars, define work blocks, and plan real timeboxes.",sleep:"Inspect sleep timing, recovery, and Psyche-linked context.",sports:"Inspect workout sessions, training volume, and reflection metadata.",kanban:"Move active work across the board without losing context.",today:"Focus today on the clearest next move.",notes:"Search Markdown work notes and reopen the linked work fast.",wiki:"Work in a file-first memory vault with backlinks, entity links, and optional embeddings.",psyche:"Reflect on values, patterns, and reports with structure.",activity:"Review the visible audit trail of what changed and when.",insights:"Store and review coaching, analysis, and recommendations.",review:"Review the week and set the next push.",settings:"Manage collaboration, safety, and operator preferences."},navigation:{openRoute:"Open {label}",create:"Create",createTitle:"Create in Forge",createDescription:"Choose what you want to add next.",closeCreateMenu:"Close create menu",newGoal:"New life goal",newGoalDescription:"Define a long-term direction.",newProject:"New project",newProjectDescription:"Add a concrete initiative under a life goal.",newTask:"New task",newTaskDescription:"Capture the next actionable step in a project.",newStrategy:"New strategy",newStrategyDescription:"Add a directed plan across projects and tasks."},commandPalette:{searchPlaceholder:"Jump to a route, wiki page, goal, project, strategy, preference workspace, or focus task",noResults:"No command matches this search yet.",categoryRoute:"Route",categoryGoal:"Goal",categoryProject:"Project",categoryTask:"Task",routeOverview:"Open the overview.",routeToday:"Open today.",routeKanban:"Open the board.",routeNotes:"Search notes.",routeWiki:"Open the wiki memory workspace.",routePsyche:"Open Psyche.",routeGoals:"Open your life goals.",routeHabits:"Open your habits.",routeProjects:"Open your projects.",routeStrategies:"Open your strategies.",routePreferences:"Open the preferences workspace.",routeCalendar:"Open the calendar workspace.",routeReview:"Open weekly review.",routeSettings:"Open settings.",openLifeGoal:"Open life goal",openFocusTask:"Open focus task"},pageState:{loadingTitle:"Getting things ready",loadingDescription:"Loading the latest Forge data for this view."},settings:{localeLabel:"Language",localeDescription:"Choose the language used throughout Forge.",localeEnglish:"English",localeFrench:"French",localeSaved:"Language saved"},overview:{heroEyebrow:"Strategic overview",heroEmptyTitle:"Ready to get started",heroDescription:"See your goals, active projects, current tasks, and recent evidence in one place.",emptyTitle:"No overview yet",emptyDescription:"Create a life goal, project, or task to give Forge something real to organize.",emptyAction:"Open life goals",commandEyebrow:"Command surface",commandTitle:"Now, next, risks, and recent proof",commandDescription:"See what needs attention now, what comes next, where drift is appearing, and what progress is already visible.",sectionGoals:"Active life goals",sectionProjects:"Active projects",sectionFocus:"Today's focus",sectionEvidence:"Recent evidence",sectionMomentum:"Momentum core",sectionAttention:"Needs attention",noGoals:"No life goals are active yet. Start by defining the direction you want Forge to support.",noProjects:"No active projects yet. Add a project to turn a goal into practical work.",noFocus:"No focus tasks yet. Promote a task when you know what deserves attention next.",noEvidence:"No evidence has been recorded yet. Completed work and logged activity will appear here.",noProjectYet:"No project yet",noAttention:"No major drift signal right now. Forge will raise neglected goals here when they start slipping.",metricsLevel:"Level",metricsWeeklyXp:"Weekly XP",metricsFocusTasks:"Focus tasks",metricsOverdue:"Overdue"},todayPage:{heroEyebrow:"Today",heroEmptyTitle:"No daily direction yet",heroDescription:"Start a task, earn XP, and keep today's work clear.",emptyTitle:"No daily runway yet",emptyDescription:"Add goals, tasks, or reward targets so Forge can shape a useful day plan.",emptyAction:"Open life goals",commandEyebrow:"Today command",commandTitle:"Directive, daily quests, recovery, and finish line",commandDescription:"See the next useful move clearly and keep the day grounded in real work.",questsTitle:"Daily quests",questsEmpty:"No daily quests yet. They will appear once Forge has enough live work and reward context.",rewardsTitle:"Milestone rewards",rewardsEmpty:"No milestone rewards are active yet. Long-term rewards will appear here as progress structure grows.",signalDirective:"Directive",signalQuest:"Quest chain",signalComeback:"Recovery",signalFinish:"Finish line",noDirective:"Choose one clear task to anchor the day.",noQuest:"No active daily quest chain",noQuestDetail:"Daily quests should reinforce real work, not distract from it.",noComeback:"Recovery window is clear",noFinish:"Keep the day clean",noDirectiveDetail:"Promote a real task and Today will become sharper immediately.",noFinishDetail:"A good finish today should make tomorrow lighter, not noisier."},kanban:{heroEyebrow:"Task board",heroTitle:"Task board",heroDescription:"Use the board to move active work, review blocked items, and open task details when you need more context.",emptyTitle:"No board yet",emptyDescription:"Create your first task inside a project to start using the board.",emptyAction:"Open life goals",healthEyebrow:"Board status",healthTitle:"Visible work, focus, blockers, and completed work",healthDescription:"See what is active, what needs attention, and what has already been completed.",visibleWork:"Visible work",focusWork:"Current focus",blockedWork:"Blocked work",completedWork:"Completed work",visibleDetail:"{hidden} tasks are outside the current filters.",focusDetailReady:"These are the tasks most ready to be picked up next.",focusDetailEmpty:"Move one backlog task into focus to make the board more useful.",blockedDetail:"These tasks need a decision, an unblock, or a reset before they can move again.",blockedDetailEmpty:"No blocked tasks right now.",doneDetail:"Completed work stays here until you review it or reopen it.",doneDetailEmpty:"Nothing has been completed on this board yet.",boardFilters:"Board filters",filterGoal:"Goal",filterOwner:"Owner",allGoals:"All goals",allOwners:"All owners",noTasksMatch:"No tasks match these filters",noTasksMatchDescription:"These filters hide every task. Reset them to see the full board again.",taskContext:"Task details",evidence:"Recent activity",runHistory:"Run history",noTaskEvidence:"No activity has been recorded for this task yet.",noRunHistory:"No runs have been recorded for this task yet.",taskPlacement:"Task placement",projectLabel:"Project: {value}",goalLabel:"Life goal: {value}",ownerLabel:"Owner: {value}",dueLabel:"Due: {value}",openTask:"Open task",openProject:"Open project",openGoal:"Open life goal",noProjectLinked:"No project linked",noGoalLinked:"No life goal linked"},dailyRunway:{runwayEyebrow:"Today",runwayTitle:"Tasks for today",prioritiesOne:"{count} task",prioritiesOther:"{count} tasks",unassigned:"Unassigned",runwayItem:"Task {index}",noNote:"No note yet.",inspect:"Open task",actionBacklog:"Start",actionFocus:"Start",actionProgress:"Done",actionBlocked:"Start",timelineEyebrow:"By status",timelineTitle:"Tasks by status",emptyBucket:"Nothing here right now."},executionBoard:{laneBacklogTitle:"Backlog",laneBacklogDetail:"Not started yet",laneFocusTitle:"Focus",laneFocusDetail:"Ready to work on",laneProgressTitle:"In progress",laneProgressDetail:"Currently moving",laneBlockedTitle:"Blocked",laneBlockedDetail:"Needs attention",laneDoneTitle:"Done",laneDoneDetail:"Completed",noExecutionNote:"No note yet.",reopen:"Reopen",emptyLane:"No tasks in this lane.",deleteDropTitle:"Drop here to delete",deleteDropDetail:"Move this task into the Bin.",deleteConfirmTitle:"Delete task?",deleteConfirmDescription:'Move "{title}" to the Bin? You can restore it later from Settings.',deleteConfirmCheckbox:"Do not ask again",deleteConfirmCancel:"No",deleteConfirmSubmit:"Yes, delete",deletingTask:"Deleting…"},weeklyReview:{heroEyebrow:"Weekly review",heroDescription:"Review the week, note what moved, and decide what needs attention next.",summaryEyebrow:"Weekly summary",summaryTitle:"This week, wins, recovery, and next steps",summaryDescription:"Use this review to understand what happened this week and choose the most useful next move.",sectionMomentum:"Momentum summary",sectionGoals:"Goal check-in",sectionWins:"Wins",completionBonus:"Completion bonus",finalize:"Finish review",finalized:"Review finalized",finalizedDetail:"This cycle is already locked into evidence.",finalizePending:"Finalizing review",noWin:"No win recorded yet",noWinDetail:"If this week was quiet, use the review to capture one useful takeaway anyway.",noRecovery:"No recovery suggestion yet",noRecoveryDetail:"If the week felt steady, keep a light recovery option available for next week."},dialogs:{closeDialog:"Close dialog",task:{eyebrow:"Task",createTitle:"Create task",editTitle:"Edit task",description:"Use tasks for the next concrete step inside a project. Pick the project first so Forge can keep the larger context aligned.",project:"Project",selectProject:"Select a project",goal:"Life goal",title:"Title",descriptionLabel:"Description",owner:"Owner",xp:"XP",priority:"Priority",status:"Status",effort:"Effort",energy:"Energy",dueDate:"Due date",tags:"Tags",save:"Save task",create:"Create task"},project:{eyebrow:"Project",createTitle:"Create project",editTitle:"Edit project",description:"Use projects to turn a life goal into a concrete stream of work with tasks, evidence, and momentum.",goal:"Life goal",selectGoal:"Select a life goal",title:"Title",descriptionLabel:"Description",status:"Status",targetXp:"Target XP",themeColor:"Theme color",save:"Save project",create:"Create project",submitError:"Project update failed."},goal:{eyebrow:"Life goal",createTitle:"Create life goal",editTitle:"Edit life goal",description:"Use life goals to define what matters over the coming months or years before you break the path into projects.",title:"Title",descriptionLabel:"Description",horizon:"Horizon",status:"Status",targetXp:"Target XP",themeColor:"Theme color",tags:"Life domains and context",save:"Save life goal",create:"Create life goal",submitError:"Goal update failed."}},taskDetail:{eyebrow:"Task",errorEyebrow:"Task",emptyPayload:"Forge returned an empty task payload.",heroFallback:"Use this task page to update the work, move it forward, and keep its context clear.",commandEyebrow:"Task overview",commandTitle:"What this task is, what to do next, and where it fits",commandDescription:"Use this page to update the task itself and understand its surrounding context clearly.",signalState:"State",signalNext:"Next move",signalEvidence:"Recent activity",signalAnchor:"Connected project",noStateChange:"No state change needed",terminalStateDetail:"This task is already in a completed state unless you decide to reopen it.",noEvidence:"No recent activity yet",noEvidenceDetail:"Completed work, corrections, and logged sessions will appear here as the task moves.",noAnchor:"No connected project yet",linkAnchorDetail:"Connect this task to a project or life goal so Forge can show why it matters.",edit:"Edit task",deleteTask:"Delete",deleting:"Deleting…",deleteTaskConfirm:'Move "{title}" to the Bin? You can restore it later unless you permanently delete it from Settings.',openProject:"Open project",openGoal:"Open life goal",markNotCompleted:"Mark not completed",sectionStatus:"Task status",fieldProject:"Project",fieldGoal:"Life goal",fieldDueDate:"Due date",pendingMove:"Moving",actionBacklog:"Move to backlog",actionFocus:"Move to focus",actionProgress:"Start now",actionBlocked:"Mark blocked",actionDone:"Mark completed",sectionEvidence:"Recent activity",noVisibleEvidence:"No activity has been recorded for this task yet.",removeLog:"Remove log",openRelatedItem:"Open related item",sectionRuns:"Work sessions",noRuns:"No work sessions have been recorded for this task yet.",sectionMetadata:"More task details",metaOwner:"Owner: {value}",metaEffort:"Effort: {value}",metaEnergy:"Energy: {value}",metaCreated:"Created: {value}",metaUpdated:"Last updated: {value}",metaCompleted:"Completed at: {value}",metaNotCompleted:"Not completed"},projectDetail:{errorEyebrow:"Project",heroEyebrow:"Project",commandEyebrow:"Project status",commandTitle:"Momentum, next task, risk, and evidence",commandDescription:"Use this page to see what is moving, what needs attention next, and what evidence already supports the project.",signalMomentum:"Momentum",signalNext:"Next task",signalRisk:"Risk",signalEvidence:"Evidence",trackedTasksOne:"{count} tracked task",trackedTasksOther:"{count} tracked tasks",noNextTask:"No next task selected yet",noNextTaskDetail:"Pick or create a task so the project has a clear next move.",needsFocus:"Needs focus",noRisk:"No immediate risk signal",noRiskDetail:"Blocked or neglected work will appear here when the project starts drifting.",noEvidence:"No recent evidence yet",noEvidenceDetail:"Completed work and logged activity will appear here as the project moves.",compatibility:"Compatibility mode",compatibilityDescription:"This project comes from an older snapshot format. You can review it here, but editing the project itself needs the updated backend.",addTask:"Add task",editProject:"Edit project",suspendProject:"Suspend",suspending:"Suspending…",finishProject:"Finish",finishing:"Finishing…",restartProject:"Restart",restarting:"Restarting…",deleteProject:"Delete",deleting:"Deleting…",deleteProjectConfirm:'Move "{title}" to the Bin? You can restore it later unless you permanently delete it from Settings.',openGoal:"Open life goal",sectionHealth:"Project health",fieldStatus:"Status",fieldProgress:"Progress",fieldMomentum:"Momentum",sectionEvidence:"Recent evidence"},goalDetail:{eyebrow:"Life goal",missingTitle:"This life goal is not available",missingDescription:"Forge cannot find this life goal in the current snapshot. Return to the goals view and choose an active one.",backToGoals:"Back to goals",heroBadgeOne:"{count} project",heroBadgeOther:"{count} projects",commandEyebrow:"Goal status",commandTitle:"Progress, next push, risk, and evidence",commandDescription:"Use this page to see what is advancing the goal, what should move next, and where support is needed.",signalProgress:"Progress",signalNext:"Next push",signalRisk:"Risk",signalEvidence:"Evidence",progressTitle:"{progress}% with {count} completed tasks",progressDetail:"{xp} XP is already banked on this goal.",noProject:"No active project yet",noProjectDetail:"Add a project so this goal has a concrete execution path.",needsProject:"Needs project",nextMove:"Next move: {value}",noRisk:"No drift signal right now",noRiskDetail:"If this goal starts slipping, Forge will surface that pressure here.",noEvidence:"No recent evidence yet",noEvidenceDetail:"Completed tasks, project motion, and agent actions will appear here as proof of progress.",edit:"Edit life goal",addProject:"Add project",deleteGoal:"Delete",deleting:"Deleting…",deleteGoalConfirm:'Move "{title}" to the Bin? You can restore it later unless you permanently delete it from Settings.',sectionProjects:"Projects advancing this goal",noProjects:"This goal does not have an active project yet. Add one to turn the goal into practical motion.",addNextTask:"Add the next task",sectionHealth:"Goal health",fieldProgress:"Progress",fieldCompletedTasks:"Completed tasks",fieldXpBanked:"XP banked",sectionEvidence:"Recent evidence",noEvidenceLogged:"No evidence has been logged for this goal yet. Task completions, project updates, and agent actions will appear here."}}}}const Lh=Ah(),Dh={common:{actions:{cancel:"Annuler",close:"Fermer",create:"Créer",edit:"Modifier",inspect:"Inspecter",open:"Ouvrir",refresh:"Actualiser",retry:"Réessayer",save:"Enregistrer",reset:"Réinitialiser les filtres",view:"Voir"},labels:{loading:"Chargement",backgroundActivity:"Activité en arrière-plan",syncInProgress:"Synchronisation en cours",connectionState:"État de la connexion",errorCode:"Code d'erreur : {code}",noDate:"Aucune date",noProject:"Aucun projet lié",noGoal:"Aucun objectif de vie lié",noExecutionNote:"Aucune note d'exécution pour le moment.",noRunNote:"Aucune note d'exécution enregistrée.",released:"Libérée",stable:"Stable",timedOut:"Expirée",waiting:"En attente",today:"Aujourd'hui"},enums:{taskStatus:{backlog:"Backlog",focus:"Priorité",in_progress:"En cours",blocked:"Bloqué",done:"Terminé"},priority:{critical:"Critique",high:"Élevée",medium:"Moyenne",low:"Basse"},effort:{marathon:"Marathon",deep:"Approfondi",light:"Léger"},energy:{high:"Haute",steady:"Stable",low:"Basse"},projectStatus:{active:"Actif",paused:"Suspendu",completed:"Terminé"},goalHorizon:{quarter:"Trimestre",year:"Année",lifetime:"Vie entière"}},shell:{appName:"The Kinetic Forge",appMark:"FORGE",more:"Plus",command:"Commande",moreRoutesEyebrow:"Autres vues",moreRoutesTitle:"Parcourir Forge",moreRoutesDescription:"Utilisez ce panneau pour accéder aux vues secondaires sans surcharger la barre inférieure.",loadingEyebrow:"Forge",loadingTitle:"Chargement de Forge",loadingDescription:"Vérification de votre session opérateur et chargement du dernier instantané.",sessionEyebrow:"Session opérateur Forge",stateEyebrow:"État de Forge",settled:"À jour",savingOne:"Enregistrement de {count} modification",savingOther:"Enregistrement de {count} modifications",refreshingOne:"Actualisation de {count} vue",refreshingOther:"Actualisation de {count} vues",collapseSidebar:"Réduire la barre latérale",expandSidebar:"Déployer la barre latérale",rail:{taskBackToKanban:"Retour au Kanban",taskOpenToday:"Ouvrir Aujourd'hui",projectAll:"Tous les projets",projectGoals:"Architecture des objectifs",goalAll:"Tous les objectifs",goalProjects:"Projets actifs",psycheHub:"Hub Psyche",psycheReports:"Rapports",overview:"Vue d'ensemble",today:"Aujourd'hui"},momentum:{title:"Momentum",streak:"Série",xp:"XP",momentum:"Momentum",streakBadgeOne:"{count} jour de série",streakBadgeOther:"{count} jours de série",weeklyXp:"{count} XP cette semaine",liveMomentum:"{count}% de momentum",psycheMode:"Psyche active"}},routeLabels:{overview:"Vue d'ensemble",goals:"Objectifs",habits:"Habitudes",projects:"Projets",strategies:"Stratégies",preferences:"Préférences",calendar:"Calendrier",sleep:"Sommeil",sports:"Sport",kanban:"Kanban",today:"Aujourd'hui",notes:"Notes",wiki:"Wiki",psyche:"Psyche",activity:"Activité",insights:"Insights",review:"Revue",settings:"Réglages"},routeDetails:{overview:"Voyez les priorités, le momentum et les preuves récentes au même endroit.",goals:"Reliez la direction long terme au travail du quotidien.",habits:"Suivez les engagements récurrents et les rechutes avec des conséquences XP explicites.",projects:"Suivez les initiatives qui font avancer vos objectifs.",strategies:"Planifiez le chemin dirigé entre le travail actuel et l'état final.",preferences:"Modélisez les goûts, comparez les arbitrages et inspectez les preuves par contexte.",calendar:"Synchronisez les calendriers, définissez les blocs de travail et planifiez des timeboxes réelles.",sleep:"Inspectez le sommeil, la régularité et le contexte lié à Psyche.",sports:"Inspectez les entraînements, le volume et les métadonnées de réflexion.",kanban:"Faites progresser le travail actif sans perdre le contexte.",today:"Concentrez aujourd'hui sur le prochain mouvement le plus net.",notes:"Recherchez les notes Markdown et rouvrez vite le travail lié.",wiki:"Travaillez dans une mémoire explicite basée sur des fichiers avec backlinks, liens Forge et embeddings optionnels.",psyche:"Réfléchissez avec structure sur vos valeurs, vos schémas et vos rapports.",activity:"Relisez la trace visible de ce qui a changé et quand.",insights:"Stockez et relisez coaching, analyses et recommandations.",review:"Relisez la semaine et préparez la prochaine poussée.",settings:"Gérez la collaboration, la sécurité et vos préférences."},navigation:{openRoute:"Ouvrir {label}",create:"Créer",createTitle:"Créer dans Forge",createDescription:"Choisissez ce que vous voulez ajouter ensuite.",closeCreateMenu:"Fermer le menu de création",newGoal:"Nouvel objectif de vie",newGoalDescription:"Définir une direction à long terme.",newProject:"Nouveau projet",newProjectDescription:"Ajouter une initiative concrète sous un objectif de vie.",newTask:"Nouvelle tâche",newTaskDescription:"Capturer la prochaine étape actionnable dans un projet.",newStrategy:"Nouvelle stratégie",newStrategyDescription:"Ajouter un plan dirigé à travers projets et tâches."},commandPalette:{searchPlaceholder:"Aller à une vue, une page wiki, un objectif, un projet, une stratégie, l'espace préférences ou une tâche prioritaire",noResults:"Aucune commande ne correspond à cette recherche.",categoryRoute:"Vue",categoryGoal:"Objectif",categoryProject:"Projet",categoryTask:"Tâche",routeOverview:"Ouvrir la vue d'ensemble.",routeToday:"Ouvrir aujourd'hui.",routeKanban:"Ouvrir le tableau.",routeNotes:"Rechercher les notes.",routeWiki:"Ouvrir l'espace mémoire wiki.",routePsyche:"Ouvrir Psyche.",routeGoals:"Ouvrir vos objectifs de vie.",routeHabits:"Ouvrir vos habitudes.",routeProjects:"Ouvrir vos projets.",routeStrategies:"Ouvrir vos stratégies.",routePreferences:"Ouvrir l'espace préférences.",routeCalendar:"Ouvrir l'espace calendrier.",routeReview:"Ouvrir la revue hebdomadaire.",routeSettings:"Ouvrir les réglages.",openLifeGoal:"Ouvrir l'objectif de vie",openFocusTask:"Ouvrir la tâche prioritaire"},pageState:{loadingTitle:"Préparation en cours",loadingDescription:"Chargement des dernières données Forge pour cette vue."},settings:{localeLabel:"Langue",localeDescription:"Choisissez la langue utilisée dans Forge.",localeEnglish:"Anglais",localeFrench:"Français",localeSaved:"Langue enregistrée"},overview:{heroEyebrow:"Vue stratégique",heroEmptyTitle:"Prêt à démarrer",heroDescription:"Voyez vos objectifs, projets actifs, tâches en cours et preuves récentes au même endroit.",emptyTitle:"Pas encore de vue d'ensemble",emptyDescription:"Créez un objectif de vie, un projet ou une tâche pour donner à Forge une base réelle.",emptyAction:"Ouvrir les objectifs de vie",commandEyebrow:"Vue de commande",commandTitle:"Maintenant, ensuite, risques et preuves récentes",commandDescription:"Cette vue doit montrer ce qui mérite votre attention maintenant, ce qui vient ensuite, où la dérive apparaît et les progrès déjà visibles.",sectionGoals:"Objectifs de vie actifs",sectionProjects:"Projets actifs",sectionFocus:"Priorité du jour",sectionEvidence:"Preuves récentes",sectionMomentum:"Noyau de momentum",sectionAttention:"À surveiller",noGoals:"Aucun objectif de vie actif pour le moment. Commencez par définir la direction que Forge doit soutenir.",noProjects:"Aucun projet actif. Ajoutez un projet pour transformer un objectif en travail concret.",noFocus:"Aucune tâche prioritaire pour le moment. Faites passer une tâche en priorité quand vous savez quoi faire ensuite.",noEvidence:"Aucune preuve enregistrée pour le moment. Le travail accompli et l'activité journalisée apparaîtront ici.",noProjectYet:"Pas encore de projet",noAttention:"Aucun signal majeur de dérive pour le moment. Forge affichera ici les objectifs négligés.",metricsLevel:"Niveau",metricsWeeklyXp:"XP hebdo",metricsFocusTasks:"Tâches prioritaires",metricsOverdue:"En retard"},todayPage:{heroEyebrow:"Aujourd'hui",heroEmptyTitle:"Pas encore de direction du jour",heroDescription:"Commencez une tâche, gagnez de l'XP et gardez la journée claire.",emptyTitle:"Pas encore de piste du jour",emptyDescription:"Ajoutez des objectifs, des tâches ou des cibles de récompense pour que Forge puisse construire une journée utile.",emptyAction:"Ouvrir les objectifs de vie",commandEyebrow:"Commande du jour",commandTitle:"Directive, quêtes du jour, reprise et ligne d'arrivée",commandDescription:"Aujourd'hui doit rendre le prochain mouvement utile évident et garder la journée ancrée dans un vrai travail.",questsTitle:"Quêtes du jour",questsEmpty:"Pas encore de quêtes du jour. Elles apparaîtront quand Forge aura assez de travail réel et de contexte de récompense.",rewardsTitle:"Récompenses jalons",rewardsEmpty:"Aucune récompense jalon active pour le moment. Elles apparaîtront à mesure que la structure de progression se précise.",signalDirective:"Directive",signalQuest:"Chaîne de quêtes",signalComeback:"Reprise",signalFinish:"Ligne d'arrivée",noDirective:"Choisissez une tâche claire pour ancrer la journée.",noQuest:"Aucune chaîne de quêtes active",noQuestDetail:"Les quêtes du jour doivent renforcer le vrai travail, pas le détourner.",noComeback:"La fenêtre de reprise est claire",noFinish:"Gardez la journée nette",noDirectiveDetail:"Faites passer une vraie tâche en priorité et la vue Aujourd'hui deviendra plus nette.",noFinishDetail:"Une bonne fin de journée doit alléger demain, pas l'encombrer."},kanban:{heroEyebrow:"Tableau des tâches",heroTitle:"Tableau des tâches",heroDescription:"Utilisez le tableau pour faire avancer le travail actif, revoir les blocages et ouvrir les détails quand nécessaire.",emptyTitle:"Pas encore de tableau",emptyDescription:"Créez votre première tâche dans un projet pour commencer à utiliser le tableau.",emptyAction:"Ouvrir les objectifs de vie",healthEyebrow:"État du tableau",healthTitle:"Travail visible, priorité, blocages et travail terminé",healthDescription:"Le tableau doit montrer ce qui est actif, ce qui demande de l'attention et ce qui est déjà terminé.",visibleWork:"Travail visible",focusWork:"Priorité actuelle",blockedWork:"Travail bloqué",completedWork:"Travail terminé",visibleDetail:"{hidden} tâches sont hors des filtres actuels.",focusDetailReady:"Ce sont les tâches les plus prêtes à être reprises maintenant.",focusDetailEmpty:"Faites passer une tâche du backlog en priorité pour rendre le tableau plus utile.",blockedDetail:"Ces tâches ont besoin d'une décision, d'un déblocage ou d'une remise à plat avant d'avancer.",blockedDetailEmpty:"Aucune tâche bloquée pour le moment.",doneDetail:"Le travail terminé reste ici jusqu'à sa revue ou sa réouverture.",doneDetailEmpty:"Rien n'a encore été terminé sur ce tableau.",boardFilters:"Filtres du tableau",filterGoal:"Objectif",filterOwner:"Responsable",allGoals:"Tous les objectifs",allOwners:"Tous les responsables",noTasksMatch:"Aucune tâche ne correspond à ces filtres",noTasksMatchDescription:"Ces filtres masquent toutes les tâches. Réinitialisez-les pour revoir l'ensemble du tableau.",taskContext:"Détails de la tâche",evidence:"Activité récente",runHistory:"Historique d'exécution",noTaskEvidence:"Aucune activité n'a encore été enregistrée pour cette tâche.",noRunHistory:"Aucune exécution n'a encore été enregistrée pour cette tâche.",taskPlacement:"Placement de la tâche",projectLabel:"Projet : {value}",goalLabel:"Objectif de vie : {value}",ownerLabel:"Responsable : {value}",dueLabel:"Échéance : {value}",openTask:"Ouvrir la tâche",openProject:"Ouvrir le projet",openGoal:"Ouvrir l'objectif de vie",noProjectLinked:"Aucun projet lié",noGoalLinked:"Aucun objectif de vie lié"},dailyRunway:{runwayEyebrow:"Aujourd'hui",runwayTitle:"Tâches du jour",prioritiesOne:"{count} tâche",prioritiesOther:"{count} tâches",unassigned:"Non attribué",runwayItem:"Tâche {index}",noNote:"Aucune note pour le moment.",inspect:"Ouvrir la tâche",actionBacklog:"Commencer",actionFocus:"Commencer",actionProgress:"Terminer",actionBlocked:"Commencer",timelineEyebrow:"Par statut",timelineTitle:"Tâches par statut",emptyBucket:"Rien ici pour le moment."},executionBoard:{laneBacklogTitle:"Backlog",laneBacklogDetail:"Pas encore commencé",laneFocusTitle:"Priorité",laneFocusDetail:"Prêt à être traité",laneProgressTitle:"En cours",laneProgressDetail:"En mouvement",laneBlockedTitle:"Bloqué",laneBlockedDetail:"Demande de l'attention",laneDoneTitle:"Terminé",laneDoneDetail:"Achevé",noExecutionNote:"Aucune note pour le moment.",reopen:"Rouvrir",emptyLane:"Aucune tâche dans cette colonne.",deleteDropTitle:"Déposer ici pour supprimer",deleteDropDetail:"Déplacez cette tâche dans la corbeille.",deleteConfirmTitle:"Supprimer la tâche ?",deleteConfirmDescription:'Déplacer "{title}" vers la corbeille ? Vous pourrez la restaurer plus tard dans Réglages.',deleteConfirmCheckbox:"Ne plus demander",deleteConfirmCancel:"Non",deleteConfirmSubmit:"Oui, supprimer",deletingTask:"Suppression…"},weeklyReview:{heroEyebrow:"Revue hebdomadaire",heroDescription:"Relisez la semaine, notez ce qui a avancé et décidez de ce qui demande de l'attention ensuite.",summaryEyebrow:"Résumé hebdomadaire",summaryTitle:"Cette semaine, les progrès, la récupération et la suite",summaryDescription:"Utilisez cette revue pour comprendre la semaine et choisir le prochain mouvement utile.",sectionMomentum:"Résumé du momentum",sectionGoals:"Point sur les objectifs",sectionWins:"Progrès",completionBonus:"Bonus de complétion",finalize:"Terminer la revue",finalized:"Revue terminée",finalizedDetail:"Ce cycle est déjà consigné comme preuve.",finalizePending:"Finalisation de la revue",noWin:"Aucun progrès enregistré",noWinDetail:"Même si la semaine a été calme, notez au moins un apprentissage utile.",noRecovery:"Aucune suggestion de récupération",noRecoveryDetail:"Si la semaine a été stable, gardez malgré tout une option légère de récupération."},dialogs:{closeDialog:"Fermer la fenêtre",task:{eyebrow:"Tâche",createTitle:"Créer une tâche",editTitle:"Modifier la tâche",description:"Utilisez les tâches pour représenter la prochaine étape concrète dans un projet. Choisissez d'abord le projet pour garder le bon contexte.",project:"Projet",selectProject:"Sélectionner un projet",goal:"Objectif de vie",title:"Titre",descriptionLabel:"Description",owner:"Responsable",xp:"XP",priority:"Priorité",status:"Statut",effort:"Effort",energy:"Énergie",dueDate:"Date d'échéance",tags:"Tags",save:"Enregistrer la tâche",create:"Créer la tâche"},project:{eyebrow:"Projet",createTitle:"Créer un projet",editTitle:"Modifier le projet",description:"Utilisez les projets pour transformer un objectif de vie en flux de travail concret avec tâches, preuves et momentum.",goal:"Objectif de vie",selectGoal:"Sélectionner un objectif de vie",title:"Titre",descriptionLabel:"Description",status:"Statut",targetXp:"XP cible",themeColor:"Couleur du thème",save:"Enregistrer le projet",create:"Créer le projet",submitError:"La mise à jour du projet a échoué."},goal:{eyebrow:"Objectif de vie",createTitle:"Créer un objectif de vie",editTitle:"Modifier l'objectif de vie",description:"Utilisez les objectifs de vie pour définir ce qui compte sur les mois ou les années à venir avant de le décliner en projets.",title:"Titre",descriptionLabel:"Description",horizon:"Horizon",status:"Statut",targetXp:"XP cible",themeColor:"Couleur du thème",tags:"Domaines de vie et contexte",save:"Enregistrer l'objectif de vie",create:"Créer l'objectif de vie",submitError:"La mise à jour de l'objectif a échoué."}},taskDetail:{eyebrow:"Tâche",errorEyebrow:"Tâche",emptyPayload:"Forge a renvoyé une charge utile de tâche vide.",heroFallback:"Utilisez cette page pour mettre à jour la tâche, la faire avancer et garder son contexte clair.",commandEyebrow:"Commande de tâche",commandTitle:"Statut, prochaine action, preuves et contexte",commandDescription:"Cette page doit aider à modifier directement la tâche et à comprendre clairement son contexte.",signalState:"Statut",signalNext:"Prochaine action",signalEvidence:"Activité récente",signalAnchor:"Projet lié",noStateChange:"Aucun changement d'état nécessaire",terminalStateDetail:"Cette tâche est déjà dans un état terminé, sauf si vous décidez de la rouvrir.",noEvidence:"Aucune activité récente pour le moment",noEvidenceDetail:"Le travail terminé, les corrections et les sessions apparaîtront ici à mesure que la tâche avance.",noAnchor:"Aucun projet lié",linkAnchorDetail:"Reliez cette tâche à un projet ou à un objectif de vie pour que Forge puisse montrer pourquoi elle compte.",edit:"Modifier la tâche",deleteTask:"Supprimer",deleting:"Suppression…",deleteTaskConfirm:`Déplacer "{title}" vers la corbeille ? Vous pourrez la restaurer plus tard tant qu'elle n'est pas supprimée définitivement dans Réglages.`,openProject:"Ouvrir le projet",openGoal:"Ouvrir l'objectif de vie",markNotCompleted:"Marquer comme non terminée",sectionStatus:"Statut de la tâche",fieldProject:"Projet",fieldGoal:"Objectif de vie",fieldDueDate:"Date d'échéance",pendingMove:"Déplacement",actionBacklog:"Passer au backlog",actionFocus:"Passer en priorité",actionProgress:"Commencer maintenant",actionBlocked:"Marquer bloquée",actionDone:"Marquer terminée",sectionEvidence:"Activité récente",noVisibleEvidence:"Aucune activité n'a encore été enregistrée pour cette tâche.",removeLog:"Supprimer l'entrée",openRelatedItem:"Ouvrir l'élément lié",sectionRuns:"Sessions de travail",noRuns:"Aucune session de travail n'a encore été enregistrée pour cette tâche.",sectionMetadata:"Autres détails de la tâche",metaOwner:"Responsable : {value}",metaEffort:"Effort : {value}",metaEnergy:"Énergie : {value}",metaCreated:"Créée : {value}",metaUpdated:"Dernière mise à jour : {value}",metaCompleted:"Terminée le : {value}",metaNotCompleted:"Non terminée"},projectDetail:{errorEyebrow:"Projet",heroEyebrow:"Projet",commandEyebrow:"État du projet",commandTitle:"Momentum, prochaine tâche, risque et preuves",commandDescription:"Utilisez cette page pour voir ce qui avance, ce qui demande votre attention ensuite, et quelles preuves soutiennent déjà le projet.",signalMomentum:"Momentum",signalNext:"Prochaine tâche",signalRisk:"Risque",signalEvidence:"Preuves",trackedTasksOne:"{count} tâche suivie",trackedTasksOther:"{count} tâches suivies",noNextTask:"Aucune prochaine tâche choisie",noNextTaskDetail:"Choisissez ou créez une tâche pour donner au projet un prochain mouvement clair.",needsFocus:"Besoin de priorité",noRisk:"Aucun risque immédiat",noRiskDetail:"Le travail bloqué ou négligé apparaîtra ici si le projet commence à dériver.",noEvidence:"Aucune preuve récente",noEvidenceDetail:"Le travail terminé et l'activité enregistrée apparaîtront ici à mesure que le projet avance.",compatibility:"Mode de compatibilité",compatibilityDescription:"Ce projet provient d'un ancien format d'instantané. Vous pouvez le consulter ici, mais sa modification demande le backend mis à jour.",addTask:"Ajouter une tâche",editProject:"Modifier le projet",suspendProject:"Suspendre",suspending:"Suspension…",finishProject:"Terminer",finishing:"Finalisation…",restartProject:"Relancer",restarting:"Relance…",deleteProject:"Supprimer",deleting:"Suppression…",deleteProjectConfirm:`Déplacer "{title}" vers la corbeille ? Vous pourrez le restaurer plus tard tant qu'il n'est pas supprimé définitivement dans Réglages.`,openGoal:"Ouvrir l'objectif de vie",sectionHealth:"Santé du projet",fieldStatus:"Statut",fieldProgress:"Progression",fieldMomentum:"Momentum",sectionEvidence:"Preuves récentes"},goalDetail:{eyebrow:"Objectif de vie",missingTitle:"Cet objectif de vie n'est pas disponible",missingDescription:"Forge ne trouve pas cet objectif de vie dans l'instantané actuel. Revenez à la vue des objectifs et choisissez-en un actif.",backToGoals:"Retour aux objectifs",heroBadgeOne:"{count} projet",heroBadgeOther:"{count} projets",commandEyebrow:"État de l'objectif",commandTitle:"Progression, prochain élan, risque et preuves",commandDescription:"Utilisez cette page pour voir ce qui fait avancer l'objectif, ce qui doit bouger ensuite, et où du soutien est nécessaire.",signalProgress:"Progression",signalNext:"Prochain élan",signalRisk:"Risque",signalEvidence:"Preuves",progressTitle:"{progress}% avec {count} tâches terminées",progressDetail:"{xp} XP sont déjà cumulés sur cet objectif.",noProject:"Aucun projet actif pour le moment",noProjectDetail:"Ajoutez un projet pour donner à cet objectif un chemin d'exécution concret.",needsProject:"Projet nécessaire",nextMove:"Prochaine action : {value}",noRisk:"Aucun signal de dérive pour le moment",noRiskDetail:"Si cet objectif commence à glisser, Forge affichera cette pression ici.",noEvidence:"Aucune preuve récente",noEvidenceDetail:"Les tâches terminées, le mouvement des projets et les actions d'agents apparaîtront ici comme preuve de progression.",edit:"Modifier l'objectif de vie",addProject:"Ajouter un projet",deleteGoal:"Supprimer",deleting:"Suppression…",deleteGoalConfirm:`Déplacer "{title}" vers la corbeille ? Vous pourrez le restaurer plus tard tant qu'il n'est pas supprimé définitivement dans Réglages.`,sectionProjects:"Projets qui font avancer cet objectif",noProjects:"Cet objectif n'a pas encore de projet actif. Ajoutez-en un pour le transformer en mouvement concret.",addNextTask:"Ajouter la prochaine tâche",sectionHealth:"Santé de l'objectif",fieldProgress:"Progression",fieldCompletedTasks:"Tâches terminées",fieldXpBanked:"XP cumulés",sectionEvidence:"Preuves récentes",noEvidenceLogged:"Aucune preuve n'a encore été enregistrée pour cet objectif. Les tâches terminées, les mises à jour de projet et les actions d'agents apparaîtront ici."}}},Zr={en:Lh,fr:Dh};function el(t,s){const i=s.split(".");let n=t;for(const a of i){if(!n||typeof n=="string")return;n=n[a]}return typeof n=="string"?n:void 0}function $h(t,s){return s?t.replace(/\{(\w+)\}/g,(i,n)=>{const a=s[n];return a==null?"":String(a)}):t}function Pa(t,s,i){const n=el(Zr[t],s),a=el(Zr.en,s);return $h(n??a??s,i)}const Oh={locale:"en",t:(t,s)=>Pa("en",t,s),formatDate:t=>t?new Intl.DateTimeFormat("en",{month:"short",day:"numeric"}).format(new Date(`${t}T00:00:00.000Z`)):Pa("en","common.labels.noDate"),formatDateTime:t=>new Intl.DateTimeFormat("en",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(t)),formatNumber:t=>new Intl.NumberFormat("en").format(t)},ud=c.createContext(null);function Fh({children:t,locale:s}){const i=c.useMemo(()=>({locale:s,t:(n,a)=>Pa(s,n,a),formatDate:n=>n?new Intl.DateTimeFormat(s,{month:"short",day:"numeric"}).format(new Date(`${n}T00:00:00.000Z`)):Pa(s,"common.labels.noDate"),formatDateTime:n=>new Intl.DateTimeFormat(s,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(n)),formatNumber:n=>new Intl.NumberFormat(s).format(n)}),[s]);return e.jsx(ud.Provider,{value:i,children:t})}function at(){return c.useContext(ud)??Oh}function tl({active:t,label:s,className:i,onClick:n}){const{t:a}=at();return e.jsxs(wt.button,{type:"button",initial:!1,animate:{opacity:t?1:.55,y:0,scale:t?1:.98},transition:{duration:.24,ease:"easeOut"},onClick:n,className:re("surface-pulse ambient-glow inline-flex min-h-11 shrink-0 items-center gap-2.5 rounded-full border border-white/8 px-4 py-2 text-left shadow-[0_18px_40px_rgba(3,8,18,0.22)] backdrop-blur-xl transition hover:border-white/14 hover:bg-white/[0.03]",n?"cursor-pointer":"cursor-default",i),"aria-live":"polite","aria-label":`${a("common.labels.backgroundActivity")}: ${s}`,children:[e.jsx(tr,{tone:"subtle",className:t?"opacity-100":"opacity-45"}),e.jsxs("div",{className:"inline-flex min-w-0 items-center gap-2 whitespace-nowrap",children:[e.jsx("span",{className:"type-label text-white/56",children:a("common.labels.backgroundActivity")}),e.jsx("span",{className:"text-white/30",children:"•"}),e.jsx("span",{className:"truncate text-sm text-white/80",children:s})]})]})}function O({className:t,tone:s="default",size:i="md",wrap:n=!1,...a}){return e.jsx("span",{className:re("inline-flex max-w-full items-center rounded-full border border-white/8 bg-white/6 font-medium text-white/78",n?"whitespace-normal break-words [overflow-wrap:anywhere]":"overflow-hidden text-ellipsis whitespace-nowrap",i==="sm"?"min-h-7 px-2.5 py-1 text-[12px]":"min-h-8 px-3 py-1.5 text-[12px]",s==="meta"&&"bg-white/[0.04] text-white/58",s==="signal"&&"bg-[rgba(192,193,255,0.12)] text-white/86",t),...a})}const _h=["goal","project","task","strategy","habit","value","pattern","behavior","belief","mode","report"],Rh={goal:{kind:"goal",label:"Goal",icon:Oa,iconClassName:"text-amber-100",nameClassName:"text-amber-100",badgeClassName:"border-amber-300/24 bg-[linear-gradient(135deg,rgba(251,191,36,0.24),rgba(251,191,36,0.08))] text-amber-50",subtleBadgeClassName:"border-amber-300/18 bg-[rgba(251,191,36,0.08)] text-amber-100",buttonClassName:"border-amber-300/20 bg-[rgba(251,191,36,0.12)] text-amber-50 hover:bg-[rgba(251,191,36,0.18)]"},project:{kind:"project",label:"Project",icon:sm,iconClassName:"text-sky-100",nameClassName:"text-sky-100",badgeClassName:"border-sky-300/24 bg-[linear-gradient(135deg,rgba(56,189,248,0.22),rgba(56,189,248,0.08))] text-sky-50",subtleBadgeClassName:"border-sky-300/18 bg-[rgba(56,189,248,0.08)] text-sky-100",buttonClassName:"border-sky-300/20 bg-[rgba(56,189,248,0.12)] text-sky-50 hover:bg-[rgba(56,189,248,0.18)]"},task:{kind:"task",label:"Task",icon:tm,iconClassName:"text-indigo-100",nameClassName:"text-indigo-100",badgeClassName:"border-indigo-300/24 bg-[linear-gradient(135deg,rgba(129,140,248,0.22),rgba(129,140,248,0.08))] text-indigo-50",subtleBadgeClassName:"border-indigo-300/18 bg-[rgba(129,140,248,0.08)] text-indigo-100",buttonClassName:"border-indigo-300/20 bg-[rgba(129,140,248,0.12)] text-indigo-50 hover:bg-[rgba(129,140,248,0.18)]"},strategy:{kind:"strategy",label:"Strategy",icon:Qn,iconClassName:"text-cyan-100",nameClassName:"text-cyan-100",badgeClassName:"border-cyan-300/24 bg-[linear-gradient(135deg,rgba(34,211,238,0.22),rgba(34,211,238,0.08))] text-cyan-50",subtleBadgeClassName:"border-cyan-300/18 bg-[rgba(34,211,238,0.08)] text-cyan-100",buttonClassName:"border-cyan-300/20 bg-[rgba(34,211,238,0.12)] text-cyan-50 hover:bg-[rgba(34,211,238,0.18)]"},habit:{kind:"habit",label:"Habit",icon:em,iconClassName:"text-teal-100",nameClassName:"text-teal-100",badgeClassName:"border-teal-300/24 bg-[linear-gradient(135deg,rgba(45,212,191,0.22),rgba(45,212,191,0.08))] text-teal-50",subtleBadgeClassName:"border-teal-300/18 bg-[rgba(45,212,191,0.08)] text-teal-100",buttonClassName:"border-teal-300/20 bg-[rgba(45,212,191,0.12)] text-teal-50 hover:bg-[rgba(45,212,191,0.18)]"},value:{kind:"value",label:"Value",icon:Zc,iconClassName:"text-emerald-100",nameClassName:"text-emerald-100",badgeClassName:"border-emerald-300/24 bg-[linear-gradient(135deg,rgba(52,211,153,0.24),rgba(52,211,153,0.08))] text-emerald-50",subtleBadgeClassName:"border-emerald-300/18 bg-[rgba(52,211,153,0.08)] text-emerald-100",buttonClassName:"border-emerald-300/20 bg-[rgba(52,211,153,0.12)] text-emerald-50 hover:bg-[rgba(52,211,153,0.18)]"},pattern:{kind:"pattern",label:"Pattern",icon:Un,iconClassName:"text-rose-100",nameClassName:"text-rose-100",badgeClassName:"border-rose-300/24 bg-[linear-gradient(135deg,rgba(251,113,133,0.24),rgba(251,113,133,0.08))] text-rose-50",subtleBadgeClassName:"border-rose-300/18 bg-[rgba(251,113,133,0.08)] text-rose-100",buttonClassName:"border-rose-300/20 bg-[rgba(251,113,133,0.12)] text-rose-50 hover:bg-[rgba(251,113,133,0.18)]"},behavior:{kind:"behavior",label:"Behavior",icon:Vc,iconClassName:"text-orange-100",nameClassName:"text-orange-100",badgeClassName:"border-orange-300/24 bg-[linear-gradient(135deg,rgba(251,146,60,0.24),rgba(251,146,60,0.08))] text-orange-50",subtleBadgeClassName:"border-orange-300/18 bg-[rgba(251,146,60,0.08)] text-orange-100",buttonClassName:"border-orange-300/20 bg-[rgba(251,146,60,0.12)] text-orange-50 hover:bg-[rgba(251,146,60,0.18)]"},belief:{kind:"belief",label:"Belief",icon:Yc,iconClassName:"text-violet-100",nameClassName:"text-violet-100",badgeClassName:"border-violet-300/24 bg-[linear-gradient(135deg,rgba(167,139,250,0.24),rgba(167,139,250,0.08))] text-violet-50",subtleBadgeClassName:"border-violet-300/18 bg-[rgba(167,139,250,0.08)] text-violet-100",buttonClassName:"border-violet-300/20 bg-[rgba(167,139,250,0.12)] text-violet-50 hover:bg-[rgba(167,139,250,0.18)]"},mode:{kind:"mode",label:"Mode",icon:Jc,iconClassName:"text-fuchsia-100",nameClassName:"text-fuchsia-100",badgeClassName:"border-fuchsia-300/24 bg-[linear-gradient(135deg,rgba(217,70,239,0.24),rgba(217,70,239,0.08))] text-fuchsia-50",subtleBadgeClassName:"border-fuchsia-300/18 bg-[rgba(217,70,239,0.08)] text-fuchsia-100",buttonClassName:"border-fuchsia-300/20 bg-[rgba(217,70,239,0.12)] text-fuchsia-50 hover:bg-[rgba(217,70,239,0.18)]"},report:{kind:"report",label:"Report",icon:Kn,iconClassName:"text-blue-100",nameClassName:"text-blue-100",badgeClassName:"border-blue-300/24 bg-[linear-gradient(135deg,rgba(96,165,250,0.24),rgba(96,165,250,0.08))] text-blue-50",subtleBadgeClassName:"border-blue-300/18 bg-[rgba(96,165,250,0.08)] text-blue-100",buttonClassName:"border-blue-300/20 bg-[rgba(96,165,250,0.12)] text-blue-50 hover:bg-[rgba(96,165,250,0.18)]"}};function Ts(t){return Rh[t]}function zh(t){return _h.includes(t)}function Ki(t,s){const i=Ts(t);return s?`border ${i.buttonClassName}`:"border border-white/8 bg-white/[0.05] text-white/62 hover:bg-white/[0.08] hover:text-white"}function ke({kind:t,label:s,compact:i=!1,showIcon:n=!0,iconOnly:a=!1,gradient:r=!0,wrap:l=!1,className:d,...o}){const x=Ts(t),f=x.icon;return e.jsxs(O,{size:i?"sm":"md",wrap:l,className:re("max-w-full min-w-0 gap-1.5 border font-medium",r?x.badgeClassName:x.subtleBadgeClassName,i&&!a&&"px-2.5",a&&"px-2.5",d),...o,children:[n?e.jsx(f,{className:re("size-3.5 shrink-0",x.iconClassName)}):null,a?null:e.jsx("span",{className:re("min-w-0 max-w-full",l?"whitespace-normal break-words [overflow-wrap:anywhere]":"truncate"),children:s??x.label})]})}const qh={sm:"text-base",md:"text-lg",lg:"text-2xl",xl:"text-3xl"},sn={1:"truncate whitespace-nowrap",2:"overflow-hidden whitespace-normal [display:-webkit-box] [-webkit-box-orient:vertical] [-webkit-line-clamp:2]",3:"overflow-hidden whitespace-normal [display:-webkit-box] [-webkit-box-orient:vertical] [-webkit-line-clamp:3]"};function _e({kind:t,label:s,variant:i="inline",size:n="md",showKind:a=!1,showIcon:r=!0,showBadge:l=!1,badgeLabel:d,badgeCompact:o=!0,badgeGradient:x=!1,lines:f=1,labelClassName:b,className:m,...h}){const p=Ts(t),w=p.icon;return i==="pill"?e.jsxs("span",{className:re("inline-flex max-w-full items-center gap-2 rounded-full border px-4 py-2 font-medium shadow-[0_10px_28px_rgba(3,8,18,0.18)]",p.badgeClassName,m),...h,children:[r?e.jsx(w,{className:re("size-4 shrink-0",p.iconClassName)}):null,e.jsx("span",{className:re("min-w-0 max-w-full",sn[f],b),children:s})]}):i==="heading"?e.jsxs("span",{className:re("inline-flex max-w-full min-w-0 items-center gap-3",m),...h,children:[l?e.jsx(ke,{kind:t,label:d??p.label,compact:o,gradient:x,className:"shrink-0"}):null,a&&!l?e.jsx(ke,{kind:t,label:d??p.label,compact:!0,gradient:!1,className:"shrink-0"}):null,e.jsx("span",{className:re("min-w-0 max-w-full font-display leading-tight",qh[n],sn[f],p.nameClassName,b),children:s})]}):e.jsxs("span",{className:re("inline-flex max-w-full min-w-0 items-center gap-2",m),...h,children:[r?e.jsx(w,{className:re("size-4 shrink-0",p.iconClassName)}):null,l?e.jsx(ke,{kind:t,label:d??p.label,compact:o,gradient:x,className:"shrink-0"}):null,a?e.jsx("span",{className:re("text-sm font-medium",p.nameClassName),children:p.label}):null,e.jsx("span",{className:re("min-w-0 max-w-full",sn[f],p.nameClassName,b),children:s})]})}function ie({className:t,size:s,...i}){return e.jsx("input",{...i,className:re("interactive-tap w-full rounded-[22px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none ring-0 placeholder:text-white/35 focus:border-[rgba(192,193,255,0.35)]",t)})}function pd(t){return t.map(s=>(s==null?void 0:s.trim())??"").filter(Boolean)}function xd(t){return Array.isArray(t)?t:[]}function Nt(t){const s=xd(t);return s.length===1?s[0]:null}function Qt(t){return t?`${t.displayName} · ${t.kind}${t.handle?` · @${t.handle}`:""}`:""}function ss(t,s="Default Forge owner"){return t?`Suggested owner: ${t.displayName} · ${t.kind}`:s}function Je(t,s){const i=Qt(s);return i?`${t} · ${i}`:t}function Be(t,s,i="No description yet."){return pd([t,Qt(s)]).join(" · ")||i}function qe(t,s){const i=s&&"user"in s?s.user:s;return pd([...t,i==null?void 0:i.displayName,i==null?void 0:i.handle,i==null?void 0:i.kind,i==null?void 0:i.description]).join(" ").toLowerCase()}function Bh({open:t,onOpenChange:s,snapshot:i}){const n=ht(),{t:a}=at(),[r,l]=c.useState("");c.useEffect(()=>{t||l("")},[t]);const d=c.useMemo(()=>[...[{id:"route-overview",title:a("common.routeLabels.overview"),detail:a("common.commandPalette.routeOverview"),href:"/overview",category:a("common.commandPalette.categoryRoute")},{id:"route-today",title:a("common.routeLabels.today"),detail:a("common.commandPalette.routeToday"),href:"/today",category:a("common.commandPalette.categoryRoute")},{id:"route-kanban",title:a("common.routeLabels.kanban"),detail:a("common.commandPalette.routeKanban"),href:"/kanban",category:a("common.commandPalette.categoryRoute")},{id:"route-psyche",title:a("common.routeLabels.psyche"),detail:a("common.commandPalette.routePsyche"),href:"/psyche",category:a("common.commandPalette.categoryRoute")},{id:"route-notes",title:a("common.routeLabels.notes"),detail:a("common.commandPalette.routeNotes"),href:"/notes",category:a("common.commandPalette.categoryRoute")},{id:"route-wiki",title:a("common.routeLabels.wiki"),detail:a("common.commandPalette.routeWiki"),href:"/wiki",category:a("common.commandPalette.categoryRoute")},{id:"route-goals",title:a("common.routeLabels.goals"),detail:a("common.commandPalette.routeGoals"),href:"/goals",category:a("common.commandPalette.categoryRoute")},{id:"route-habits",title:a("common.routeLabels.habits"),detail:a("common.commandPalette.routeHabits"),href:"/habits",category:a("common.commandPalette.categoryRoute")},{id:"route-projects",title:a("common.routeLabels.projects"),detail:a("common.commandPalette.routeProjects"),href:"/projects",category:a("common.commandPalette.categoryRoute")},{id:"route-strategies",title:a("common.routeLabels.strategies"),detail:a("common.commandPalette.routeStrategies"),href:"/strategies",category:a("common.commandPalette.categoryRoute")},{id:"route-preferences",title:a("common.routeLabels.preferences"),detail:a("common.commandPalette.routePreferences"),href:"/preferences",category:a("common.commandPalette.categoryRoute")},{id:"route-calendar",title:a("common.routeLabels.calendar"),detail:a("common.commandPalette.routeCalendar"),href:"/calendar",category:a("common.commandPalette.categoryRoute")},{id:"route-review",title:a("common.routeLabels.review"),detail:a("common.commandPalette.routeReview"),href:"/review/weekly",category:a("common.commandPalette.categoryRoute")},{id:"route-settings",title:a("common.routeLabels.settings"),detail:a("common.commandPalette.routeSettings"),href:"/settings",category:a("common.commandPalette.categoryRoute")}],...i.dashboard.goals.slice(0,6).map(f=>({id:`goal-${f.id}`,title:f.title,detail:Qt(f.user)||a("common.commandPalette.openLifeGoal"),href:`/goals/${f.id}`,category:a("common.commandPalette.categoryGoal"),kind:"goal"})),...i.dashboard.projects.slice(0,6).map(f=>({id:`project-${f.id}`,title:f.title,detail:[f.goalTitle,Qt(f.user)].filter(Boolean).join(" · "),href:`/projects/${f.id}`,category:a("common.commandPalette.categoryProject"),kind:"project"})),...i.strategies.slice(0,6).map(f=>({id:`strategy-${f.id}`,title:f.title,detail:[`Alignment ${f.metrics.alignmentScore}%`,Qt(f.user)].filter(Boolean).join(" · "),href:`/strategies/${f.id}`,category:"Strategy",kind:"strategy"})),...i.overview.topTasks.slice(0,8).map(f=>({id:`task-${f.id}`,title:f.title,detail:Qt(f.user)||a("common.commandPalette.openFocusTask"),href:`/tasks/${f.id}`,category:a("common.commandPalette.categoryTask"),kind:"task"}))],[i,a]),o=c.useMemo(()=>{const x=r.trim().toLowerCase();return x?d.filter(f=>`${f.title} ${f.detail} ${f.category}`.toLowerCase().includes(x)).slice(0,12):d.slice(0,12)},[d,r]);return e.jsx(Lt,{open:t,onOpenChange:s,children:e.jsxs(Dt,{children:[e.jsx($t,{className:"fixed inset-0 z-40 bg-[rgba(5,10,18,0.68)] backdrop-blur-xl"}),e.jsxs(Ot,{className:"fixed inset-x-4 top-[12vh] z-50 mx-auto max-w-2xl overflow-hidden rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(20,28,42,0.98),rgba(12,17,30,0.98))] shadow-[0_32px_90px_rgba(3,8,18,0.45)]",children:[e.jsxs("div",{className:"border-b border-white/8 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 rounded-[22px] bg-white/[0.04] px-4 py-3",children:[e.jsx(dt,{className:"size-4 text-white/42"}),e.jsx(ie,{autoFocus:!0,value:r,onChange:x=>l(x.target.value),placeholder:a("common.commandPalette.searchPlaceholder"),className:"border-0 bg-transparent px-0 py-0 focus:border-0"})]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2 text-white/50",children:[{label:a("common.routeLabels.overview"),icon:Ro},{label:a("common.routeLabels.today"),icon:yi},{label:a("common.routeLabels.kanban"),icon:Gi},{label:a("common.routeLabels.notes"),icon:Wn},{label:a("common.routeLabels.wiki"),icon:Gn},{label:a("common.routeLabels.psyche"),icon:Hn},{label:a("common.routeLabels.goals"),icon:Oa},{label:a("common.routeLabels.habits"),icon:Un},{label:a("common.routeLabels.projects"),icon:zo},{label:a("common.routeLabels.strategies"),icon:Qn},{label:a("common.routeLabels.preferences"),icon:Fa},{label:a("common.routeLabels.calendar"),icon:us},{label:a("common.routeLabels.settings"),icon:Xn}].map(x=>e.jsxs("span",{className:"inline-flex min-h-10 items-center gap-2 rounded-full bg-white/[0.04] px-3 py-2 text-xs text-white/58",children:[e.jsx(x.icon,{className:"size-3.5"}),x.label]},x.label))})]}),e.jsx("div",{className:"max-h-[60vh] overflow-y-auto p-3",children:e.jsxs("div",{className:"grid gap-2",children:[o.map(x=>e.jsx("button",{type:"button",className:"interactive-tap rounded-[22px] bg-white/[0.04] px-4 py-3 text-left transition hover:bg-white/[0.07]",onClick:()=>{s(!1),n(x.href)},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/46",children:x.category}),e.jsx("div",{className:"mt-1 type-title-md text-white",children:x.kind?e.jsx(_e,{kind:x.kind,label:x.title}):x.title}),e.jsx("div",{className:"mt-1 text-sm text-white/58",children:x.detail})]}),e.jsx(Gs,{className:"size-4 text-white/35"})]})},x.id)),o.length===0?e.jsx("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-5 text-sm text-white/56",children:a("common.commandPalette.noResults")}):null]})})]})]})})}function sl({routeKey:t,tone:s="core",children:i}){return e.jsx(wt.div,{"data-route-key":t,"data-route-tone":s,className:"w-full max-w-full min-w-0",initial:!1,animate:{opacity:1,y:0},transition:{duration:.12,ease:"easeOut"},children:i})}const Kh=im("inline-flex min-w-0 max-w-full items-center justify-center gap-2 overflow-hidden whitespace-nowrap rounded-[var(--radius-control)] font-medium leading-none transition focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[rgba(192,193,255,0.45)] disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{primary:"bg-[linear-gradient(135deg,rgba(192,193,255,0.36),rgba(192,193,255,0.22))] text-white shadow-[0_12px_30px_rgba(192,193,255,0.08)]",secondary:"bg-white/8 text-white hover:bg-white/12",ghost:"bg-transparent text-[var(--primary)] hover:bg-white/6"},size:{sm:"min-h-[2.125rem] px-2.5 py-[0.4375rem] text-[13px]",md:"interactive-tap min-h-10 px-3 py-2 text-[13px]",lg:"min-h-11 px-4 py-2.5 text-sm"}},defaultVariants:{variant:"primary",size:"md"}});function W({className:t,variant:s,size:i,pending:n=!1,pendingLabel:a,children:r,disabled:l,...d}){return e.jsxs("button",{className:re(Kh({variant:s,size:i}),t),disabled:l||n,"aria-busy":n,...d,children:[n?e.jsx(tr,{className:"size-3.5",tone:"subtle"}):null,e.jsx("span",{className:"inline-flex min-w-0 max-w-full items-center gap-2 overflow-hidden truncate whitespace-nowrap",children:n&&a?a:r})]})}function Ra({open:t,onOpenChange:s,eyebrow:i,title:n,description:a,children:r}){const{t:l}=at();return e.jsx(Lt,{open:t,onOpenChange:s,children:e.jsxs(Dt,{children:[e.jsx($t,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.72)] backdrop-blur-xl"}),e.jsxs(Ot,{className:"fixed inset-x-4 bottom-4 top-4 z-50 mx-auto flex max-w-xl flex-col overflow-hidden rounded-[32px] border border-white/8 bg-[linear-gradient(180deg,rgba(20,28,42,0.98),rgba(12,17,30,0.98))] shadow-[0_32px_90px_rgba(3,8,18,0.45)]",children:[e.jsx("div",{className:"border-b border-white/8 px-5 py-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"type-label text-white/46",children:i}),e.jsx(Rt,{className:"mt-2 type-display-section text-white",children:n}),a?e.jsx(Gt,{className:"mt-3 type-body text-white/64",children:a}):null]}),e.jsx(W,{variant:"secondary",onClick:()=>s(!1),children:l("common.actions.close")})]})}),e.jsx("div",{className:"min-h-0 flex-1 overflow-x-hidden overflow-y-auto p-4",children:r})]})]})})}function Ps({children:t,className:s}){return e.jsx("div",{className:re("text-sm leading-6 text-white/50",s),children:t})}function Xe({content:t,label:s="Explain this field",className:i}){const[n,a]=c.useState(!1),r=c.useRef(null),l=c.useId();return c.useEffect(()=>{if(!n)return;const d=o=>{var x;(x=r.current)!=null&&x.contains(o.target)||a(!1)};return document.addEventListener("pointerdown",d),()=>document.removeEventListener("pointerdown",d)},[n]),e.jsxs("span",{ref:r,className:re("relative inline-flex items-center",i),onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":n?l:void 0,"aria-expanded":n,className:"inline-flex size-5 items-center justify-center rounded-full text-white/42 transition hover:bg-white/[0.06] hover:text-white/78 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[rgba(192,193,255,0.35)]",onFocus:()=>a(!0),onBlur:()=>a(!1),onClick:()=>a(d=>!d),children:e.jsx(am,{className:"size-3.5"})}),e.jsx("span",{id:l,role:"tooltip",className:re("pointer-events-none absolute right-0 top-[calc(100%+0.55rem)] z-40 w-[min(16rem,calc(100vw-2.5rem))] max-w-[calc(100vw-2.5rem)] rounded-[18px] border border-white/8 bg-[rgba(12,17,30,0.96)] px-3 py-2.5 text-sm leading-6 text-white/74 shadow-[0_18px_48px_rgba(3,8,18,0.42)] transition",n?"translate-y-0 opacity-100":"translate-y-1 opacity-0"),children:t})]})}const il="(max-width: 1023px)";function Uh(){const[t,s]=c.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(il).matches);return c.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const i=window.matchMedia(il),n=a=>{s(a.matches)};return s(i.matches),typeof i.addEventListener=="function"?(i.addEventListener("change",n),()=>i.removeEventListener("change",n)):(i.addListener(n),()=>i.removeListener(n))},[]),t}function Y({label:t,description:s,labelHelp:i,hint:n,error:a,children:r}){return e.jsxs("label",{className:"grid gap-2",children:[e.jsxs("span",{className:"flex items-center gap-2 text-sm font-medium text-white",children:[e.jsx("span",{children:t}),i?e.jsx(Xe,{content:i,label:`Explain ${t}`}):null]}),s?e.jsx("span",{className:"text-sm leading-6 text-white/54",children:s}):null,r,n?e.jsx(Ps,{children:n}):null,a?e.jsx("span",{className:"text-sm text-rose-300",children:a}):null]})}function tt({options:t,value:s,onChange:i,columns:n=2}){return e.jsx("div",{className:re("grid gap-3",n===3?"md:grid-cols-3":"md:grid-cols-2"),children:t.map(a=>{const r=a.value===s;return e.jsxs("button",{type:"button",className:re("rounded-[22px] border px-4 py-4 text-left transition",r?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.14)] text-white shadow-[0_18px_36px_rgba(5,12,24,0.24)]":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"),onClick:()=>i(a.value),children:[e.jsx("div",{className:"font-medium",children:a.label}),a.description?e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:a.description}):null]},a.value)})})}function it({open:t,onOpenChange:s,eyebrow:i,title:n,description:a,value:r,onChange:l,steps:d,onSubmit:o,submitLabel:x,pending:f=!1,pendingLabel:b,error:m,resolveError:h,initialStepId:p,contentClassName:w}){const{t:v}=at(),I=Uh(),[k,S]=c.useState(0),M=c.useRef(t),P=c.useRef(p),y=d[k];c.useEffect(()=>{const j=M.current,L=P.current!==p;if(M.current=t,P.current=p,!t){S(0);return}if(!j||L){if(p){const q=d.findIndex(G=>G.id===p);S(q>=0?q:0);return}S(0);return}if(k>=d.length){S(Math.max(0,d.length-1));return}if(!y&&p){const q=d.findIndex(G=>G.id===p);S(q>=0?q:0)}},[p,t,y,k,d]);const N=j=>{l({...r,...j})},A=d.length,T=A===0?0:(k+1)/A*100,F=y?h==null?void 0:h(y.id):void 0,u=F===void 0?m:F;return e.jsx(Lt,{open:t,onOpenChange:s,children:e.jsxs(Dt,{children:[e.jsx($t,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.72)] backdrop-blur-xl"}),e.jsxs(Ot,{"data-testid":"question-flow-dialog",className:re("fixed z-50 flex flex-col overflow-hidden border border-white/8 bg-[linear-gradient(180deg,rgba(21,28,44,0.985),rgba(12,17,30,0.985))] shadow-[0_30px_90px_rgba(3,8,18,0.45)]",I?"inset-x-3 bottom-3 top-4 rounded-[30px]":"left-1/2 top-1/2 h-[min(52rem,calc(100vh-1rem))] w-[min(56rem,calc(100vw-1.5rem))] -translate-x-1/2 -translate-y-1/2 rounded-[34px]",w),children:[e.jsx(Rt,{className:"sr-only",children:n}),e.jsx(Gt,{className:"sr-only",children:a}),e.jsx("div",{className:"sticky top-0 z-10 border-b border-white/8 bg-[rgba(12,17,30,0.9)] px-4 py-2.5 backdrop-blur-xl md:px-6",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-[11px] uppercase tracking-[0.18em] text-white/42",children:[e.jsx("span",{className:"truncate",children:i}),e.jsxs("span",{className:"whitespace-nowrap",children:["Step ",k+1," of ",A]})]}),e.jsx("div",{className:"mt-2 h-1.5 rounded-full bg-white/[0.06]",children:e.jsx(wt.div,{className:"h-full rounded-full bg-[linear-gradient(90deg,rgba(192,193,255,0.9),rgba(125,211,252,0.82))]",animate:{width:`${T}%`},transition:{duration:.35,ease:"easeOut"}})})]}),e.jsx(_t,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":v("common.dialogs.closeDialog"),className:"rounded-full bg-white/6 p-2 text-white/65 transition hover:bg-white/10 hover:text-white",children:e.jsx(mt,{className:"size-4"})})})]})}),e.jsx("div",{"data-testid":"question-flow-canvas",className:"min-h-0 flex-1 overflow-y-auto overscroll-contain px-4 py-4 md:px-6 md:py-5",children:e.jsx(Ta,{mode:"wait",children:e.jsxs(wt.div,{initial:{opacity:0,y:18},animate:{opacity:1,y:0},exit:{opacity:0,y:-18},transition:{duration:.28,ease:"easeOut"},className:"flex min-h-full min-w-0 flex-col gap-5",children:[e.jsxs("div",{className:"flex min-h-full min-w-0 flex-col justify-start",children:[y.eyebrow?e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-[var(--secondary)]",children:y.eyebrow}):null,e.jsx("h3",{className:"mt-1.5 font-display text-[clamp(1.45rem,2.15vw,2rem)] leading-tight text-white",children:y.title}),y.description?e.jsx("p",{className:"mt-1.5 max-w-3xl text-sm leading-6 text-white/58",children:y.description}):null,e.jsx("div",{className:"mt-5 grid flex-1 content-start gap-5",children:y.render(r,N)})]}),u?e.jsx("div",{className:"rounded-[20px] border border-rose-400/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-200",children:u}):null]},y.id)})}),e.jsx("div",{className:"sticky bottom-0 border-t border-white/8 bg-[rgba(12,17,30,0.92)] px-4 pt-2.5 pb-[calc(env(safe-area-inset-bottom)+0.75rem)] backdrop-blur-xl md:px-6 md:pb-3",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2 sm:justify-between",children:[e.jsx("div",{className:"hidden min-w-0 shrink text-[12px] text-white/45 sm:block",children:e.jsxs("span",{className:"truncate whitespace-nowrap",children:["Step ",k+1,"/",A]})}),e.jsxs("div",{className:"flex min-w-0 shrink-0 flex-wrap items-center justify-end gap-1.5 sm:gap-2",children:[k>0?e.jsxs(W,{type:"button",variant:"secondary",className:"min-w-max px-3 text-[12px]",onClick:()=>S(j=>Math.max(0,j-1)),children:[e.jsx(qo,{className:"size-4"}),"Back"]}):e.jsx(_t,{asChild:!0,children:e.jsx(W,{type:"button",variant:"secondary",className:"min-w-max px-3 text-[12px]",children:v("common.actions.cancel")})}),k<A-1?e.jsxs(W,{type:"button",className:"min-w-max px-3 text-[12px]",onClick:()=>S(j=>Math.min(A-1,j+1)),children:["Continue",e.jsx(Gs,{className:"size-4"})]}):e.jsxs(W,{type:"button",className:"min-w-max px-3 text-[12px]",pending:f,pendingLabel:b,onClick:()=>void o(),children:[e.jsx(ji,{className:"size-4"}),x]})]})]})})]})]})})}const Ce=c.forwardRef(function({className:s,...i},n){return e.jsx("textarea",{ref:n,...i,className:re("min-h-28 w-full rounded-[22px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none placeholder:text-white/35 focus:border-[rgba(192,193,255,0.35)]",s)})}),Qh={contentMarkdown:"",author:""};function Wh(){return{...Qh}}function sr({notes:t,onChange:s,entityLabel:i}){return e.jsxs("div",{className:"grid gap-3",children:[t.length===0?e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4 text-sm leading-6 text-white/58",children:["Add an optional Markdown note if this ",i," should start with context, evidence, or a clear handoff summary."]}):null,t.map((n,a)=>e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:["Creation note ",a+1]}),e.jsx(W,{type:"button",variant:"ghost",size:"sm",onClick:()=>s(t.filter((r,l)=>l!==a)),children:"Remove"})]}),e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Author"}),e.jsx(ie,{value:n.author,placeholder:"Albert",onChange:r=>s(t.map((l,d)=>d===a?{...l,author:r.target.value}:l))})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Markdown note"}),e.jsx(Ce,{className:"min-h-28",value:n.contentMarkdown,placeholder:"Capture why this was created now, what changed, or what the next person should know.",onChange:r=>s(t.map((l,d)=>d===a?{...l,contentMarkdown:r.target.value}:l))})]})]})]},a)),e.jsx("div",{children:e.jsx(W,{type:"button",variant:"secondary",onClick:()=>s([...t,Wh()]),children:"Add creation note"})})]})}function is({value:t,users:s,onChange:i,label:n="Owner",defaultLabel:a="Default Forge owner",help:r}){return e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-white",children:n}),r?e.jsx("span",{className:"text-xs leading-5 text-white/52",children:r}):null,e.jsxs("select",{value:t??"",onChange:l=>i(l.target.value||null),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:a}),s.map(l=>e.jsxs("option",{value:l.id,children:[l.displayName," · ",l.kind]},l.id))]})]})}const Gh=ot(["en","fr"]),ir=Ze({contentMarkdown:ve().trim().min(1,"Note content is required"),author:ve().trim()}),gd=Ze({title:ve().trim().min(1,"Title is required"),description:ve().trim(),horizon:ot(["quarter","year","lifetime"]),status:ot(["active","paused","completed"]),userId:ve().trim().nullable().optional(),targetPoints:Zt.number().int().min(25).max(1e4),themeColor:ve().trim().regex(/^#[0-9a-fA-F]{6}$/,"Theme color must be a valid hex value"),tagIds:Ae(ve()),notes:Ae(ir)}),bd=Ze({goalId:ve().trim().min(1,"Life goal is required"),title:ve().trim().min(1,"Title is required"),description:ve().trim(),status:ot(["active","paused","completed"]),userId:ve().trim().nullable().optional(),targetPoints:Zt.number().int().min(25).max(1e4),themeColor:ve().trim().regex(/^#[0-9a-fA-F]{6}$/,"Theme color must be a valid hex value"),notes:Ae(ir)}),Hh=Ze({profile:Ze({operatorName:ve().trim().min(1,"Name is required"),operatorEmail:ve().trim().min(1,"Email is required"),operatorTitle:ve().trim().min(1,"Title is required")}),notifications:Ze({goalDriftAlerts:ya(),dailyQuestReminders:ya(),achievementCelebrations:ya()}),execution:Ze({maxActiveTasks:Zt.number().int().min(1).max(8),timeAccountingMode:ot(["split","parallel","primary_only"])}),themePreference:ot(["obsidian","solar","system"]),localePreference:Gh,calendarProviders:Ze({microsoft:Ze({clientId:ve().trim(),tenantId:ve().trim(),redirectUri:ve().trim()}).optional()}).optional()}),Xh=Ze({label:ve().trim().min(1,"Label is required"),agentLabel:ve().trim().min(1,"Agent name is required"),agentType:ve().trim().min(1,"Agent type is required"),description:ve().trim(),trustLevel:ot(["standard","trusted","autonomous"]),autonomyMode:ot(["approval_required","scoped_write","autonomous"]),approvalMode:ot(["approval_by_default","high_impact_only","none"]),scopes:Ae(ve().trim().min(1)).min(1)}),Jh=Ze({originType:ot(["system","user","agent"]),originAgentId:ve().trim(),originLabel:ve().trim(),entityType:ve().trim(),entityId:ve().trim(),timeframeLabel:ve().trim(),title:ve().trim().min(1,"Title is required"),summary:ve().trim().min(1,"Summary is required"),recommendation:ve().trim().min(1,"Recommendation is required"),rationale:ve().trim(),confidence:Zt.number().min(0).max(1),ctaLabel:ve().trim().min(1,"CTA label is required")}),fd=Ze({title:ve().trim().min(1,"Title is required"),description:ve().trim(),owner:ve().trim().min(1,"Owner is required"),userId:ve().trim().nullable().optional(),goalId:ve().trim(),projectId:ve().trim().min(1,"Project is required"),priority:ot(["low","medium","high","critical"]),status:ot(["backlog","focus","in_progress","blocked","done"]),effort:ot(["light","deep","marathon"]),energy:ot(["low","steady","high"]),dueDate:ve().trim(),points:Zt.number().int().min(5).max(500),tagIds:Ae(ve()),notes:Ae(ir)}),Yh=Ze({title:ve().trim().min(1,"Title is required"),description:ve().trim(),status:ot(["active","paused","archived"]),userId:ve().trim().nullable().optional(),polarity:ot(["positive","negative"]),frequency:ot(["daily","weekly"]),targetCount:Zt.number().int().min(1).max(14),weekDays:Ae(Jn().int().min(0).max(6)).max(7),linkedGoalIds:Ae(ve().trim().min(1)),linkedProjectIds:Ae(ve().trim().min(1)),linkedTaskIds:Ae(ve().trim().min(1)),linkedValueIds:Ae(ve().trim().min(1)),linkedPatternIds:Ae(ve().trim().min(1)),linkedBehaviorIds:Ae(ve().trim().min(1)),linkedBeliefIds:Ae(ve().trim().min(1)),linkedModeIds:Ae(ve().trim().min(1)),linkedReportIds:Ae(ve().trim().min(1)),linkedBehaviorId:ve().trim(),rewardXp:Zt.number().int().min(1).max(100),penaltyXp:Zt.number().int().min(1).max(100),generatedHealthEventTemplate:Ze({enabled:ya(),workoutType:ve().trim(),title:ve().trim(),durationMinutes:Zt.number().int().min(1).max(1440),xpReward:Zt.number().int().min(0).max(500),tags:Ae(ve().trim()),links:Ae(Ze({entityType:ve().trim().min(1),entityId:ve().trim().min(1),relationshipType:ve().trim().default("context")})),notesTemplate:ve().trim()})}).superRefine((t,s)=>{t.frequency==="weekly"&&t.weekDays.length===0&&s.addIssue({code:nm.custom,path:["weekDays"],message:"Pick at least one weekday"})}),Vh=Ze({entityType:ot(["task","project"]),entityId:ve().trim().min(1,"A target is required"),deltaMinutes:Zt.number().int().refine(t=>t!==0,"Minutes must not be zero"),note:ve().trim()});Ze({name:ve().trim().min(1,"Name is required"),kind:ot(["value","category","execution"]),userId:ve().trim().nullable().optional(),color:ve().trim().regex(/^#[0-9a-fA-F]{6}$/,"Color must be a valid hex value"),description:ve().trim()});const an={title:"",description:"",horizon:"year",status:"active",userId:null,targetPoints:400,themeColor:"#c8a46b",tagIds:[],notes:[]};function Zh(t){return{title:t.title,description:t.description,horizon:t.horizon,status:t.status,userId:t.userId??null,targetPoints:t.targetPoints,themeColor:t.themeColor,tagIds:t.tagIds,notes:[]}}function ar({open:t,pending:s=!1,editingGoal:i,tags:n,users:a,defaultUserId:r=null,onOpenChange:l,onSubmit:d}){const{t:o}=at(),x=a??[],f=x.find(S=>S.id===r)??null,[b,m]=c.useState(an),[h,p]=c.useState(null),[w,v]=c.useState({}),I=S=>{v(Object.fromEntries(Object.entries(S).map(([M,P])=>[M,P==null?void 0:P[0]])))};c.useEffect(()=>{t&&(p(null),v({}),m(i?Zh(i):{...an,userId:r}))},[r,i,t]);const k=[{id:"intent",eyebrow:"Direction",title:"Name the arc and why it matters",description:"Start with the long-horizon direction itself. We can refine cadence, tags, and visual tone after the intent is clear.",render:(S,M)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:o("common.dialogs.goal.title"),error:w.title??null,children:e.jsx(ie,{value:S.title,onChange:P=>M({title:P.target.value}),placeholder:"Build a durable body and calm energy"})}),e.jsx(Y,{label:o("common.dialogs.goal.descriptionLabel"),children:e.jsx(Ce,{value:S.description,onChange:P=>M({description:P.target.value}),placeholder:"Write the goal description in Markdown. This can stay short or grow into a long strategic page."})}),e.jsx(is,{value:S.userId,users:x,onChange:P=>M({userId:P}),label:"Owner user",defaultLabel:ss(f),help:"Goals can belong to a human or bot user. The current single-user scope becomes the default when one user is selected."})]})},{id:"cadence",eyebrow:"Cadence",title:"Choose the horizon and current posture",description:"Keep this simple: how long does this arc run, and is it currently active, paused, or already complete?",render:(S,M)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:o("common.dialogs.goal.horizon"),children:e.jsx(tt,{value:S.horizon,onChange:P=>M({horizon:P}),options:[{value:"quarter",label:o("common.enums.goalHorizon.quarter"),description:"Tight strategic push for the coming months."},{value:"year",label:o("common.enums.goalHorizon.year"),description:"A full-cycle objective for this year."},{value:"lifetime",label:o("common.enums.goalHorizon.lifetime"),description:"A long-running life arc that projects can keep serving."}],columns:3})}),e.jsx(Y,{label:o("common.dialogs.goal.status"),children:e.jsx(tt,{value:S.status,onChange:P=>M({status:P}),options:[{value:"active",label:o("common.enums.projectStatus.active"),description:"This is live right now."},{value:"paused",label:o("common.enums.projectStatus.paused"),description:"Keep it visible, but do not push it right now."},{value:"completed",label:o("common.enums.projectStatus.completed"),description:"You have already fulfilled this arc."}]})})]})},{id:"signal",eyebrow:"Signal",title:"Set the target and visual signature",description:"Give Forge enough signal to show progress and make this arc recognizable throughout the app.",render:(S,M)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:o("common.dialogs.goal.targetXp"),error:w.targetPoints??null,children:e.jsx(ie,{type:"number",value:S.targetPoints,onChange:P=>M({targetPoints:Number(P.target.value)||0})})}),e.jsx(Y,{label:o("common.dialogs.goal.themeColor"),error:w.themeColor??null,children:e.jsxs("div",{className:"flex items-center gap-3 rounded-[22px] border border-white/8 bg-white/6 px-4 py-3",children:[e.jsx("input",{className:"h-10 w-12 rounded-lg border border-white/10 bg-transparent",type:"color",value:S.themeColor,onChange:P=>M({themeColor:P.target.value})}),e.jsx(ie,{className:"border-none bg-transparent px-0 py-0",value:S.themeColor,onChange:P=>M({themeColor:P.target.value})})]})}),e.jsx(Y,{label:o("common.dialogs.goal.tags"),children:e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(P=>{const y=S.tagIds.includes(P.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${y?"bg-white/16 text-white":"bg-white/6 text-white/58 hover:bg-white/10 hover:text-white"}`,onClick:()=>M({tagIds:y?S.tagIds.filter(N=>N!==P.id):[...S.tagIds,P.id]}),children:P.name},P.id)})})})]})},{id:"notes",eyebrow:"Evidence",title:"Attach any creation context that should live with this goal",description:"Creation notes become real linked Markdown notes, so strategic context does not vanish into the form flow.",render:(S,M)=>e.jsx(Y,{label:"Creation notes",children:e.jsx(sr,{notes:S.notes,onChange:P=>M({notes:P}),entityLabel:"goal"})})}];return e.jsx(it,{open:t,onOpenChange:l,eyebrow:o("common.dialogs.goal.eyebrow"),title:o(i?"common.dialogs.goal.editTitle":"common.dialogs.goal.createTitle"),description:o("common.dialogs.goal.description"),value:b,onChange:m,steps:k,pending:s,pendingLabel:o(i?"common.dialogs.goal.save":"common.dialogs.goal.create"),submitLabel:o(i?"common.dialogs.goal.save":"common.dialogs.goal.create"),error:h,onSubmit:async()=>{p(null);const S=gd.safeParse(b);if(!S.success){I(S.error.flatten().fieldErrors),p("Some answers still need attention before this goal arc can be saved.");return}v({});try{await d(S.data,i==null?void 0:i.id),m(an),l(!1)}catch(M){p(M instanceof Error?M.message:o("common.dialogs.goal.submitError"))}}})}function $e({user:t,compact:s=!1,className:i}){if(!t)return e.jsx(O,{size:s?"sm":"md",className:re("border-white/10 bg-white/[0.05] text-white/55",i),children:"Unassigned"});const n=t.kind==="bot"?ka:Mn;return e.jsxs(O,{size:s?"sm":"md",className:re("max-w-full gap-1.5 border text-white",t.kind==="bot"?"border-cyan-300/18 bg-cyan-400/12 text-cyan-50":"border-amber-300/18 bg-amber-400/12 text-amber-50",i),children:[e.jsx(n,{className:"size-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:t.displayName}),e.jsx("span",{className:"text-white/55",children:t.kind})]})}const al={goalId:"",title:"",description:"",status:"active",userId:null,targetPoints:240,themeColor:"#c0c1ff",notes:[]};function eu(t){return{goalId:t.goalId,title:t.title,description:t.description,status:t.status,userId:t.userId??null,targetPoints:t.targetPoints,themeColor:t.themeColor,notes:[]}}function nr({open:t,goals:s,users:i,editingProject:n,initialGoalId:a,defaultUserId:r=null,onOpenChange:l,onSubmit:d}){const{t:o}=at(),x=i??[],[f,b]=c.useState(al),[m,h]=c.useState(null),[p,w]=c.useState({}),v=s.find(M=>M.id===f.goalId)??null,I=x.find(M=>M.id===((v==null?void 0:v.userId)??r))??null,k=M=>{w(Object.fromEntries(Object.entries(M).map(([P,y])=>[P,y==null?void 0:y[0]])))};c.useEffect(()=>{var M;t&&(h(null),w({}),b(n?eu(n):{...al,goalId:a??"",userId:((M=s.find(P=>P.id===a))==null?void 0:M.userId)??r}))},[r,n,s,a,t]);const S=[{id:"anchor",eyebrow:"Anchor",title:"Attach the project to the right goal",description:"Projects should serve one clear life-goal arc, so start by picking the direction this initiative belongs to.",render:(M,P)=>e.jsx(Y,{label:o("common.dialogs.project.goal"),error:p.goalId??null,children:e.jsx("div",{className:"grid gap-3",children:s.map(y=>{const N=y.id===M.goalId;return e.jsxs("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${N?"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:()=>P({goalId:y.id}),children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx(_e,{kind:"goal",label:y.title,className:"max-w-full"}),e.jsx($e,{user:y.user,compact:!0})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:y.description||"No strategic note attached yet."})]},y.id)})})})},{id:"shape",eyebrow:"Shape",title:"Name the initiative and the work it will make possible",description:"Keep the project concrete. The title should sound like something you can actually move forward this season.",render:(M,P)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:o("common.dialogs.project.title"),error:p.title??null,children:e.jsx(ie,{value:M.title,onChange:y=>P({title:y.target.value}),placeholder:"Launch the new creative practice system"})}),e.jsx(Y,{label:o("common.dialogs.project.descriptionLabel"),children:e.jsx(Ce,{value:M.description,onChange:y=>P({description:y.target.value}),placeholder:"Write the project description in Markdown. Use as much detail as the workstream needs."})}),e.jsx(is,{value:M.userId,users:x,onChange:y=>P({userId:y}),label:"Owner user",defaultLabel:ss(I),help:"Projects can intentionally cross user boundaries, but the linked goal owner is suggested by default."})]})},{id:"signal",eyebrow:"Signal",title:"Set the project's posture and progress target",description:"This keeps the board, reward system, and detail views aligned without forcing you through a giant settings form.",render:(M,P)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:o("common.dialogs.project.status"),children:e.jsx(tt,{value:M.status,onChange:y=>P({status:y}),options:[{value:"active",label:o("common.enums.projectStatus.active"),description:"Push this initiative now."},{value:"paused",label:o("common.enums.projectStatus.paused"),description:"Keep it available without active pressure."},{value:"completed",label:o("common.enums.projectStatus.completed"),description:"This initiative has landed."}]})}),e.jsx(Y,{label:o("common.dialogs.project.targetXp"),error:p.targetPoints??null,children:e.jsx(ie,{type:"number",value:M.targetPoints,onChange:y=>P({targetPoints:Number(y.target.value)||0})})}),e.jsx(Y,{label:o("common.dialogs.project.themeColor"),error:p.themeColor??null,children:e.jsxs("div",{className:"flex items-center gap-3 rounded-[22px] border border-white/8 bg-white/6 px-4 py-3",children:[e.jsx("input",{className:"h-10 w-12 rounded-lg border border-white/10 bg-transparent",type:"color",value:M.themeColor,onChange:y=>P({themeColor:y.target.value})}),e.jsx(ie,{className:"border-none bg-transparent px-0 py-0",value:M.themeColor,onChange:y=>P({themeColor:y.target.value})})]})})]})},{id:"notes",eyebrow:"Evidence",title:"Keep the creation context attached to the project from day one",description:"Use linked Markdown notes when the initiative needs setup context, assumptions, or a handoff summary right away.",render:(M,P)=>e.jsx(Y,{label:"Creation notes",children:e.jsx(sr,{notes:M.notes,onChange:y=>P({notes:y}),entityLabel:"project"})})}];return e.jsx(it,{open:t,onOpenChange:l,eyebrow:o("common.dialogs.project.eyebrow"),title:o(n?"common.dialogs.project.editTitle":"common.dialogs.project.createTitle"),description:o("common.dialogs.project.description"),value:f,onChange:b,steps:S,submitLabel:o(n?"common.dialogs.project.save":"common.dialogs.project.create"),error:m,onSubmit:async()=>{h(null);const M=bd.safeParse(f);if(!M.success){k(M.error.flatten().fieldErrors),h("A couple of answers still need attention before this project can be saved.");return}w({});try{await d(M.data,n==null?void 0:n.id),l(!1)}catch(P){h(P instanceof Error?P.message:o("common.dialogs.project.submitError"))}}})}const nn={title:"",description:"",owner:"Albert",userId:null,goalId:"",projectId:"",priority:"medium",status:"focus",effort:"deep",energy:"steady",dueDate:"",points:60,tagIds:[],notes:[]};function tu(t){return{title:t.title,description:t.description,owner:t.owner,userId:t.userId??null,goalId:t.goalId??"",projectId:t.projectId??"",priority:t.priority,status:t.status,effort:t.effort,energy:t.energy,dueDate:t.dueDate??"",points:t.points,tagIds:t.tagIds,notes:[]}}function za({open:t,goals:s,projects:i,tags:n,users:a,editingTask:r,initialProjectId:l,defaultUserId:d=null,onOpenChange:o,onSubmit:x}){const{t:f}=at(),b=s??[],m=i??[],h=n??[],p=a??[],[w,v]=c.useState(nn),[I,k]=c.useState(null),[S,M]=c.useState({}),P=T=>{M(Object.fromEntries(Object.entries(T).map(([F,u])=>[F,u==null?void 0:u[0]])))};c.useEffect(()=>{var T,F,u;t&&(k(null),M({}),v(r?tu(r):{...nn,owner:((T=p.find(j=>{var L;return j.id===(((L=m.find(q=>q.id===l))==null?void 0:L.userId)??d)}))==null?void 0:T.displayName)??nn.owner,userId:((F=m.find(j=>j.id===l))==null?void 0:F.userId)??d,projectId:l??"",goalId:((u=m.find(j=>j.id===l))==null?void 0:u.goalId)??""}))},[d,r,l,t,m,p]);const y=c.useMemo(()=>m.find(T=>T.id===w.projectId)??null,[w.projectId,m]),N=p.find(T=>T.id===((y==null?void 0:y.userId)??d))??null;c.useEffect(()=>{y&&w.goalId!==y.goalId&&v(T=>({...T,goalId:y.goalId}))},[w.goalId,y]);const A=[{id:"anchor",eyebrow:"Placement",title:"Choose where this task belongs",description:"Link the task to the right project so the board, life goal, and rewards stay connected.",render:(T,F)=>{var u;return e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:f("common.dialogs.task.project"),labelHelp:"Projects are the main home for tasks. Pick the stream of work this task belongs to.",error:S.projectId??null,children:e.jsx("div",{className:"grid gap-3",children:m.map(j=>{const L=j.id===T.projectId;return e.jsxs("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${L?"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:()=>F({projectId:j.id,goalId:j.goalId}),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(_e,{kind:"project",label:j.title,className:"min-w-0",showIcon:!1}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e.jsx(ke,{kind:"goal",label:j.goalTitle,compact:!0,gradient:!1}),e.jsx($e,{user:j.user,compact:!0})]})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:j.description})]},j.id)})})}),e.jsx(Y,{label:f("common.dialogs.task.goal"),labelHelp:"The life goal is shown automatically from the project so you can still see the bigger reason this task matters.",children:e.jsx(ie,{readOnly:!0,value:y?((u=b.find(j=>j.id===y.goalId))==null?void 0:u.title)??"":"",placeholder:"The linked life goal will appear here."})})]})}},{id:"shape",eyebrow:"Shape",title:"Define the next concrete move",description:"Keep the task small enough to be actionable and strong enough to clearly move the project forward.",render:(T,F)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:f("common.dialogs.task.title"),error:S.title??null,children:e.jsx(ie,{value:T.title,onChange:u=>F({title:u.target.value}),placeholder:"Draft the first mode atlas sketch"})}),e.jsx(Y,{label:f("common.dialogs.task.descriptionLabel"),children:e.jsx(Ce,{value:T.description,onChange:u=>F({description:u.target.value}),placeholder:"Write the task description in Markdown. Keep it short or turn it into a full acceptance doc."})}),e.jsx(Y,{label:f("common.dialogs.task.owner"),labelHelp:"The owner is the person or role expected to carry this task.",error:S.owner??null,children:e.jsx(ie,{value:T.owner,onChange:u=>F({owner:u.target.value}),placeholder:"Albert"})}),e.jsx(is,{value:T.userId,users:p,onChange:u=>{var j;return F({userId:u,owner:((j=p.find(L=>L.id===u))==null?void 0:j.displayName)??T.owner})},label:"Owner user",defaultLabel:ss(N),help:"Tasks can belong to a human or bot user. The linked project owner is suggested first so cross-user task routing stays explicit."})]})},{id:"execution",eyebrow:"Execution",title:"Set priority, status, effort, and energy",description:"This is the minimum the execution engine needs in order to place the task well and show the right next move.",render:(T,F)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:f("common.dialogs.task.priority"),labelHelp:"Priority controls how strongly Forge should surface this task in the board and daily views.",children:e.jsx(tt,{value:T.priority,onChange:u=>F({priority:u}),options:[{value:"low",label:f("common.enums.priority.low")},{value:"medium",label:f("common.enums.priority.medium")},{value:"high",label:f("common.enums.priority.high")},{value:"critical",label:f("common.enums.priority.critical")}]})}),e.jsx(Y,{label:f("common.dialogs.task.status"),labelHelp:"Status tells Forge whether the task is waiting, ready for focus, active, blocked, or done.",children:e.jsx(tt,{value:T.status,onChange:u=>F({status:u}),options:[{value:"backlog",label:f("common.enums.taskStatus.backlog")},{value:"focus",label:f("common.enums.taskStatus.focus")},{value:"in_progress",label:f("common.enums.taskStatus.in_progress")},{value:"blocked",label:f("common.enums.taskStatus.blocked")}]})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Y,{label:f("common.dialogs.task.effort"),labelHelp:"Effort describes how much concentration and time this task usually needs.",children:e.jsx(tt,{value:T.effort,onChange:u=>F({effort:u}),options:[{value:"light",label:f("common.enums.effort.light")},{value:"deep",label:f("common.enums.effort.deep")},{value:"marathon",label:f("common.enums.effort.marathon")}]})}),e.jsx(Y,{label:f("common.dialogs.task.energy"),labelHelp:"Energy helps you match this task to a low-energy, steady, or high-energy moment.",children:e.jsx(tt,{value:T.energy,onChange:u=>F({energy:u}),options:[{value:"low",label:f("common.enums.energy.low")},{value:"steady",label:f("common.enums.energy.steady")},{value:"high",label:f("common.enums.energy.high")}]})})]})]})},{id:"signal",eyebrow:"Reward and timing",title:"Set the reward and timing details",description:"This keeps the daily surfaces honest without forcing you through a bloated last-mile form.",render:(T,F)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Y,{label:f("common.dialogs.task.xp"),labelHelp:"XP is the reward weight for finishing this task. Higher XP should mean more meaningful work.",error:S.points??null,children:e.jsx(ie,{type:"number",value:T.points,onChange:u=>F({points:Number(u.target.value)||0}),placeholder:"60"})}),e.jsx(Y,{label:f("common.dialogs.task.dueDate"),labelHelp:"Only add a due date when timing really matters for this task.",children:e.jsx(ie,{type:"date",value:T.dueDate,onChange:u=>F({dueDate:u.target.value})})})]}),e.jsx(Y,{label:f("common.dialogs.task.tags"),children:e.jsx("div",{className:"flex flex-wrap gap-2",children:h.map(u=>{const j=T.tagIds.includes(u.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${j?"bg-white/16 text-white":"bg-white/6 text-white/58 hover:bg-white/10 hover:text-white"}`,onClick:()=>F({tagIds:j?T.tagIds.filter(L=>L!==u.id):[...T.tagIds,u.id]}),children:u.name},u.id)})})})]})},{id:"notes",eyebrow:"Evidence",title:"Capture launch context if this task needs a durable work note",description:"These notes become linked Markdown evidence on the task immediately, which helps preserve setup context, blockers, or handoff detail.",render:(T,F)=>e.jsx(Y,{label:"Creation notes",children:e.jsx(sr,{notes:T.notes,onChange:u=>F({notes:u}),entityLabel:"task"})})}];return e.jsx(it,{open:t,onOpenChange:o,eyebrow:f("common.dialogs.task.eyebrow"),title:f(r?"common.dialogs.task.editTitle":"common.dialogs.task.createTitle"),description:f("common.dialogs.task.description"),value:w,onChange:v,steps:A,submitLabel:f(r?"common.dialogs.task.save":"common.dialogs.task.create"),error:I,onSubmit:async()=>{k(null);const T=fd.safeParse(w);if(!T.success){P(T.error.flatten().fieldErrors),k("A few task details still need attention before this move can be saved.");return}M({});try{await x(T.data,r==null?void 0:r.id),o(!1)}catch(F){k(F instanceof Error?F.message:"Unable to save this task right now.")}}})}const nl="(max-width: 1023px)";function su(){const[t,s]=c.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(nl).matches);return c.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const i=window.matchMedia(nl),n=a=>{s(a.matches)};return s(i.matches),typeof i.addEventListener=="function"?(i.addEventListener("change",n),()=>i.removeEventListener("change",n)):(i.addListener(n),()=>i.removeListener(n))},[]),t}function rl({kind:t,title:s,description:i,onClick:n}){return e.jsxs("button",{type:"button",className:"w-full min-w-0 rounded-[22px] border border-white/8 bg-white/[0.04] px-4 py-4 text-left transition hover:bg-white/[0.08]",onClick:n,children:[e.jsx(ke,{kind:t,label:s,compact:!0,gradient:!1,className:"max-w-full"}),e.jsx("div",{className:"mt-1 text-sm text-white/55",children:i})]})}function iu({goals:t,projects:s,tags:i,users:n,defaultUserId:a=null,onCreateGoal:r,onCreateProject:l,onCreateTask:d,className:o}){const{t:x}=at(),f=ht(),b=t??[],m=s??[],h=i??[],p=n??[],[w,v]=c.useState(!1),[I,k]=c.useState(!1),[S,M]=c.useState(!1),[P,y]=c.useState(!1),[N,A]=c.useState(null),T=su(),F=c.useRef(null),u=c.useRef(null);c.useEffect(()=>{if(!w||T)return;const L=()=>{var ne;const Q=(ne=F.current)==null?void 0:ne.getBoundingClientRect();Q&&A({top:Math.max(24,Q.top-18),right:Math.max(24,window.innerWidth-Q.right)})};L();const q=Q=>{var ne,H;(ne=F.current)!=null&&ne.contains(Q.target)||(H=u.current)!=null&&H.contains(Q.target)||v(!1)},G=Q=>{Q.key==="Escape"&&v(!1)};return document.addEventListener("pointerdown",q),document.addEventListener("keydown",G),window.addEventListener("resize",L),window.addEventListener("scroll",L,!0),()=>{document.removeEventListener("pointerdown",q),document.removeEventListener("keydown",G),window.removeEventListener("resize",L),window.removeEventListener("scroll",L,!0)}},[T,w]);const j=[{id:"goal",kind:"goal",group:"Execution",title:x("common.navigation.newGoal"),description:x("common.navigation.newGoalDescription"),onSelect:()=>{v(!1),k(!0)}},{id:"project",kind:"project",group:"Execution",title:x("common.navigation.newProject"),description:x("common.navigation.newProjectDescription"),onSelect:()=>{v(!1),M(!0)}},{id:"task",kind:"task",group:"Execution",title:x("common.navigation.newTask"),description:x("common.navigation.newTaskDescription"),onSelect:()=>{v(!1),y(!0)}},{id:"strategy",kind:"strategy",group:"Execution",title:"Strategy",description:"Plan a directed path across projects and tasks toward a real end state.",onSelect:()=>{v(!1),f("/strategies?create=1")}},{id:"habit",kind:"habit",group:"Execution",title:"Habit",description:"Track a recurring commitment or recurring slip with explicit XP logic.",onSelect:()=>{v(!1),f("/habits?create=1")}},{id:"value",kind:"value",group:"Psyche",title:"Value",description:"Place one value into the goal, project, and task constellation.",onSelect:()=>{v(!1),f("/psyche/values?create=1")}},{id:"pattern",kind:"pattern",group:"Psyche",title:"Pattern",description:"Map a loop, its payoff, its cost, and the response you want.",onSelect:()=>{v(!1),f("/psyche/patterns?create=1")}},{id:"behavior",kind:"behavior",group:"Psyche",title:"Behavior",description:"Describe the move first, then classify it and link it.",onSelect:()=>{v(!1),f("/psyche/behaviors?create=1")}},{id:"report",kind:"report",group:"Psyche",title:"Report",description:"Start a Spark-to-Pivot reflective chain.",onSelect:()=>{v(!1),f("/psyche/reports?create=1")}}];return e.jsxs(e.Fragment,{children:[e.jsx("div",{ref:F,className:o,style:T?{right:"max(1rem, calc(var(--forge-safe-area-right) + 1rem))",bottom:"var(--forge-mobile-create-bottom)"}:void 0,children:e.jsxs(W,{type:"button","data-testid":"create-floating-trigger","aria-expanded":w,"aria-haspopup":"dialog",onClick:()=>v(L=>T?!0:!L),className:`min-w-max max-w-[calc(100vw-2rem)] shrink-0 rounded-full px-3.5 py-2 text-[12px] shadow-[0_20px_60px_rgba(4,8,18,0.34)] ${w?"bg-[linear-gradient(135deg,rgba(192,193,255,0.52),rgba(125,211,252,0.24))] text-white":""}`,children:[e.jsx(vt,{className:`size-4 transition ${w?"text-white":"text-white/72"}`}),x("common.navigation.create")]})}),w&&!T&&typeof document<"u"&&N?Bo.createPortal(e.jsxs("div",{ref:u,"data-testid":"create-desktop-menu",className:"fixed z-50 w-[min(26rem,calc(100vw-2rem))] max-h-[min(34rem,calc(100vh-4rem))] overflow-y-auto rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,24,40,0.985),rgba(10,15,27,0.985))] p-4 shadow-[0_28px_90px_rgba(3,8,18,0.46)]",style:{top:`${N.top}px`,right:`${N.right}px`,transform:"translateY(-100%)"},children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Create"}),e.jsx("div",{className:"mt-2 text-lg font-medium text-white",children:"Start the next move"}),e.jsx("div",{className:"mt-1 text-sm leading-6 text-white/56",children:"Pick one thing to create. The flow keeps the first step light and visible."}),["Execution","Psyche"].map(L=>e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:L}),e.jsx("div",{className:"mt-2 grid gap-2",children:j.filter(q=>q.group===L).map(q=>e.jsx(rl,{kind:q.kind,title:q.title,description:q.description,onClick:q.onSelect},q.id))})]},L))]}),document.body):null,e.jsx(Lt,{open:w&&T,onOpenChange:v,children:e.jsxs(Dt,{children:[e.jsx($t,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.72)] backdrop-blur-xl lg:hidden"}),e.jsxs(Ot,{"data-testid":"create-mobile-sheet",className:"fixed inset-x-4 bottom-28 z-50 flex max-h-[min(30rem,calc(100vh-8rem))] flex-col overflow-hidden rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(24,31,50,0.98),rgba(15,21,36,0.98))] p-0 shadow-[0_30px_90px_rgba(3,8,18,0.45)] lg:hidden",style:{left:"max(1rem, calc(var(--forge-safe-area-left) + 1rem))",right:"max(1rem, calc(var(--forge-safe-area-right) + 1rem))",bottom:"calc(var(--forge-mobile-nav-clearance) - 0.5rem)"},children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 border-b border-white/8 px-5 py-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:x("common.navigation.create")}),e.jsx(Rt,{className:"mt-2 font-display text-2xl text-white",children:x("common.navigation.createTitle")}),e.jsx(Gt,{className:"mt-2 text-sm leading-6 text-white/60",children:x("common.navigation.createDescription")})]}),e.jsx(_t,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":x("common.navigation.closeCreateMenu"),className:"rounded-full bg-white/6 p-2 text-white/65 transition hover:bg-white/10 hover:text-white",children:e.jsx(mt,{className:"size-4"})})})]}),e.jsx("div",{className:"overflow-y-auto p-4 overscroll-contain",children:["Execution","Psyche"].map(L=>e.jsxs("div",{className:"mt-1 grid gap-2 first:mt-0",children:[e.jsx("div",{className:"px-1 text-[11px] uppercase tracking-[0.18em] text-white/38",children:L}),j.filter(q=>q.group===L).map(q=>e.jsx(rl,{kind:q.kind,title:q.title,description:q.description,onClick:q.onSelect},q.id))]},L))})]})]})}),e.jsx(ar,{open:I,editingGoal:null,tags:h,users:p,defaultUserId:a,onOpenChange:k,onSubmit:async L=>{await r(L)}}),e.jsx(nr,{open:S,goals:b,users:p,editingProject:null,defaultUserId:a,onOpenChange:M,onSubmit:async L=>{await l(L)}}),e.jsx(za,{open:P,goals:b,projects:m,tags:h,users:p,editingTask:null,defaultUserId:a,onOpenChange:y,onSubmit:async L=>{await d(L)}})]})}function au(t){return t===null?"20":String(Math.max(1,Math.round(t/60)))}function nu({tasks:t,projects:s,activeRunCount:i,maxActiveTasks:n,timeAccountingMode:a,pending:r,errorMessage:l,initialTaskId:d,defaultProjectId:o,onCancel:x,onStartExisting:f,onCreateAndStart:b}){const[m,h]=c.useState("existing"),[p,w]=c.useState(""),[v,I]=c.useState(d??null),[k,S]=c.useState(""),[M,P]=c.useState(""),[y,N]=c.useState(o??""),[A,T]=c.useState("planned"),[F,u]=c.useState("20");c.useEffect(()=>{h(d?"existing":"new"),w(""),I(d??null),S(""),P(""),N(o??""),T("planned"),u("20")},[o,d]);const j=c.useMemo(()=>t.filter(H=>H.status!=="done").sort((H,_)=>H.time.hasCurrentRun!==_.time.hasCurrentRun?Number(_.time.hasCurrentRun)-Number(H.time.hasCurrentRun):H.status!==_.status?H.status.localeCompare(_.status):H.title.localeCompare(_.title)),[t]),L=c.useMemo(()=>{const H=p.trim().toLowerCase();return H?j.filter(_=>{var R,C,J,ee,le,oe;const U=s.find(ue=>ue.id===_.projectId);return[_.title,_.description,_.owner,((R=_.user)==null?void 0:R.displayName)??"",((C=_.user)==null?void 0:C.handle)??"",((J=_.user)==null?void 0:J.kind)??"",(U==null?void 0:U.title)??"",((ee=U==null?void 0:U.user)==null?void 0:ee.displayName)??"",((le=U==null?void 0:U.user)==null?void 0:le.handle)??"",((oe=U==null?void 0:U.user)==null?void 0:oe.kind)??""].some(ue=>ue.toLowerCase().includes(H))}):j},[s,j,p]),q=c.useMemo(()=>s.find(H=>H.id===y)??null,[y,s]),G=A==="planned"?Math.max(60,(Number.parseInt(F,10)||20)*60):null,Q=m==="existing"?!!v:!!(k.trim()&&y),ne=a==="split"?"Split time":a==="parallel"?"Parallel time":"Primary only";return e.jsxs("div",{className:"grid gap-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:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Start work"}),e.jsx("h3",{className:"mt-2 font-display text-[clamp(1.2rem,1.8vw,1.65rem)] text-white",children:"Pick a task and start the timer"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-white/60",children:"Use an existing task or create a new one quickly. Forge will move the task into in progress as soon as work starts."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(O,{className:"bg-white/[0.08] text-white/72",children:[i,"/",n," live"]}),e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:ne})]})]}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:[{value:"existing",label:"Existing task",detail:"Search and start something that already exists."},{value:"new",label:"New quick task",detail:"Create a task with a title, short description, and project."}].map(H=>{const _=m===H.value;return e.jsxs("button",{type:"button",className:re("rounded-[18px] border px-4 py-4 text-left transition",_?"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/65 hover:bg-white/[0.07]"),onClick:()=>h(H.value),children:[e.jsx("div",{className:"font-medium",children:H.label}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-inherit/80",children:H.detail})]},H.value)})}),m==="existing"?e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"type-label text-white/45",children:"Search tasks"}),e.jsxs("div",{className:"relative",children:[e.jsx(dt,{className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-white/32"}),e.jsx(ie,{value:p,onChange:H=>w(H.target.value),placeholder:"Search task, project, human, bot, or owner",className:"pl-10"})]})]}),e.jsx("div",{className:"grid max-h-[19rem] gap-2 overflow-y-auto rounded-[20px] bg-white/[0.03] p-2",children:L.length===0?e.jsx("div",{className:"rounded-[16px] border border-dashed border-white/8 px-4 py-8 text-center text-sm text-white/42",children:"No tasks match. Switch to New quick task to create one now."}):L.slice(0,16).map(H=>{const _=v===H.id,U=s.find(R=>R.id===H.projectId);return e.jsx("button",{type:"button",className:re("rounded-[16px] border px-4 py-3 text-left transition",_?"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:()=>I(H.id),children:e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(_e,{kind:"task",label:H.title,className:"max-w-full"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[U?e.jsx(ke,{kind:"project",label:U.title,compact:!0,gradient:!1}):null,e.jsx(O,{className:"bg-white/[0.08] text-white/70",children:H.status.replaceAll("_"," ")}),H.time.activeRunCount>0?e.jsxs(O,{className:"bg-emerald-500/12 text-emerald-200",children:[H.time.activeRunCount," live"]}):null]})]}),e.jsxs("span",{className:"text-[12px] text-white/45",children:[H.points," xp"]})]})},H.id)})})]}):e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"type-label text-white/45",children:"Task title"}),e.jsx(ie,{value:k,onChange:H=>S(H.target.value),placeholder:"Write the next concrete task"})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"type-label text-white/45",children:"Short description"}),e.jsx(Ce,{value:M,onChange:H=>P(H.target.value),placeholder:"Keep it short and concrete."})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"type-label text-white/45",children:"Project"}),e.jsxs("select",{value:y,onChange:H=>N(H.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:"",children:"Select project"}),s.map(H=>e.jsx("option",{value:H.id,children:H.user?`${H.title} · ${H.user.displayName} (${H.user.kind})`:H.title},H.id))]})]}),q?e.jsxs("div",{className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/62",children:["This task will be created inside ",e.jsx("span",{className:"font-medium text-white",children:q.title}),q.user?` for ${q.user.displayName} (${q.user.kind})`:""," ","and started immediately."]}):null]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("span",{className:"type-label text-white/45",children:"Timer"}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_8rem]",children:[[{value:"planned",label:"20 min planned",detail:"Pomodoro-style by default."},{value:"unlimited",label:"Unlimited",detail:"Keep tracking until you stop."}].map(H=>{const _=A===H.value;return e.jsxs("button",{type:"button",className:re("rounded-[18px] border px-4 py-3 text-left transition",_?"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/65 hover:bg-white/[0.07]"),onClick:()=>T(H.value),children:[e.jsx("div",{className:"font-medium",children:H.label}),e.jsx("div",{className:"mt-1.5 text-sm leading-6 text-inherit/80",children:H.detail})]},H.value)}),e.jsxs("label",{className:re("grid gap-2",A!=="planned"&&"opacity-50"),children:[e.jsx("span",{className:"type-label text-white/45",children:"Minutes"}),e.jsx(ie,{type:"number",min:1,max:240,disabled:A!=="planned",value:F,onChange:H=>u(H.target.value)})]})]})]}),l?e.jsx("div",{className:"rounded-[18px] bg-rose-500/10 px-4 py-3 text-sm leading-6 text-rose-200",children:l}):null,e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-t border-white/6 pt-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 text-[12px] text-white/45",children:[e.jsx("div",{className:"rounded-full bg-white/[0.05] px-3 py-2",children:"Starts in progress"}),e.jsx("div",{className:"rounded-full bg-white/[0.05] px-3 py-2",children:A==="planned"?`${au(G)} min target`:"Unlimited timer"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{variant:"secondary",size:"lg",onClick:x,children:"Cancel"}),e.jsxs(W,{size:"lg",pending:r,pendingLabel:"Starting",disabled:!Q,onClick:async()=>{if(Q){if(m==="existing"&&v){await f(v,{timerMode:A,plannedDurationSeconds:G});return}await b({title:k.trim(),description:M.trim(),projectId:y,timerMode:A,plannedDurationSeconds:G})}},children:[m==="existing"?e.jsx(Sa,{className:"size-4"}):e.jsx(rm,{className:"size-4"}),"Start work",e.jsx(Cs,{className:"size-4"})]})]})]})]})}function ll({open:t,onOpenChange:s,presentation:i="responsive",...n}){const a=e.jsx(nu,{...n,onCancel:()=>s(!1)});return e.jsxs(e.Fragment,{children:[t&&i!=="mobile_sheet"?e.jsx("div",{className:"hidden lg:block",children:e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(17,24,39,0.98),rgba(11,16,28,0.97))] p-4 shadow-[0_24px_60px_rgba(3,8,18,0.28)]",children:[e.jsx("div",{className:"mb-3 flex justify-end",children:e.jsxs(W,{variant:"ghost",size:"sm",className:"px-3",onClick:()=>s(!1),children:[e.jsx(mt,{className:"size-4"}),"Close"]})}),a]})}):null,i!=="desktop_inline"?e.jsx("div",{className:i==="responsive"?"lg:hidden":"",children:e.jsx(Ra,{open:t,onOpenChange:s,eyebrow:"Start work",title:"Start work",description:"Pick an existing task or create a new one quickly, then start the timer immediately.",children:a})}):null]})}const rr=c.createContext({expanded:!1,setExpanded:()=>{}});function ol({children:t}){const[s,i]=c.useState(!1),n=c.useRef(0);return c.useEffect(()=>{if(!s)return;n.current=performance.now();let a=window.scrollY;const r=()=>{if(performance.now()-n.current<280){a=window.scrollY;return}window.scrollY-a>16&&i(!1),a=window.scrollY};return window.addEventListener("scroll",r,{passive:!0}),()=>window.removeEventListener("scroll",r)},[s]),e.jsx(rr.Provider,{value:{expanded:s,setExpanded:i},children:t})}function hi(t){const s=Math.max(0,Math.floor(t)),i=Math.floor(s/3600),n=Math.floor(s%3600/60),a=s%60;return i>0?`${i}:${String(n).padStart(2,"0")}:${String(a).padStart(2,"0")}`:`${String(n).padStart(2,"0")}:${String(a).padStart(2,"0")}`}function ru(t,s,i,n,a){const r=Math.max(1,t.length),l=Date.parse(i),d=Number.isFinite(l)?Math.max(0,Math.floor((a-l)/1e3)):0;return t.map(o=>{const x=s.find(w=>w.id===o.taskId),f=o.status==="active"?o.elapsedWallSeconds+d:o.elapsedWallSeconds,b=o.status!=="active"?0:n==="parallel"?d:n==="split"?d/r:o.isCurrent?d:0,m=o.creditedSeconds+b,h=o.timerMode==="planned"&&o.plannedDurationSeconds!==null?Math.max(0,o.plannedDurationSeconds-f):null,p=o.timerMode==="planned"&&o.plannedDurationSeconds!==null?Math.max(0,f-o.plannedDurationSeconds):0;return{run:o,title:(x==null?void 0:x.title)??o.taskTitle,wallSeconds:f,creditedSeconds:m,remainingSeconds:h,overtimeSeconds:p}}).sort((o,x)=>Number(x.run.isCurrent)-Number(o.run.isCurrent))}function wd(t,s,i,n){const[a,r]=c.useState(()=>Date.now());return c.useEffect(()=>{if(t.length===0)return;const l=window.setInterval(()=>r(Date.now()),1e3);return()=>window.clearInterval(l)},[t.length]),c.useMemo(()=>ru(t,s,i,n,a),[i,a,t,s,n])}function dl({runs:t,tasks:s,generatedAt:i,timeAccountingMode:n,pending:a,onOpenStartWork:r,onPause:l,onFocus:d}){const{expanded:o,setExpanded:x}=c.useContext(rr),f=wd(t,s,i,n),b=f.find(h=>h.run.isCurrent)??f[0]??null,m=b?f.filter(h=>h.run.id!==b.run.id):[];return b?e.jsxs("div",{className:re("flex min-h-[2.125rem] min-w-0 items-center rounded-full border border-white/8 bg-white/[0.04] transition-colors",o&&"border-[var(--primary)]/25 bg-[var(--primary)]/[0.06]"),children:[e.jsxs("button",{type:"button","aria-expanded":o,"aria-label":o?"Collapse work details":"Expand work details",className:"flex min-w-0 flex-1 cursor-pointer items-center gap-1.5 rounded-l-full py-1 pl-2.5 pr-2 transition-colors hover:bg-white/[0.04]",onClick:()=>x(h=>!h),children:[e.jsx(Sa,{className:"size-3.5 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"truncate text-[12px] font-medium text-white",children:b.title}),e.jsx("span",{className:"shrink-0 text-[11px] tabular-nums text-white/44",children:hi(b.creditedSeconds)})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 pr-1",children:[m.length>0?e.jsx("button",{type:"button",title:"Switch to next task",disabled:a,className:"inline-flex size-6 items-center justify-center rounded-full bg-[var(--primary)]/15 text-[10px] font-bold tabular-nums text-[var(--primary)] transition hover:bg-[var(--primary)]/25 disabled:pointer-events-none disabled:opacity-70",onClick:()=>void d(m[0].run.id),children:f.length}):null,e.jsx("button",{type:"button",title:"Stop",disabled:a,className:"inline-flex size-6 items-center justify-center rounded-full text-white/50 transition hover:bg-white/[0.1] hover:text-white disabled:pointer-events-none disabled:opacity-70",onClick:()=>void l(b.run.id),children:e.jsx(lm,{className:"size-2.5 fill-current"})}),e.jsx("button",{type:"button",title:"Start new work",disabled:a,className:"inline-flex size-6 items-center justify-center rounded-full text-white/50 transition hover:bg-white/[0.1] hover:text-white disabled:pointer-events-none disabled:opacity-70",onClick:()=>r(),children:e.jsx(Cs,{className:"size-2.5 fill-current"})})]})]}):e.jsxs("div",{className:"flex min-h-[2.125rem] min-w-0 items-center gap-1.5 rounded-full border border-white/8 bg-white/[0.04] py-1 pl-2.5 pr-1",children:[e.jsx(Sa,{className:"size-3.5 shrink-0 text-white/48"}),e.jsx("span",{className:"truncate text-[12px] text-white/48",children:"No active work"}),e.jsx("button",{type:"button",className:"ml-auto inline-flex h-[1.5rem] shrink-0 items-center rounded-full bg-white/10 px-2 text-[11px] font-medium text-white transition hover:bg-white/15",onClick:r,children:"Start work"})]})}function cl({runs:t,tasks:s,generatedAt:i,timeAccountingMode:n,pending:a,onOpenStartWork:r,onFocus:l,onPause:d,onComplete:o}){const{expanded:x}=c.useContext(rr),f=wd(t,s,i,n),b=f.find(p=>p.run.isCurrent)??f[0]??null,m=b?f.filter(p=>p.run.id!==b.run.id):[],h=n==="split"&&f.length>1?`Split across ${f.length} active tasks`:n==="parallel"&&f.length>1?`Parallel time across ${f.length} active tasks`:n==="primary_only"&&f.length>1?"Only the current task is earning credited time":null;return b?e.jsx(Ta,{initial:!1,children:x?e.jsx(wt.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.25,ease:"easeOut"},className:"overflow-hidden",children:e.jsxs("div",{className:"mt-2 rounded-2xl border border-white/8 bg-[linear-gradient(180deg,rgba(192,193,255,0.10),rgba(192,193,255,0.03))] p-4",children:[e.jsxs("div",{className:"flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(O,{tone:"signal",className:"text-white/82",children:"Current task"}),e.jsx(O,{tone:"meta",children:b.run.timerMode==="planned"?"Planned timer":"Unlimited timer"}),h?e.jsx(O,{tone:"meta",children:h}):null]}),e.jsx("div",{className:"mt-3 text-xl font-medium text-white md:text-2xl",children:b.title}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-4 text-sm text-white/62",children:[e.jsxs("span",{children:[hi(b.creditedSeconds)," credited"]}),e.jsxs("span",{children:[hi(b.wallSeconds)," wall time"]}),b.run.timerMode==="planned"?b.overtimeSeconds>0?e.jsxs("span",{className:"text-amber-200",children:["+",hi(b.overtimeSeconds)," overtime"]}):e.jsxs("span",{children:[hi(b.remainingSeconds??0)," remaining"]}):e.jsx("span",{children:"Unlimited session"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(W,{variant:"secondary",pending:a,pendingLabel:"Opening",onClick:r,children:[e.jsx(Sa,{className:"size-4"}),"Start work"]}),e.jsxs(W,{variant:"secondary",pending:a,pendingLabel:"Pausing",onClick:()=>void d(b.run.id),children:[e.jsx(om,{className:"size-4"}),"Pause"]}),e.jsxs(W,{pending:a,pendingLabel:"Completing",onClick:()=>void o(b.run.id),children:[e.jsx(Hi,{className:"size-4"}),"Complete"]})]})]}),m.length>0?e.jsx("div",{className:"mt-4 grid gap-2 lg:grid-cols-2",children:m.map(p=>e.jsxs("button",{type:"button",className:re("flex items-center justify-between gap-3 rounded-2xl bg-white/[0.04] px-4 py-3 text-left transition hover:bg-white/[0.08]",a&&"pointer-events-none opacity-70"),onClick:()=>void l(p.run.id),children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white/88",children:p.title}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-3 text-[12px] text-white/48",children:[e.jsxs("span",{children:[hi(p.creditedSeconds)," credited"]}),e.jsx("span",{children:p.run.timerMode==="planned"?"planned":"unlimited"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-[12px] text-white/42",children:[e.jsx(yi,{className:"size-3.5"}),"Switch"]})]},p.run.id))}):null]})},"timer-rail-detail"):null}):null}function se({className:t,...s}){return e.jsx("div",{className:re("w-full max-w-full min-w-0 rounded-[var(--radius-card)] bg-[var(--card-gradient)] p-5 shadow-[var(--card-shadow)] backdrop-blur-sm",t),...s})}class qa extends Error{constructor(i){super(i.message);Ai(this,"status");Ai(this,"code");Ai(this,"details");Ai(this,"requestPath");this.name="ForgeApiError",this.status=i.status,this.code=i.code,this.details=i.details??[],this.requestPath=i.requestPath}}function lu(t){return t instanceof qa?{title:`Request failed (${t.status})`,description:t.details.length>0?`${t.message} ${t.details.map(s=>`${s.path}: ${s.message}`).join(" · ")}`:t.message,code:t.code}:t instanceof Error?{title:"Something went wrong",description:t.message,code:"unknown_error"}:{title:"Something went wrong",description:"Unexpected API failure.",code:"unknown_error"}}function xt({eyebrow:t,title:s,description:i}){const{t:n}=at();return e.jsxs(se,{className:"surface-pulse ambient-glow mx-auto grid max-w-2xl gap-4 text-center",children:[e.jsx("div",{className:"type-label text-white/40",children:t??n("common.labels.loading")}),e.jsx("div",{className:"type-display-section text-white",children:s??n("common.pageState.loadingTitle")}),e.jsx("p",{className:"type-body mx-auto max-w-xl text-white/60",children:i??n("common.pageState.loadingDescription")}),e.jsxs("div",{className:"mx-auto flex min-h-11 items-center gap-3 rounded-full bg-white/[0.05] px-4 py-3 text-white/60",children:[e.jsx(tr,{tone:"subtle",className:"size-3.5"}),e.jsx("span",{className:"type-meta",children:n("common.labels.syncInProgress")})]})]})}function Oe({error:t,onRetry:s,eyebrow:i}){const{t:n}=at(),{title:a,description:r,code:l}=lu(t);return e.jsxs(se,{className:"mx-auto grid max-w-2xl gap-4",children:[e.jsx("div",{className:"type-label text-rose-200/72",children:i??n("common.labels.connectionState")}),e.jsx("div",{className:"type-display-section text-white",children:a}),e.jsx("p",{className:"type-body text-white/62",children:r}),e.jsx("div",{className:"type-meta text-white/40",children:n("common.labels.errorCode",{code:l})}),s?e.jsx("div",{className:"flex flex-wrap gap-3",children:e.jsxs(W,{type:"button",variant:"secondary",onClick:s,children:[e.jsx(ps,{className:"mr-2 size-4"}),n("common.actions.retry")]})}):null]})}function gt({eyebrow:t,title:s,description:i,action:n}){const{t:a}=at();return e.jsxs(se,{className:"mx-auto grid max-w-2xl gap-4 text-center",children:[e.jsx("div",{className:"type-label text-white/38",children:t??a("common.labels.loading")}),e.jsx("div",{className:"type-display-section text-white",children:s}),e.jsx("p",{className:"type-body mx-auto max-w-xl text-white/60",children:i}),n?e.jsx("div",{className:"flex justify-center",children:n}):null]})}function vd(t){const s=t.startsWith("/")?t:`/${t}`;return s.endsWith("/")?s:`${s}/`}function ou(t){const s=vd(t);return s==="/"?"/":s.endsWith("/")?s.slice(0,-1):s}function du(){return new URL(vd("/forge/"),window.location.origin)}function Ws(t){if(t.startsWith("/api/"))return t;const s=t.startsWith("/")?t.slice(1):t;return new URL(s,du()).pathname}function cu(){const t=We();c.useEffect(()=>{const s=new EventSource(Ws("/api/v1/events/stream")),i=()=>{Promise.all([t.invalidateQueries({queryKey:["forge-snapshot"]}),t.invalidateQueries({queryKey:["task-context"]})])};return s.addEventListener("snapshot",i),s.addEventListener("activity",i),s.onerror=()=>{s.close()},()=>{s.removeEventListener("snapshot",i),s.removeEventListener("activity",i),s.close()}},[t])}function $n(t,s=0){return t===null||typeof t=="boolean"||typeof t=="number"||typeof t=="string"?t:typeof t=="bigint"?t.toString():t instanceof Error?{name:t.name,message:t.message,stack:t.stack??null}:Array.isArray(t)?s>=3?`[Array(${t.length})]`:t.slice(0,20).map(i=>$n(i,s+1)):t&&typeof t=="object"?s>=3?"[Object]":Object.fromEntries(Object.entries(t).slice(0,30).map(([i,n])=>[i,$n(n,s+1)])):String(t)}function mu(t){return t?Object.fromEntries(Object.entries(t).map(([s,i])=>[s,$n(i)])):{}}async function Ma(t){try{await fetch(Ws("/api/v1/diagnostics/logs"),{method:"POST",credentials:"same-origin",keepalive:!0,headers:{"content-type":"application/json","x-forge-source":"ui"},body:JSON.stringify({...t,source:t.source??"ui",details:mu(t.details)})})}catch{}}function hu(t){return s=>Ma({...t,...s})}const uu={allowWorkBlockKinds:[],blockWorkBlockKinds:[],allowCalendarIds:[],blockCalendarIds:[],allowEventTypes:[],blockEventTypes:[],allowEventKeywords:[],blockEventKeywords:[],allowAvailability:[],blockAvailability:[]};function ws(t){return{id:(t==null?void 0:t.id)??"",title:(t==null?void 0:t.title)??"",description:(t==null?void 0:t.description)??"",status:(t==null?void 0:t.status)??"backlog",priority:(t==null?void 0:t.priority)??"medium",owner:(t==null?void 0:t.owner)??"Albert",goalId:(t==null?void 0:t.goalId)??null,projectId:(t==null?void 0:t.projectId)??null,dueDate:(t==null?void 0:t.dueDate)??null,effort:(t==null?void 0:t.effort)??"deep",energy:(t==null?void 0:t.energy)??"steady",points:(t==null?void 0:t.points)??0,plannedDurationSeconds:(t==null?void 0:t.plannedDurationSeconds)??null,schedulingRules:(t==null?void 0:t.schedulingRules)??null,sortOrder:(t==null?void 0:t.sortOrder)??0,completedAt:(t==null?void 0:t.completedAt)??null,createdAt:(t==null?void 0:t.createdAt)??new Date(0).toISOString(),updatedAt:(t==null?void 0:t.updatedAt)??new Date(0).toISOString(),tagIds:(t==null?void 0:t.tagIds)??[],userId:(t==null?void 0:t.userId)??null,user:(t==null?void 0:t.user)??null,time:(t==null?void 0:t.time)??{totalTrackedSeconds:0,totalCreditedSeconds:0,liveTrackedSeconds:0,liveCreditedSeconds:0,manualAdjustedSeconds:0,activeRunCount:0,hasCurrentRun:!1,currentRunId:null}}}function rn(t){return{id:(t==null?void 0:t.id)??"",title:(t==null?void 0:t.title)??"",description:(t==null?void 0:t.description)??"",horizon:(t==null?void 0:t.horizon)==="quarter"||(t==null?void 0:t.horizon)==="lifetime"?t.horizon:"year",status:(t==null?void 0:t.status)==="paused"||(t==null?void 0:t.status)==="completed"?t.status:"active",targetPoints:(t==null?void 0:t.targetPoints)??0,themeColor:(t==null?void 0:t.themeColor)??"#c8a46b",createdAt:(t==null?void 0:t.createdAt)??new Date(0).toISOString(),updatedAt:(t==null?void 0:t.updatedAt)??new Date(0).toISOString(),tagIds:(t==null?void 0:t.tagIds)??[],userId:(t==null?void 0:t.userId)??null,user:(t==null?void 0:t.user)??null}}function ln(t){return{id:(t==null?void 0:t.id)??"",name:(t==null?void 0:t.name)??"",kind:(t==null?void 0:t.kind)==="value"||(t==null?void 0:t.kind)==="execution"?t.kind:"category",color:(t==null?void 0:t.color)??"#71717a",description:(t==null?void 0:t.description)??"",userId:(t==null?void 0:t.userId)??null,user:(t==null?void 0:t.user)??null}}function on(t){return{id:(t==null?void 0:t.id)??"",goalId:(t==null?void 0:t.goalId)??"",title:(t==null?void 0:t.title)??"",description:(t==null?void 0:t.description)??(t==null?void 0:t.summary)??"",status:(t==null?void 0:t.status)==="paused"||(t==null?void 0:t.status)==="completed"?t.status:"active",targetPoints:(t==null?void 0:t.targetPoints)??(t==null?void 0:t.totalPoints)??0,themeColor:(t==null?void 0:t.themeColor)??"#c0c1ff",schedulingRules:(t==null?void 0:t.schedulingRules)??uu,createdAt:(t==null?void 0:t.createdAt)??new Date(0).toISOString(),updatedAt:(t==null?void 0:t.updatedAt)??new Date(0).toISOString(),goalTitle:(t==null?void 0:t.goalTitle)??"",activeTaskCount:(t==null?void 0:t.activeTaskCount)??0,completedTaskCount:(t==null?void 0:t.completedTaskCount)??0,totalTasks:(t==null?void 0:t.totalTasks)??0,earnedPoints:(t==null?void 0:t.earnedPoints)??(t==null?void 0:t.totalPoints)??0,progress:(t==null?void 0:t.progress)??0,nextTaskId:(t==null?void 0:t.nextTaskId)??null,nextTaskTitle:(t==null?void 0:t.nextTaskTitle)??null,momentumLabel:(t==null?void 0:t.momentumLabel)??"No momentum yet",userId:(t==null?void 0:t.userId)??null,user:(t==null?void 0:t.user)??null,time:(t==null?void 0:t.time)??{totalTrackedSeconds:0,totalCreditedSeconds:0,liveTrackedSeconds:0,liveCreditedSeconds:0,manualAdjustedSeconds:0,activeRunCount:0,hasCurrentRun:!1,currentRunId:null}}}function sa(t){return{id:(t==null?void 0:t.id)??"",title:(t==null?void 0:t.title)??"",description:(t==null?void 0:t.description)??"",status:(t==null?void 0:t.status)??"active",polarity:(t==null?void 0:t.polarity)??"positive",frequency:(t==null?void 0:t.frequency)??"daily",targetCount:(t==null?void 0:t.targetCount)??1,weekDays:(t==null?void 0:t.weekDays)??[],linkedGoalIds:(t==null?void 0:t.linkedGoalIds)??[],linkedProjectIds:(t==null?void 0:t.linkedProjectIds)??[],linkedTaskIds:(t==null?void 0:t.linkedTaskIds)??[],linkedValueIds:(t==null?void 0:t.linkedValueIds)??[],linkedPatternIds:(t==null?void 0:t.linkedPatternIds)??[],linkedBehaviorIds:(t==null?void 0:t.linkedBehaviorIds)??[],linkedBeliefIds:(t==null?void 0:t.linkedBeliefIds)??[],linkedModeIds:(t==null?void 0:t.linkedModeIds)??[],linkedReportIds:(t==null?void 0:t.linkedReportIds)??[],linkedBehaviorId:(t==null?void 0:t.linkedBehaviorId)??null,linkedBehaviorTitle:(t==null?void 0:t.linkedBehaviorTitle)??null,linkedBehaviorTitles:(t==null?void 0:t.linkedBehaviorTitles)??[],rewardXp:(t==null?void 0:t.rewardXp)??12,penaltyXp:(t==null?void 0:t.penaltyXp)??8,generatedHealthEventTemplate:(t==null?void 0:t.generatedHealthEventTemplate)??{enabled:!1,workoutType:"",title:"",durationMinutes:60,xpReward:0,tags:[],links:[],notesTemplate:""},createdAt:(t==null?void 0:t.createdAt)??new Date(0).toISOString(),updatedAt:(t==null?void 0:t.updatedAt)??new Date(0).toISOString(),lastCheckInAt:(t==null?void 0:t.lastCheckInAt)??null,lastCheckInStatus:(t==null?void 0:t.lastCheckInStatus)??null,streakCount:(t==null?void 0:t.streakCount)??0,completionRate:(t==null?void 0:t.completionRate)??0,dueToday:(t==null?void 0:t.dueToday)??!1,userId:(t==null?void 0:t.userId)??null,user:(t==null?void 0:t.user)??null,checkIns:(t==null?void 0:t.checkIns)??[]}}function ml(t){return{id:(t==null?void 0:t.id)??"",kind:(t==null?void 0:t.kind)??"human",handle:(t==null?void 0:t.handle)??"",displayName:(t==null?void 0:t.displayName)??"",description:(t==null?void 0:t.description)??"",accentColor:(t==null?void 0:t.accentColor)??"#c0c1ff",createdAt:(t==null?void 0:t.createdAt)??new Date(0).toISOString(),updatedAt:(t==null?void 0:t.updatedAt)??new Date(0).toISOString()}}function pu(t){return{id:(t==null?void 0:t.id)??"",title:(t==null?void 0:t.title)??"",overview:(t==null?void 0:t.overview)??"",endStateDescription:(t==null?void 0:t.endStateDescription)??"",status:(t==null?void 0:t.status)==="paused"||(t==null?void 0:t.status)==="completed"?t.status:"active",targetGoalIds:(t==null?void 0:t.targetGoalIds)??[],targetProjectIds:(t==null?void 0:t.targetProjectIds)??[],linkedEntities:(t==null?void 0:t.linkedEntities)??[],graph:(t==null?void 0:t.graph)??{nodes:[],edges:[]},metrics:(t==null?void 0:t.metrics)??{alignmentScore:0,planCoverageScore:0,sequencingScore:100,scopeDisciplineScore:100,qualityScore:0,targetProgressScore:0,completedNodeCount:0,startedNodeCount:0,readyNodeCount:0,totalNodeCount:1,completedTargetCount:0,totalTargetCount:0,offPlanEntityCount:0,offPlanActiveEntityCount:0,offPlanCompletedEntityCount:0,activeNodeIds:[],nextNodeIds:[],blockedNodeIds:[],outOfOrderNodeIds:[]},isLocked:(t==null?void 0:t.isLocked)??!1,lockedAt:(t==null?void 0:t.lockedAt)??null,lockedByUserId:(t==null?void 0:t.lockedByUserId)??null,lockedByUser:(t==null?void 0:t.lockedByUser)??null,createdAt:(t==null?void 0:t.createdAt)??new Date(0).toISOString(),updatedAt:(t==null?void 0:t.updatedAt)??new Date(0).toISOString(),userId:(t==null?void 0:t.userId)??null,user:(t==null?void 0:t.user)??null}}function xu(t){var r,l,d,o,x,f,b,m,h,p,w,v,I,k,S,M,P,y,N,A,T,F,u,j,L,q,G,Q,ne,H,_,U,R,C,J,ee,le,oe,ue,me,$,ce,E,z,K,je,V,D,X,he,ye,ze,fe,Pe,Ge,Z,He,Ue,Qe,ct,zt,qt,Pt,Mt,Et,te,we,Me,Ve,Se,xe,Ie,Ee,et,Fe,ut,Te,rt,kt,Bt,ds,Ds,$s,Os,g,B,de,be,Ne,lt,fs,cs,Pi,Mi,Ei,Cr,Ir,Tr,Pr,Mr,Er,Ar,Lr,Dr,$r,Or,Fr,_r,Rr,zr,qr,Br,Kr,Ur,Qr;const s=t,i=(s.projects??s.campaigns??[]).map(on),n=(((r=s.dashboard)==null?void 0:r.projects)??((l=s.dashboard)==null?void 0:l.campaigns)??i).map(on),a=(((d=s.overview)==null?void 0:d.projects)??((o=s.overview)==null?void 0:o.campaigns)??n).map(on);return{...t,meta:{apiVersion:"v1",transport:"rest+sse",generatedAt:((x=t.meta)==null?void 0:x.generatedAt)??new Date().toISOString(),backend:((f=t.meta)==null?void 0:f.backend)??"forge-node-runtime",mode:((b=t.meta)==null?void 0:b.mode)??"transitional-node"},metrics:{totalXp:((m=t.metrics)==null?void 0:m.totalXp)??0,level:((h=t.metrics)==null?void 0:h.level)??1,currentLevelXp:((p=t.metrics)==null?void 0:p.currentLevelXp)??0,nextLevelXp:((w=t.metrics)==null?void 0:w.nextLevelXp)??120,weeklyXp:((v=t.metrics)==null?void 0:v.weeklyXp)??0,streakDays:((I=t.metrics)==null?void 0:I.streakDays)??0,comboMultiplier:((k=t.metrics)==null?void 0:k.comboMultiplier)??1,momentumScore:((S=t.metrics)==null?void 0:S.momentumScore)??0,topGoalId:((M=t.metrics)==null?void 0:M.topGoalId)??null,topGoalTitle:((P=t.metrics)==null?void 0:P.topGoalTitle)??null},users:(t.users??[]).map(ml),strategies:(t.strategies??[]).map(pu),userScope:{selectedUserIds:((y=t.userScope)==null?void 0:y.selectedUserIds)??[],selectedUsers:(((N=t.userScope)==null?void 0:N.selectedUsers)??[]).map(ml)},dashboard:{stats:{totalPoints:((T=(A=t.dashboard)==null?void 0:A.stats)==null?void 0:T.totalPoints)??0,completedThisWeek:((u=(F=t.dashboard)==null?void 0:F.stats)==null?void 0:u.completedThisWeek)??0,activeGoals:((L=(j=t.dashboard)==null?void 0:j.stats)==null?void 0:L.activeGoals)??0,alignmentScore:((G=(q=t.dashboard)==null?void 0:q.stats)==null?void 0:G.alignmentScore)??0,focusTasks:((ne=(Q=t.dashboard)==null?void 0:Q.stats)==null?void 0:ne.focusTasks)??0,overdueTasks:((_=(H=t.dashboard)==null?void 0:H.stats)==null?void 0:_.overdueTasks)??0,dueThisWeek:((R=(U=t.dashboard)==null?void 0:U.stats)==null?void 0:R.dueThisWeek)??0},goals:(((C=t.dashboard)==null?void 0:C.goals)??[]).map(Xt=>({...Xt,...rn(Xt)})),projects:n,tasks:(((J=t.dashboard)==null?void 0:J.tasks)??[]).map(ws),habits:(((ee=t.dashboard)==null?void 0:ee.habits)??t.habits??[]).map(sa),tags:(((le=t.dashboard)==null?void 0:le.tags)??[]).map(ln),suggestedTags:(((oe=t.dashboard)==null?void 0:oe.suggestedTags)??[]).map(ln),owners:((ue=t.dashboard)==null?void 0:ue.owners)??[],executionBuckets:(((me=t.dashboard)==null?void 0:me.executionBuckets)??[]).map(Xt=>({...Xt,tasks:(Xt.tasks??[]).map(ws)})),gamification:(($=t.dashboard)==null?void 0:$.gamification)??{totalXp:((ce=t.metrics)==null?void 0:ce.totalXp)??0,level:((E=t.metrics)==null?void 0:E.level)??1,currentLevelXp:((z=t.metrics)==null?void 0:z.currentLevelXp)??0,nextLevelXp:((K=t.metrics)==null?void 0:K.nextLevelXp)??120,weeklyXp:((je=t.metrics)==null?void 0:je.weeklyXp)??0,streakDays:((V=t.metrics)==null?void 0:V.streakDays)??0,comboMultiplier:((D=t.metrics)==null?void 0:D.comboMultiplier)??1,momentumScore:((X=t.metrics)==null?void 0:X.momentumScore)??0,topGoalId:((he=t.metrics)==null?void 0:he.topGoalId)??null,topGoalTitle:((ye=t.metrics)==null?void 0:ye.topGoalTitle)??null},achievements:((ze=t.dashboard)==null?void 0:ze.achievements)??[],milestoneRewards:((fe=t.dashboard)==null?void 0:fe.milestoneRewards)??[],recentActivity:((Pe=t.dashboard)==null?void 0:Pe.recentActivity)??[],notesSummaryByEntity:((Ge=t.dashboard)==null?void 0:Ge.notesSummaryByEntity)??{}},overview:{generatedAt:((Z=t.overview)==null?void 0:Z.generatedAt)??new Date().toISOString(),strategicHeader:{streakDays:((Ue=(He=t.overview)==null?void 0:He.strategicHeader)==null?void 0:Ue.streakDays)??((Qe=t.metrics)==null?void 0:Qe.streakDays)??0,level:((zt=(ct=t.overview)==null?void 0:ct.strategicHeader)==null?void 0:zt.level)??((qt=t.metrics)==null?void 0:qt.level)??1,totalXp:((Mt=(Pt=t.overview)==null?void 0:Pt.strategicHeader)==null?void 0:Mt.totalXp)??((Et=t.metrics)==null?void 0:Et.totalXp)??0,currentLevelXp:((we=(te=t.overview)==null?void 0:te.strategicHeader)==null?void 0:we.currentLevelXp)??((Me=t.metrics)==null?void 0:Me.currentLevelXp)??0,nextLevelXp:((Se=(Ve=t.overview)==null?void 0:Ve.strategicHeader)==null?void 0:Se.nextLevelXp)??((xe=t.metrics)==null?void 0:xe.nextLevelXp)??120,momentumScore:((Ee=(Ie=t.overview)==null?void 0:Ie.strategicHeader)==null?void 0:Ee.momentumScore)??((et=t.metrics)==null?void 0:et.momentumScore)??0,focusTasks:((ut=(Fe=t.overview)==null?void 0:Fe.strategicHeader)==null?void 0:ut.focusTasks)??0,overdueTasks:((rt=(Te=t.overview)==null?void 0:Te.strategicHeader)==null?void 0:rt.overdueTasks)??0},projects:a,activeGoals:(((kt=t.overview)==null?void 0:kt.activeGoals)??[]).map(Xt=>({...Xt,...rn(Xt)})),topTasks:(((Bt=t.overview)==null?void 0:Bt.topTasks)??[]).map(ws),dueHabits:(((ds=t.overview)==null?void 0:ds.dueHabits)??((Ds=t.today)==null?void 0:Ds.dueHabits)??(($s=t.dashboard)==null?void 0:$s.habits)??[]).map(sa),recentEvidence:((Os=t.overview)==null?void 0:Os.recentEvidence)??[],achievements:((g=t.overview)==null?void 0:g.achievements)??[],domainBalance:((B=t.overview)==null?void 0:B.domainBalance)??[],neglectedGoals:((de=t.overview)==null?void 0:de.neglectedGoals)??[]},today:{generatedAt:((be=t.today)==null?void 0:be.generatedAt)??new Date().toISOString(),directive:{task:(lt=(Ne=t.today)==null?void 0:Ne.directive)!=null&<.task?ws(t.today.directive.task):null,goalTitle:((cs=(fs=t.today)==null?void 0:fs.directive)==null?void 0:cs.goalTitle)??null,rewardXp:((Mi=(Pi=t.today)==null?void 0:Pi.directive)==null?void 0:Mi.rewardXp)??0,sessionLabel:((Cr=(Ei=t.today)==null?void 0:Ei.directive)==null?void 0:Cr.sessionLabel)??"No active session"},timeline:(((Ir=t.today)==null?void 0:Ir.timeline)??[]).map(Xt=>({...Xt,tasks:(Xt.tasks??[]).map(ws)})),dueHabits:(((Tr=t.today)==null?void 0:Tr.dueHabits)??((Pr=t.overview)==null?void 0:Pr.dueHabits)??((Mr=t.dashboard)==null?void 0:Mr.habits)??[]).map(sa),dailyQuests:((Er=t.today)==null?void 0:Er.dailyQuests)??[],milestoneRewards:((Ar=t.today)==null?void 0:Ar.milestoneRewards)??[],recentHabitRewards:((Lr=t.today)==null?void 0:Lr.recentHabitRewards)??[],momentum:{streakDays:(($r=(Dr=t.today)==null?void 0:Dr.momentum)==null?void 0:$r.streakDays)??0,momentumScore:((Fr=(Or=t.today)==null?void 0:Or.momentum)==null?void 0:Fr.momentumScore)??0,recoveryHint:((Rr=(_r=t.today)==null?void 0:_r.momentum)==null?void 0:Rr.recoveryHint)??""}},risk:{generatedAt:((zr=t.risk)==null?void 0:zr.generatedAt)??new Date().toISOString(),overdueTasks:(((qr=t.risk)==null?void 0:qr.overdueTasks)??[]).map(ws),blockedTasks:(((Br=t.risk)==null?void 0:Br.blockedTasks)??[]).map(ws),neglectedGoals:((Kr=t.risk)==null?void 0:Kr.neglectedGoals)??[],summary:((Ur=t.risk)==null?void 0:Ur.summary)??""},goals:(t.goals??[]).map(rn),projects:i,tags:(t.tags??[]).map(ln),tasks:(t.tasks??[]).map(ws),habits:(t.habits??((Qr=t.dashboard)==null?void 0:Qr.habits)??[]).map(sa),activity:t.activity??[],activeTaskRuns:t.activeTaskRuns??[]}}function lr(t){const s=typeof t.location=="string"?t.location:"",i=t.place??{label:s,address:"",timezone:"",latitude:null,longitude:null,source:"",externalPlaceId:""};return{...t,place:{label:i.label||s,address:i.address??"",timezone:i.timezone??"",latitude:i.latitude??null,longitude:i.longitude??null,source:i.source??"",externalPlaceId:i.externalPlaceId??""}}}function gu(t){return{...t,events:t.events.map(lr)}}async function bu(t){const s=await t.text();if(!s)return null;try{return JSON.parse(s)}catch{return s}}async function ae(t,s){const i=new Headers(s==null?void 0:s.headers);i.set("x-forge-source","ui"),(s==null?void 0:s.body)!==void 0&&!(typeof FormData<"u"&&s.body instanceof FormData)&&!i.has("content-type")&&i.set("content-type","application/json");let n;try{n=await fetch(Ws(t),{credentials:"same-origin",headers:i,...s})}catch(r){throw t!=="/api/v1/diagnostics/logs"&&Ma({level:"error",scope:"frontend_api",eventKey:"request_network_failure",message:`API request failed before reaching Forge: ${t}`,route:t,functionName:"request",details:{error:r instanceof Error?{name:r.name,message:r.message,stack:r.stack??null}:String(r)}}),r}const a=await bu(n);if(!n.ok){const r=typeof a=="object"&&a!==null?a:null,l=Array.isArray(r==null?void 0:r.details)?r.details:[];throw t!=="/api/v1/diagnostics/logs"&&Ma({level:n.status>=500?"error":"warning",scope:"frontend_api",eventKey:"request_failed",message:`API request failed: ${t}`,route:t,functionName:"request",details:{statusCode:n.status,code:typeof(r==null?void 0:r.code)=="string"?r.code:typeof(r==null?void 0:r.error)=="string"?r.error:"request_failed",response:typeof a=="string"||a&&typeof a=="object"?a:null,validationIssues:l}}),new qa({status:n.status,code:typeof(r==null?void 0:r.code)=="string"?r.code:typeof(r==null?void 0:r.error)=="string"?r.error:"request_failed",message:typeof(r==null?void 0:r.error)=="string"?r.error:typeof(r==null?void 0:r.message)=="string"?r.message:typeof a=="string"?a:`Request failed: ${n.status}`,requestPath:t,details:l})}return a}function or(t){return t.map(s=>({contentMarkdown:s.contentMarkdown.trim(),author:s.author.trim()||null})).filter(s=>s.contentMarkdown.length>0)}const fu="forge.selected-user-ids";function wu(){if(typeof window>"u")return[];try{const t=window.localStorage.getItem(fu);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean):[]}catch{return[]}}function vu(t){return t??wu()}function Ft(t){return Array.isArray(t)?t.filter(s=>typeof s=="string"):void 0}function Ct(t,s){for(const i of vu(s))i.trim()&&t.append("userIds",i.trim())}function Ci(){return ae("/api/v1/auth/operator-session")}function yu(){return ae("/api/v1/auth/operator-session",{method:"DELETE"})}function yd(t){const s=new URLSearchParams;Ct(s,Ft(t));const i=s.size>0?`?${s.toString()}`:"";return ae(`/api/v1/context${i}`).then(xu)}function hl(t){const s=new URLSearchParams;t.userId&&s.set("userId",t.userId),t.domain&&s.set("domain",t.domain),t.contextId&&s.set("contextId",t.contextId);const i=s.size>0?`?${s.toString()}`:"";return ae(`/api/v1/preferences/workspace${i}`)}function ju(t){return ae("/api/v1/preferences/game/start",{method:"POST",body:JSON.stringify(t)})}function Nu(t){return ae("/api/v1/preferences/catalogs",{method:"POST",body:JSON.stringify(t)})}function ku(t,s){return ae(`/api/v1/preferences/catalogs/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Su(t){return ae(`/api/v1/preferences/catalogs/${t}`,{method:"DELETE"})}function Cu(t){return ae("/api/v1/preferences/catalog-items",{method:"POST",body:JSON.stringify(t)})}function Iu(t,s){return ae(`/api/v1/preferences/catalog-items/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Tu(t){return ae(`/api/v1/preferences/catalog-items/${t}`,{method:"DELETE"})}function Pu(t){return ae("/api/v1/preferences/contexts",{method:"POST",body:JSON.stringify(t)})}function Mu(t,s){return ae(`/api/v1/preferences/contexts/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Eu(t){return ae("/api/v1/preferences/contexts/merge",{method:"POST",body:JSON.stringify(t)})}function Au(t){return ae("/api/v1/preferences/items",{method:"POST",body:JSON.stringify(t)})}function Lu(t,s){return ae(`/api/v1/preferences/items/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function On(t){return ae("/api/v1/preferences/items/from-entity",{method:"POST",body:JSON.stringify(t)})}function Du(t){return ae("/api/v1/preferences/judgments",{method:"POST",body:JSON.stringify(t)})}function $u(t){return ae("/api/v1/preferences/signals",{method:"POST",body:JSON.stringify(t)})}function Ou(t,s){return ae(`/api/v1/preferences/items/${t}/score`,{method:"PATCH",body:JSON.stringify(s)})}function Fu(t){const s=new URLSearchParams;Ct(s,Ft(t));const i=s.size>0?`?${s.toString()}`:"";return ae(`/api/v1/insights${i}`)}function Ba(t){const s=new URLSearchParams;Ct(s,Ft(t));const i=s.size>0?`?${s.toString()}`:"";return ae(`/api/v1/psyche/overview${i}`)}function ls(t){const s=new URLSearchParams;Ct(s,Ft(t));const i=s.size>0?`?${s.toString()}`:"";return ae(`/api/v1/psyche/values${i}`)}function Ii(t){return ae("/api/v1/psyche/values",{method:"POST",body:JSON.stringify(t)})}function _u(t,s){return ae(`/api/v1/psyche/values/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Xs(t){const s=new URLSearchParams;Ct(s,Ft(t));const i=s.size>0?`?${s.toString()}`:"";return ae(`/api/v1/psyche/patterns${i}`)}function dr(t){return ae("/api/v1/psyche/patterns",{method:"POST",body:JSON.stringify(t)})}function Ru(t,s){return ae(`/api/v1/psyche/patterns/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function os(t){const s=new URLSearchParams;Ct(s,Ft(t));const i=s.size>0?`?${s.toString()}`:"";return ae(`/api/v1/psyche/behaviors${i}`)}function Ka(t){return ae("/api/v1/psyche/behaviors",{method:"POST",body:JSON.stringify(t)})}function zu(t,s){return ae(`/api/v1/psyche/behaviors/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Xi(){return ae("/api/v1/psyche/schema-catalog")}function As(t){const s=new URLSearchParams;Ct(s,Ft(t));const i=s.size>0?`?${s.toString()}`:"";return ae(`/api/v1/psyche/beliefs${i}`)}function cr(t){return ae("/api/v1/psyche/beliefs",{method:"POST",body:JSON.stringify(t)})}function qu(t,s){return ae(`/api/v1/psyche/beliefs/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Ls(t){const s=new URLSearchParams;Ct(s,Ft(t));const i=s.size>0?`?${s.toString()}`:"";return ae(`/api/v1/psyche/modes${i}`)}function Ji(t){return ae("/api/v1/psyche/modes",{method:"POST",body:JSON.stringify(t)})}function Bu(t,s){return ae(`/api/v1/psyche/modes/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Ku(){return ae("/api/v1/psyche/mode-guides")}function Uu(t){return ae("/api/v1/psyche/mode-guides",{method:"POST",body:JSON.stringify(t)})}function jd(){return ae("/api/v1/psyche/event-types")}function Nd(){return ae("/api/v1/psyche/emotions")}function Ti(t){const s=new URLSearchParams;Ct(s,Ft(t));const i=s.size>0?`?${s.toString()}`:"";return ae(`/api/v1/psyche/reports${i}`)}function kd(t){return ae("/api/v1/psyche/reports",{method:"POST",body:JSON.stringify(t)})}function Qu(t){return ae(`/api/v1/psyche/reports/${t}`)}function Wu(t,s){return ae(`/api/v1/psyche/reports/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Sd(t={}){const s=new URLSearchParams;t.linkedEntityType&&s.set("linkedEntityType",t.linkedEntityType),t.linkedEntityId&&s.set("linkedEntityId",t.linkedEntityId),t.anchorKey!==void 0&&t.anchorKey!==null&&s.set("anchorKey",t.anchorKey);for(const n of t.linkedTo??[])s.append("linkedTo",`${n.entityType}:${n.entityId}`);for(const n of t.tags??[])n.trim()&&s.append("tags",n.trim());for(const n of t.textTerms??[])n.trim()&&s.append("textTerms",n.trim());t.author&&s.set("author",t.author),t.query&&s.set("query",t.query),Ct(s,t.userIds),t.updatedFrom&&s.set("updatedFrom",t.updatedFrom),t.updatedTo&&s.set("updatedTo",t.updatedTo),t.limit&&s.set("limit",String(t.limit));const i=s.size>0?`?${s.toString()}`:"";return ae(`/api/v1/notes${i}`)}function mr(t){return ae("/api/v1/notes",{method:"POST",body:JSON.stringify(t)})}function Cd(t,s){return ae(`/api/v1/notes/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Id(t,s="soft"){const i=s==="soft"?"":`?mode=${s}`;return ae(`/api/v1/notes/${t}${i}`,{method:"DELETE"})}function Ua(){return ae("/api/v1/wiki/settings")}function Gu(t){return ae("/api/v1/wiki/spaces",{method:"POST",body:JSON.stringify(t)})}function Hu(t={}){const s=new URLSearchParams;t.spaceId&&s.set("spaceId",t.spaceId),t.kind&&s.set("kind",t.kind),t.limit&&s.set("limit",String(t.limit));const i=s.size>0?`?${s.toString()}`:"";return ae(`/api/v1/wiki/pages${i}`)}function Xu(t){return ae(`/api/v1/wiki/pages/${t}`)}function Ju(t={}){var i;const s=new URLSearchParams;return(i=t.spaceId)!=null&&i.trim()&&s.set("spaceId",t.spaceId.trim()),ae(`/api/v1/wiki/home${s.size>0?`?${s.toString()}`:""}`)}function Yu(t){var i;const s=new URLSearchParams;return(i=t.spaceId)!=null&&i.trim()&&s.set("spaceId",t.spaceId.trim()),ae(`/api/v1/wiki/by-slug/${encodeURIComponent(t.slug)}${s.size>0?`?${s.toString()}`:""}`)}function Vu(t={}){var i;const s=new URLSearchParams;return(i=t.spaceId)!=null&&i.trim()&&s.set("spaceId",t.spaceId.trim()),t.kind&&s.set("kind",t.kind),ae(`/api/v1/wiki/tree${s.size>0?`?${s.toString()}`:""}`)}function Zu(t){return ae("/api/v1/wiki/pages",{method:"POST",body:JSON.stringify({kind:t.kind??"wiki",title:t.title,slug:t.slug??"",parentSlug:t.parentSlug??null,indexOrder:t.indexOrder??0,showInIndex:t.showInIndex??!0,aliases:t.aliases??[],summary:t.summary??"",contentMarkdown:t.contentMarkdown,author:t.author??null,tags:t.tags??[],spaceId:t.spaceId??"",frontmatter:t.frontmatter??{},links:t.links??[]})})}function ep(t,s){return ae(`/api/v1/wiki/pages/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function tp(t){return ae("/api/v1/wiki/search",{method:"POST",body:JSON.stringify(t)})}function sp(t={}){return ae("/api/v1/wiki/sync",{method:"POST",body:JSON.stringify(t)})}function ip(t={}){return ae("/api/v1/wiki/reindex",{method:"POST",body:JSON.stringify(t)})}function ap(t){return ae("/api/v1/wiki/settings/llm-profiles",{method:"POST",body:JSON.stringify(t)})}function np(t){return ae("/api/v1/wiki/settings/llm-profiles/test",{method:"POST",body:JSON.stringify(t)})}function rp(t){return ae("/api/v1/wiki/settings/embedding-profiles",{method:"POST",body:JSON.stringify(t)})}function lp(t,s){return ae(`/api/v1/wiki/settings/${t}-profiles/${s}`,{method:"DELETE"})}function ul(t){return ae("/api/v1/wiki/ingest-jobs",{method:"POST",body:JSON.stringify(t)})}function op(t){var i,n,a;const s=new FormData;return(i=t.spaceId)!=null&&i.trim()&&s.set("spaceId",t.spaceId.trim()),(n=t.titleHint)!=null&&n.trim()&&s.set("titleHint",t.titleHint.trim()),(a=t.llmProfileId)!=null&&a.trim()&&s.set("llmProfileId",t.llmProfileId.trim()),s.set("parseStrategy",t.parseStrategy??"auto"),s.set("entityProposalMode",t.entityProposalMode??"suggest"),s.set("createAsKind",t.createAsKind??"wiki"),s.set("linkedEntityHints",JSON.stringify(t.linkedEntityHints??[])),t.files.forEach(r=>{s.append("files",r)}),ae("/api/v1/wiki/ingest-jobs/uploads",{method:"POST",body:s})}function Td(t={}){var i;const s=new URLSearchParams;return(i=t.spaceId)!=null&&i.trim()&&s.set("spaceId",t.spaceId.trim()),typeof t.limit=="number"&&s.set("limit",String(t.limit)),ae(`/api/v1/wiki/ingest-jobs${s.size>0?`?${s.toString()}`:""}`)}function dp(t){return ae(`/api/v1/wiki/ingest-jobs/${t}`)}function cp(t){return ae("/api/v1/wiki/search",{method:"POST",body:JSON.stringify({spaceId:t.spaceId,kind:t.kind,mode:t.mode??"text",query:t.query??"",profileId:t.profileId,limit:t.limit??8})})}function Pd(t){return ae(`/api/v1/wiki/ingest-jobs/${t}`,{method:"DELETE"})}function mp(t){return ae(`/api/v1/wiki/ingest-jobs/${t}/rerun`,{method:"POST"})}function hp(t){return ae(`/api/v1/wiki/ingest-jobs/${t}/resume`,{method:"POST"})}function up(t){return ae(`/api/v1/wiki/ingest-jobs/${t.jobId}/review`,{method:"POST",body:JSON.stringify({decisions:t.decisions})})}function Md(t){return ae("/api/v1/insights",{method:"POST",body:JSON.stringify({...t,originAgentId:t.originAgentId||null,originLabel:t.originLabel||null,entityType:t.entityType||null,entityId:t.entityId||null,timeframeLabel:t.timeframeLabel||null,visibility:"visible",status:"open",evidence:[]})})}function pp(t){return ae(`/api/v1/insights/${t}`,{method:"DELETE"})}function pl(t,s,i=""){return ae(`/api/v1/insights/${t}/feedback`,{method:"POST",body:JSON.stringify({feedbackType:s,note:i})})}function xp(){return ae("/api/v1/reviews/weekly")}function gp(){return ae("/api/v1/reviews/weekly/finalize",{method:"POST"})}function Qa(t={}){const s=new URLSearchParams;t.from&&s.set("from",t.from),t.to&&s.set("to",t.to),Ct(s,Ft(t.userIds));const i=s.size>0?`?${s.toString()}`:"";return ae(`/api/v1/calendar/overview${i}`).then(n=>({...n,calendar:gu(n.calendar)}))}function bp(){return ae("/api/v1/calendar/connections")}function dn(t){return ae("/api/v1/calendar/discovery",{method:"POST",body:JSON.stringify(t)})}function fp(t){return ae("/api/v1/calendar/oauth/microsoft/start",{method:"POST",body:JSON.stringify(t)})}function wp(t){return ae("/api/v1/calendar/oauth/microsoft/test-config",{method:"POST",body:JSON.stringify(t)})}function vp(t){return ae(`/api/v1/calendar/oauth/microsoft/session/${t}`)}function yp(t){return ae(`/api/v1/calendar/connections/${t}/discovery`)}function jp(t){return ae("/api/v1/calendar/connections",{method:"POST",body:JSON.stringify(t)})}function Np(t){return ae(`/api/v1/calendar/connections/${t}/sync`,{method:"POST"})}function kp(t,s){return ae(`/api/v1/calendar/connections/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Sp(t){return ae(`/api/v1/calendar/connections/${t}`,{method:"DELETE"})}function Cp(){return ae("/api/v1/calendar/calendars")}function Ip(t){return ae("/api/v1/calendar/work-block-templates",{method:"POST",body:JSON.stringify(t)})}function Tp(t,s){return ae(`/api/v1/calendar/work-block-templates/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Pp(t){return ae(`/api/v1/calendar/work-block-templates/${t}`,{method:"DELETE"})}function Mp(t){return ae("/api/v1/calendar/events",{method:"POST",body:JSON.stringify(t)}).then(s=>({...s,event:lr(s.event)}))}function Ep(t,s){return ae(`/api/v1/calendar/events/${t}`,{method:"PATCH",body:JSON.stringify(s)}).then(i=>({...i,event:lr(i.event)}))}function Ap(t){return ae(`/api/v1/calendar/events/${t}`,{method:"DELETE"})}function Lp(t){return ae("/api/v1/calendar/timeboxes",{method:"POST",body:JSON.stringify(t)})}function Dp(t,s){return ae(`/api/v1/calendar/timeboxes/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function $p(t){return ae("/api/v1/calendar/timeboxes/recommend",{method:"POST",body:JSON.stringify(t)})}function Op(t={}){const s=new URLSearchParams;Ct(s,t.userIds),t.status&&s.set("status",t.status),t.polarity&&s.set("polarity",t.polarity),t.dueToday&&s.set("dueToday","true"),t.limit&&s.set("limit",String(t.limit));const i=s.size>0?`?${s.toString()}`:"";return ae(`/api/v1/habits${i}`)}function Fp(t){return ae("/api/v1/habits",{method:"POST",body:JSON.stringify({...t,linkedBehaviorId:t.linkedBehaviorId||null})})}function _p(t,s){return ae(`/api/v1/habits/${t}`,{method:"PATCH",body:JSON.stringify({...s,linkedBehaviorId:s.linkedBehaviorId===""?null:s.linkedBehaviorId})})}function Rp(t){return ae(`/api/v1/habits/${t}`,{method:"DELETE"})}function zp(t,s){return ae(`/api/v1/habits/${t}/check-ins`,{method:"POST",body:JSON.stringify(s)})}function qp(t,s){return ae(`/api/v1/habits/${t}/check-ins/${encodeURIComponent(s)}`,{method:"DELETE"})}function Bp(t){return ae(`/api/v1/projects/${t}/board`)}function Kp(){return ae("/api/v1/operator/context")}function Wa(){return ae("/api/v1/settings")}function Up(t){const s=new URLSearchParams;Ct(s,Ft(t));const i=s.size>0?`?${s.toString()}`:"";return ae(`/api/v1/health/overview${i}`)}function Qp(t){const s=new URLSearchParams;Ct(s,Ft(t));const i=s.size>0?`?${s.toString()}`:"";return ae(`/api/v1/health/sleep${i}`)}function Wp(t){const s=new URLSearchParams;Ct(s,Ft(t));const i=s.size>0?`?${s.toString()}`:"";return ae(`/api/v1/health/fitness${i}`)}function Gp(t){return ae("/api/v1/health/pairing-sessions",{method:"POST",body:JSON.stringify(t??{})})}function Hp(t){return ae(`/api/v1/health/pairing-sessions/${t}`,{method:"DELETE"})}function Xp(t){return ae("/api/v1/health/pairing-sessions/revoke-all",{method:"POST",body:JSON.stringify(t??{})})}function Jp(t,s){return ae(`/api/v1/health/workouts/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Yp(t,s){return ae(`/api/v1/health/sleep/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Vp(){return ae("/api/v1/users/directory")}function Zp(t,s){return ae(`/api/v1/users/access-grants/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function ex(t){return ae("/api/v1/users",{method:"POST",body:JSON.stringify(t)})}function tx(t,s){return ae(`/api/v1/users/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function sx(t){return ae("/api/v1/strategies",{method:"POST",body:JSON.stringify(t)})}function ix(t){return ae(`/api/v1/strategies/${t}`)}function Fn(t,s){return ae(`/api/v1/strategies/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Ed(t){return ae(`/api/v1/strategies/${t}`,{method:"DELETE"})}function ax(){return ae("/api/v1/settings/bin")}function nx(){return ae("/api/v1/agents/onboarding")}function rx(){return ae("/api/v1/approval-requests")}function lx(t,s=""){return ae(`/api/v1/approval-requests/${t}/approve`,{method:"POST",body:JSON.stringify({note:s})})}function ox(t,s=""){return ae(`/api/v1/approval-requests/${t}/reject`,{method:"POST",body:JSON.stringify({note:s})})}function dx(){return ae("/api/v1/rewards/rules")}function cx(t,s){return ae(`/api/v1/rewards/rules/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function mx(t){return ae("/api/v1/rewards/bonus",{method:"POST",body:JSON.stringify(t)})}function hx(t=50){return ae(`/api/v1/rewards/ledger?limit=${t}`)}function Ad(){return ae("/api/v1/metrics/xp")}function Ld(t){return ae("/api/v1/settings",{method:"PATCH",body:JSON.stringify(t)})}function xl(t){return ae("/api/v1/entities/delete",{method:"POST",body:JSON.stringify(t)})}function gl(t){return ae("/api/v1/entities/restore",{method:"POST",body:JSON.stringify(t)})}function ux(t){return ae("/api/v1/entities/search",{method:"POST",body:JSON.stringify(t)})}function px(t){return ae("/api/v1/settings/tokens",{method:"POST",body:JSON.stringify(t)})}function xx(t){return ae(`/api/v1/settings/tokens/${t}/rotate`,{method:"POST"})}function gx(t){return ae(`/api/v1/settings/tokens/${t}/revoke`,{method:"POST"})}function bx(t={}){const s=new URLSearchParams;return s.set("limit",String(t.limit??100)),t.entityType&&s.set("entityType",t.entityType),t.entityId&&s.set("entityId",t.entityId),t.includeCorrected&&s.set("includeCorrected","true"),Ct(s,Ft(t.userIds)),ae(`/api/v1/activity?${s.toString()}`)}function fx(t={}){const s=new URLSearchParams;return s.set("limit",String(t.limit??200)),t.level&&s.set("level",t.level),t.source&&s.set("source",t.source),t.scope&&s.set("scope",t.scope),t.route&&s.set("route",t.route),t.entityType&&s.set("entityType",t.entityType),t.entityId&&s.set("entityId",t.entityId),t.jobId&&s.set("jobId",t.jobId),t.search&&s.set("search",t.search),t.beforeCreatedAt&&s.set("beforeCreatedAt",t.beforeCreatedAt),t.beforeId&&s.set("beforeId",t.beforeId),ae(`/api/v1/diagnostics/logs?${s.toString()}`)}function Dd(t){return ae("/api/v1/goals",{method:"POST",body:JSON.stringify({...t,notes:or(t.notes)})})}function $d(t){return ae("/api/v1/projects",{method:"POST",body:JSON.stringify({...t,notes:or(t.notes)})})}function Od(t,s){return ae(`/api/v1/projects/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function wx(t,s="soft"){return ae(`/api/v1/projects/${t}${s==="hard"?"?mode=hard":""}`,{method:"DELETE"})}function vx(t,s){return ae(`/api/v1/goals/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function yx(t){return ae(`/api/v1/goals/${t}`,{method:"DELETE"})}function Ea(t){const s={...t,goalId:t.goalId||null,projectId:t.projectId||null,dueDate:t.dueDate||null,notes:or(t.notes)};return ae("/api/v1/tasks",{method:"POST",body:JSON.stringify(s)})}function Yi(t,s){return ae(`/api/v1/tasks/${t}`,{method:"PATCH",body:JSON.stringify({...s,goalId:s.goalId===""?null:s.goalId,projectId:s.projectId===""?null:s.projectId,dueDate:s.dueDate===""?null:s.dueDate})})}function hr(t){return ae(`/api/v1/tasks/${t}`,{method:"DELETE"})}function ur(t){return ae(`/api/v1/tasks/${t}/uncomplete`,{method:"POST",body:JSON.stringify({})})}function jx(t){return ae(`/api/v1/tasks/${t}/context`)}function Nx(t){return ae("/api/v1/operator/log-work",{method:"POST",body:JSON.stringify(t)})}function Fd(t){return ae("/api/v1/work-adjustments",{method:"POST",body:JSON.stringify(t)})}function _d(t,s="Removed from the visible archive."){return ae(`/api/v1/activity/${t}/remove`,{method:"POST",body:JSON.stringify({reason:s})})}function kx(t){return ae("/api/v1/session-events",{method:"POST",body:JSON.stringify(t)})}function Sx(t,s){return ae(`/api/v1/tasks/${t}/runs`,{method:"POST",body:JSON.stringify(s)})}function Cx(t,s){return ae(`/api/v1/task-runs/${t}/heartbeat`,{method:"POST",body:JSON.stringify(s)})}function Ix(t,s={}){return ae(`/api/v1/task-runs/${t}/focus`,{method:"POST",body:JSON.stringify(s)})}function Rd(t,s){return ae(`/api/v1/task-runs/${t}/complete`,{method:"POST",body:JSON.stringify(s)})}function zd(t,s){return ae(`/api/v1/task-runs/${t}/release`,{method:"POST",body:JSON.stringify(s)})}const qd=c.createContext(null),pt=[{to:"/overview",labelKey:"common.routeLabels.overview",detailKey:"common.routeDetails.overview",icon:Ro},{to:"/goals",labelKey:"common.routeLabels.goals",detailKey:"common.routeDetails.goals",icon:Oa},{to:"/habits",labelKey:"common.routeLabels.habits",detailKey:"common.routeDetails.habits",icon:Un},{to:"/projects",labelKey:"common.routeLabels.projects",detailKey:"common.routeDetails.projects",icon:zo},{to:"/strategies",labelKey:"common.routeLabels.strategies",detailKey:"common.routeDetails.strategies",icon:Qn},{to:"/preferences",labelKey:"common.routeLabels.preferences",detailKey:"common.routeDetails.preferences",icon:Fa},{to:"/calendar",labelKey:"common.routeLabels.calendar",detailKey:"common.routeDetails.calendar",icon:us},{to:"/sleep",labelKey:"common.routeLabels.sleep",detailKey:"common.routeDetails.sleep",icon:Ko},{to:"/sports",labelKey:"common.routeLabels.sports",detailKey:"common.routeDetails.sports",icon:Uo},{to:"/kanban",labelKey:"common.routeLabels.kanban",detailKey:"common.routeDetails.kanban",icon:Gi},{to:"/today",labelKey:"common.routeLabels.today",detailKey:"common.routeDetails.today",icon:yi},{to:"/notes",labelKey:"common.routeLabels.notes",detailKey:"common.routeDetails.notes",icon:Wn},{to:"/wiki",labelKey:"common.routeLabels.wiki",detailKey:"common.routeDetails.wiki",icon:Gn},{to:"/psyche",labelKey:"common.routeLabels.psyche",detailKey:"common.routeDetails.psyche",icon:Hn},{to:"/activity",labelKey:"common.routeLabels.activity",detailKey:"common.routeDetails.activity",icon:Ni},{to:"/insights",labelKey:"common.routeLabels.insights",detailKey:"common.routeDetails.insights",icon:dm},{to:"/review/weekly",labelKey:"common.routeLabels.review",detailKey:"common.routeDetails.review",icon:cm},{to:"/settings",labelKey:"common.routeLabels.settings",detailKey:"common.routeDetails.settings",icon:Xn}],Tx=pt.filter(t=>t.to!=="/preferences"&&t.to!=="/sleep"),Px=[pt[0],pt[10],pt[9],pt[13]],Mx=[pt[1],pt[2],pt[3],pt[4],pt[6],pt[8],pt[11],pt[12],pt[14],pt[15],pt[16],pt[17]],Bd="forge.selected-user-ids";function Ex(t,s,i){return Math.min(Math.max(t,s),i)}function Jt(t,s,i){return s+(i-s)*t}function Ax(){var t,s,i;return typeof window>"u"?0:Math.max(window.scrollY||0,((t=document.scrollingElement)==null?void 0:t.scrollTop)||0,((s=document.documentElement)==null?void 0:s.scrollTop)||0,((i=document.body)==null?void 0:i.scrollTop)||0)}function Kd(t){return new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:t>=1e3?1:0}).format(t)}function Lx(t){return t==="/wiki"||t.startsWith("/wiki/page/")?"/wiki":t==="/wiki/new"||t.startsWith("/wiki/edit/")?"/wiki/editor":t}function Dx(t){return t==="/wiki"||t.startsWith("/wiki/page/")||t==="/wiki/new"||t.startsWith("/wiki/edit/")}function Na(t){return t.startsWith("/psyche")||t==="/preferences"||t.startsWith("/preferences/")||t==="/sleep"||t.startsWith("/sleep/")}function $x(t){const s=new URLSearchParams;return t.job.spaceId&&s.set("spaceId",t.job.spaceId),s.set("ingest","1"),s.set("ingestJobId",t.job.id),{pathname:"/wiki",search:`?${s.toString()}`}}function Ox(t){return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(t))}function Fx(){if(typeof window>"u")return[];try{const t=window.localStorage.getItem(Bd);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean):[]}catch{return[]}}function _x(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Bd,JSON.stringify(Array.from(new Set(t))))}catch{return}}function Ud(t,s){if(t.length!==s.length)return!1;const i=[...t].sort().join("|"),n=[...s].sort().join("|");return i===n}function Rx(t){const s=t.split(/\s+/).map(i=>i.trim()).filter(Boolean);return s.length===0?"??":s.length===1?s[0].slice(0,2).toUpperCase():`${s[0][0]??""}${s[1][0]??""}`.toUpperCase()}function Qd(t){const s=t.filter(n=>n.kind==="human"),i=t.filter(n=>n.kind==="bot");return[{id:"all",label:"All",shortLabel:"All",description:"Show every human and bot together.",userIds:[],token:"ALL",icon:Yn},{id:"humans",label:"Humans",shortLabel:"Humans",description:"Focus only on human-owned work.",userIds:s.map(n=>n.id),token:"HU",icon:Mn},{id:"bots",label:"Bots",shortLabel:"Bots",description:"Focus only on bot-owned work.",userIds:i.map(n=>n.id),token:"AI",icon:ka},...t.map(n=>({id:n.id,label:n.displayName,shortLabel:n.displayName,description:`${n.kind==="human"?"Human":"Bot"} · ${n.handle}`,userIds:[n.id],token:Rx(n.displayName),icon:n.kind==="human"?Mn:ka}))]}function zx(t,s){return Qd(t).find(i=>Ud(s,i.userIds))??{id:"custom",label:s.length>1?`${s.length} selected`:"Custom",shortLabel:s.length>1?`${s.length} selected`:"Custom",description:"Using a custom combination of users.",userIds:s,token:s.length>1?String(s.length):"C",icon:Yn}}function bl({users:t,selectedUserIds:s,onChange:i,compact:n=!1}){const[a,r]=c.useState(!1),l=c.useMemo(()=>Qd(t),[t]),d=c.useMemo(()=>zx(t,s),[s,t]);return e.jsxs(Lt,{open:a,onOpenChange:r,children:[e.jsx(wh,{asChild:!0,children:e.jsxs("button",{type:"button",className:re("shell-scope-trigger inline-flex items-center gap-2",n?"px-2.5 text-[12px]":"px-3.5 text-[13px]"),children:[e.jsx("span",{className:"shell-scope-avatar",children:d.token}),e.jsx("span",{className:re("truncate text-left",n?"max-w-[7.5rem]":"max-w-[11rem]"),children:d.shortLabel})]})}),e.jsxs(Dt,{children:[e.jsx($t,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.72)] backdrop-blur-sm"}),e.jsxs(Ot,{className:"fixed left-1/2 top-[12vh] z-50 w-[min(40rem,calc(100vw-1.5rem))] -translate-x-1/2 rounded-[30px] border border-white/10 bg-[rgba(10,15,28,0.97)] p-4 shadow-[0_32px_90px_rgba(0,0,0,0.45)] sm:p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(Rt,{className:"font-display text-[1.25rem] tracking-[-0.04em] text-white",children:"Choose user scope"}),e.jsx(Gt,{className:"mt-1 text-[13px] leading-6 text-white/56",children:"Change which humans and bots shape the current Forge view."})]}),e.jsx(_t,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-[12px] font-medium text-white/70 transition hover:bg-white/[0.08] hover:text-white",children:"Close"})})]}),e.jsx("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:l.map(o=>{const x=Ud(s,o.userIds),f=o.icon;return e.jsxs("button",{type:"button",className:re("flex items-center justify-between gap-3 rounded-[24px] border px-4 py-4 text-left transition",x?"border-[rgba(192,193,255,0.24)] bg-[rgba(192,193,255,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/78 hover:bg-white/[0.06] hover:text-white"),onClick:()=>{i(o.userIds),r(!1)},children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"shell-scope-avatar",children:e.jsx(f,{className:"size-3.5"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate text-[14px] font-semibold",children:o.label}),e.jsx("span",{className:"mt-1 block text-[12px] leading-5 text-white/52",children:o.description})]})]}),x?e.jsx(ji,{className:"size-4 shrink-0 text-[var(--primary)]"}):null]},o.id)})})]})]})]})}function qx({to:t,labelKey:s,icon:i,compact:n=!1}){const{t:a}=at(),r=ki(),l=a(s),d=t==="/psyche"&&Na(r.pathname);return e.jsxs(Ks,{to:t,title:n?l:void 0,"aria-label":l,className:({isActive:o})=>`interactive-tap flex items-center rounded-[18px] text-sm transition ${o||d?"bg-white/[0.08] text-white shadow-[inset_0_0_0_1px_rgba(192,193,255,0.2)]":"text-white/60 hover:bg-white/[0.04] hover:text-white"} ${n?"justify-center px-3 py-3.5":"gap-3 px-4 py-3"}`,children:[e.jsx(i,{className:"size-4 shrink-0"}),n?null:e.jsx("span",{children:l})]})}function Bx(){const[t,s]=c.useState(!1),{t:i}=at();return e.jsxs(e.Fragment,{children:[e.jsx("nav",{"data-testid":"mobile-bottom-nav",className:"fixed inset-x-0 bottom-0 z-40 border-t border-white/6 bg-[rgba(9,14,28,0.94)] backdrop-blur-xl lg:hidden",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:"0.75rem",paddingBottom:"calc(var(--forge-safe-area-bottom) + 0.75rem)"},children:e.jsxs("div",{className:"grid grid-cols-5 gap-2",children:[Px.map(n=>e.jsxs(Ks,{to:n.to,className:({isActive:a})=>`flex min-h-11 flex-col items-center justify-center gap-1 rounded-2xl px-2 py-2 text-[12px] ${a?"bg-white/[0.08] text-[var(--primary)]":"text-white/55"}`,children:[e.jsx(n.icon,{className:"size-4"}),e.jsx("span",{children:i(n.labelKey)})]},n.to)),e.jsxs("button",{type:"button",className:"flex min-h-11 flex-col items-center justify-center gap-1 rounded-2xl px-2 py-2 text-[12px] text-white/55",onClick:()=>s(!0),children:[e.jsx(Xn,{className:"size-4"}),e.jsx("span",{children:i("common.shell.more")})]})]})}),e.jsx(Ra,{open:t,onOpenChange:s,eyebrow:i("common.shell.moreRoutesEyebrow"),title:i("common.shell.moreRoutesTitle"),description:i("common.shell.moreRoutesDescription"),children:e.jsx("div",{className:"grid gap-3",children:Mx.map(n=>e.jsxs(Ks,{to:n.to,onClick:()=>s(!1),className:({isActive:a})=>`interactive-tap flex items-center justify-between rounded-[24px] px-4 py-4 ${a?"bg-white/[0.08] text-white":"bg-white/[0.04] text-white/70"}`,children:[e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(n.icon,{className:"size-4 text-[var(--primary)]"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-base font-medium",children:i(n.labelKey)}),e.jsx("span",{className:"mt-1 block text-sm text-white/54",children:i(n.detailKey)})]})]}),e.jsx(Ni,{className:"size-4 text-white/35"})]},n.to))})})]})}function Kx({onClick:t}){const{t:s}=at();return e.jsxs(W,{variant:"secondary",size:"sm",className:"min-w-[8.25rem] px-3.5",onClick:t,children:[e.jsx(dt,{className:"size-4"}),s("common.shell.command"),e.jsx(O,{size:"sm",tone:"meta",className:"ml-1 hidden bg-white/[0.06] text-white/52 xl:inline-flex",children:"⌘K"})]})}function Ux({children:t,settings:s,timerPending:i,startWorkOpen:n,startWorkPending:a,startWorkError:r,startWorkDefaults:l,onOpenStartWork:d,onCloseStartWork:o,onStartExistingTask:x,onCreateAndStartTask:f,onFocusRun:b,onPauseRun:m,onCompleteRun:h}){var Pe,Ge;const p=ki(),w=Ye(),{t:v}=at(),I=pt.find(Z=>p.pathname.startsWith(Z.to))??pt[0],k=Lx(p.pathname),[S,M]=c.useState(!1),[P,y]=c.useState(!1),[N,A]=c.useState(0),[T,F]=c.useState(!1),u=c.useRef(!1),j=c.useRef(!1),L=c.useRef(!1),q=Na(p.pathname),G=Dx(p.pathname),Q=Na(p.pathname),ne=G||Q,H=um(),_=pm(),U=vh(),R=N>=.96,C=H+_,J=pe({queryKey:["forge-background-wiki-ingest-jobs"],queryFn:()=>Td({limit:12}),refetchInterval:Z=>{var Ue;const He=((Ue=Z.state.data)==null?void 0:Ue.jobs)??[];return P||He.some(Qe=>["queued","processing"].includes(Qe.job.status))?2e3:!1}}),ee=[{id:"streak",label:v("common.shell.momentum.streak"),compactValue:String(w.snapshot.metrics.streakDays),expandedValue:v(w.snapshot.metrics.streakDays===1?"common.shell.momentum.streakBadgeOne":"common.shell.momentum.streakBadgeOther",{count:w.snapshot.metrics.streakDays}),icon:xm},{id:"xp",label:v("common.shell.momentum.xp"),compactValue:String(w.snapshot.metrics.totalXp),expandedValue:`${w.snapshot.metrics.totalXp} XP`,icon:Gi},{id:"momentum",label:v("common.shell.momentum.momentum"),compactValue:`${w.snapshot.metrics.momentumScore}%`,expandedValue:v("common.shell.momentum.liveMomentum",{count:w.snapshot.metrics.momentumScore}),icon:gm}],le=(((Pe=J.data)==null?void 0:Pe.jobs)??[]).some(Z=>["queued","processing"].includes(Z.job.status))?(()=>{var He,Ue,Qe;const Z=(((He=J.data)==null?void 0:He.jobs)??[]).filter(ct=>["queued","processing"].includes(ct.job.status));return Z.length===1?((Ue=Z[0])==null?void 0:Ue.job.latestMessage)||((Qe=Z[0])==null?void 0:Qe.job.titleHint)||"1 ingest running":`${Z.length} ingest jobs running`})():_>0?v(_===1?"common.shell.savingOne":"common.shell.savingOther",{count:_}):H>0?v(H===1?"common.shell.refreshingOne":"common.shell.refreshingOther",{count:H}):v("common.shell.settled"),oe=((Ge=J.data)==null?void 0:Ge.jobs)??[],ue=oe.some(Z=>["queued","processing"].includes(Z.job.status)),me=c.useMemo(()=>p.pathname.startsWith("/tasks/")?[{to:"/kanban",label:v("common.shell.rail.taskBackToKanban")},{to:"/today",label:v("common.shell.rail.taskOpenToday")}]:p.pathname.startsWith("/projects/")?[{to:"/projects",label:v("common.shell.rail.projectAll")},{to:"/goals",label:v("common.shell.rail.projectGoals")}]:p.pathname.startsWith("/goals/")?[{to:"/goals",label:v("common.shell.rail.goalAll")},{to:"/projects",label:v("common.shell.rail.goalProjects")}]:p.pathname.startsWith("/strategies")?[{to:"/strategies",label:v("common.routeLabels.strategies")},{to:"/projects",label:v("common.shell.rail.projectAll")}]:Na(p.pathname)?[{to:"/psyche",label:v("common.shell.rail.psycheHub")},{to:"/psyche/reports",label:v("common.shell.rail.psycheReports")}]:[{to:"/overview",label:v("common.shell.rail.overview")},{to:"/today",label:v("common.shell.rail.today")}],[p.pathname,v]);c.useEffect(()=>{const Z=He=>{(He.metaKey||He.ctrlKey)&&He.key.toLowerCase()==="k"&&(He.preventDefault(),M(Ue=>!Ue))};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[]),c.useEffect(()=>{try{window.localStorage.getItem("forge.desktop-nav-collapsed")==="true"&&F(!0)}catch{return}},[]),c.useEffect(()=>{if(L.current){L.current=!1;return}try{window.localStorage.setItem("forge.desktop-nav-collapsed",String(T))}catch{return}},[T]),c.useEffect(()=>{if(ne){u.current||(j.current=T,u.current=!0,T||(L.current=!0,F(!0)));return}u.current&&(u.current=!1,T!==j.current&&(L.current=!0,F(j.current)))},[ne,T]),c.useEffect(()=>{const Z=()=>{const He=window.innerWidth>=1024?72:56,Ue=Ex(Ax()/He,0,1);A(Qe=>Math.abs(Qe-Ue)<.01?Qe:Ue)};return Z(),window.addEventListener("scroll",Z,{passive:!0}),window.addEventListener("resize",Z),()=>{window.removeEventListener("scroll",Z),window.removeEventListener("resize",Z)}},[]);const $=Jt(N,10,6),ce=Jt(N,9,6),E=Jt(N,1.12,1),z=1-N,K=Jt(N,160,0),je=Jt(N,12,0),V=Jt(N,0,-10),D=Jt(N,9,6),X=Jt(N,8,6),he=Jt(N,1,.95),ye=1-N,ze=Jt(N,240,0),fe=Jt(N,0,-8);return e.jsxs("div",{className:`min-h-screen ${w.snapshot.meta.mode==="transitional-node"?"theme-forge-obsidian":""}`,children:[e.jsx(Bh,{open:S,onOpenChange:M,snapshot:w.snapshot}),e.jsxs("div",{className:"hidden lg:grid lg:min-h-screen",style:{gridTemplateColumns:T?"5.75rem minmax(0,1fr)":"17.75rem minmax(0,1fr)"},children:[e.jsxs("aside",{className:re("flex min-h-screen flex-col border-r border-white/5 bg-[rgba(8,13,28,0.78)] py-6 backdrop-blur-xl transition-[padding,width]",T?"px-3":"px-5"),children:[e.jsxs("div",{className:re("flex items-start",T?"flex-col items-center gap-3":"justify-between gap-3"),children:[e.jsxs(Le,{to:"/overview",className:re("block min-w-0",T&&"text-center"),children:[e.jsx("div",{className:re("font-display text-[var(--primary)]",T?"text-2xl":"text-3xl"),children:v("common.shell.appMark")}),T?null:e.jsxs("div",{className:"type-meta mt-2 text-white/40",children:["Level ",w.snapshot.metrics.level]})]}),e.jsx(W,{type:"button",variant:"secondary",size:"sm",className:"mt-0.5 px-2.5",onClick:()=>F(Z=>!Z),"aria-label":v(T?"common.shell.expandSidebar":"common.shell.collapseSidebar"),title:v(T?"common.shell.expandSidebar":"common.shell.collapseSidebar"),children:T?e.jsx(bm,{className:"size-4"}):e.jsx(fm,{className:"size-4"})})]}),e.jsx("div",{className:re("grid gap-2",T?"mt-6":"mt-8"),children:Tx.map(Z=>e.jsx(qx,{to:Z.to,labelKey:Z.labelKey,icon:Z.icon,compact:T},Z.to))}),e.jsx("div",{className:re(T?"mt-4":"mt-6"),children:e.jsxs("div",{className:re("rounded-[24px] bg-white/[0.04]",T?"px-2 py-2.5":"p-4"),children:[T?null:e.jsx("div",{className:"type-label text-white/40",children:v("common.shell.momentum.title")}),e.jsx("div",{className:re("grid",T?"gap-1.5":"mt-3 gap-3"),children:ee.map(Z=>{const He=Z.icon;return T?e.jsxs("div",{title:`${Z.label}: ${Z.compactValue}`,className:"flex min-w-0 flex-col items-center gap-1 rounded-[16px] bg-white/[0.04] px-1 py-2.5 text-center",children:[e.jsx(He,{className:"size-3.5 shrink-0 text-white/42"}),e.jsx("div",{className:"max-w-full text-[12px] font-semibold leading-none text-white",children:Z.compactValue})]},Z.id):e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-white/42",children:Z.label}),e.jsx("div",{className:"mt-1 text-lg font-semibold leading-tight text-white",children:Z.expandedValue})]},Z.id)})})]})})]}),e.jsxs("div",{className:"min-h-screen",children:[e.jsx(ol,{children:e.jsxs(wt.header,{className:"sticky top-0 z-30 border-b border-white/5 bg-[rgba(10,16,30,0.82)] px-6 backdrop-blur-xl",animate:void 0,style:{paddingTop:`${$}px`,paddingBottom:`${ce}px`},transition:{duration:.35,ease:"easeOut"},children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-5",children:[e.jsx(wt.div,{className:"shrink-0 font-display text-white",animate:void 0,style:{fontSize:`${E}rem`,lineHeight:1},transition:{duration:.35,ease:"easeOut"},children:v(I.labelKey)}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(dl,{runs:w.snapshot.activeTaskRuns,tasks:w.snapshot.tasks,generatedAt:w.snapshot.meta.generatedAt,timeAccountingMode:s.execution.timeAccountingMode,pending:i,onOpenStartWork:()=>d(),onPause:m,onFocus:b})})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-2",children:[e.jsx(tl,{active:C>0||ue,label:le,onClick:()=>y(!0)}),e.jsx(Kx,{onClick:()=>M(!0)}),e.jsxs(W,{variant:"secondary",size:"sm",className:"min-w-[7.25rem] px-3.5",onClick:()=>void w.refresh(),children:[e.jsx(ps,{className:"size-4"}),v("common.actions.refresh")]})]})]}),e.jsx(cl,{runs:w.snapshot.activeTaskRuns,tasks:w.snapshot.tasks,generatedAt:w.snapshot.meta.generatedAt,timeAccountingMode:s.execution.timeAccountingMode,pending:i,onOpenStartWork:()=>d(),onFocus:b,onPause:m,onComplete:h}),e.jsxs(wt.div,{className:"flex items-center justify-between gap-4 overflow-hidden border-t border-white/6",animate:void 0,style:{opacity:z,maxHeight:`${K}px`,marginTop:`${je}px`,paddingTop:`${je}px`,transform:`translateY(${V}px)`,pointerEvents:N>=.96?"none":"auto"},transition:{duration:.28,ease:"easeOut"},children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[me.map(Z=>e.jsx(Le,{to:Z.to,className:"interactive-tap inline-flex min-h-10 min-w-max items-center justify-center rounded-full bg-white/[0.04] px-4 py-2 text-[13px] leading-none whitespace-nowrap text-white/62 transition hover:bg-white/[0.07] hover:text-white",children:Z.label},Z.to)),e.jsx(bl,{users:w.snapshot.users,selectedUserIds:w.selectedUserIds,onChange:w.setSelectedUserIds,compact:!0})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(O,{tone:"meta",children:v(w.snapshot.metrics.streakDays===1?"common.shell.momentum.streakBadgeOne":"common.shell.momentum.streakBadgeOther",{count:w.snapshot.metrics.streakDays})}),e.jsx(O,{tone:"meta",children:v("common.shell.momentum.weeklyXp",{count:w.snapshot.metrics.weeklyXp})}),e.jsx(O,{tone:q?"signal":"meta",children:q?v("common.shell.momentum.psycheMode"):v("common.shell.momentum.liveMomentum",{count:w.snapshot.metrics.momentumScore})})]})]})]})}),e.jsx("div",{className:"px-6 pt-3",children:e.jsx(ll,{open:n,onOpenChange:Z=>{Z||o()},presentation:"desktop_inline",tasks:w.snapshot.tasks,projects:w.snapshot.dashboard.projects,activeRunCount:w.snapshot.activeTaskRuns.length,maxActiveTasks:s.execution.maxActiveTasks,timeAccountingMode:s.execution.timeAccountingMode,pending:a,errorMessage:r,initialTaskId:l.taskId??null,defaultProjectId:l.projectId??null,onStartExisting:x,onCreateAndStart:f})}),e.jsx("main",{className:"px-6 py-3",children:e.jsx(sl,{routeKey:k,tone:q?"psyche":"core",children:t})})]})]}),e.jsxs("div",{className:"min-h-[100dvh] overflow-x-clip lg:hidden",children:[e.jsx(ol,{children:e.jsxs(wt.header,{className:"sticky top-0 z-30 border-b border-white/6 bg-[rgba(8,13,28,0.92)] px-4 backdrop-blur-xl",animate:void 0,style:{paddingTop:`${D}px`,paddingBottom:`${X}px`},transition:{duration:.35,ease:"easeOut"},children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[e.jsx("div",{className:re("shrink-0 font-display text-white transition",R?"text-[0.95rem]":"text-base"),style:{fontSize:`${he}rem`},children:v(I.labelKey)}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(dl,{runs:w.snapshot.activeTaskRuns,tasks:w.snapshot.tasks,generatedAt:w.snapshot.meta.generatedAt,timeAccountingMode:s.execution.timeAccountingMode,pending:i,onOpenStartWork:()=>d(),onPause:m,onFocus:b})})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsx(W,{variant:"secondary",size:"sm",className:"min-h-[2.125rem] px-2.5",onClick:()=>M(!0),children:e.jsx(dt,{className:"size-4"})}),e.jsxs("div",{className:"inline-flex min-h-[2.125rem] items-center gap-1.5 rounded-full border border-white/8 bg-white/[0.05] px-2.5 text-[12px] font-medium text-[var(--primary)]",children:[e.jsx(Gi,{className:"size-3.5 shrink-0"}),e.jsxs("span",{children:[Kd(w.snapshot.metrics.totalXp)," XP"]})]})]})]}),e.jsx(cl,{runs:w.snapshot.activeTaskRuns,tasks:w.snapshot.tasks,generatedAt:w.snapshot.meta.generatedAt,timeAccountingMode:s.execution.timeAccountingMode,pending:i,onOpenStartWork:()=>d(),onFocus:b,onPause:m,onComplete:h}),e.jsx(wt.div,{className:"overflow-hidden",animate:void 0,style:{opacity:ye,maxHeight:`${ze}px`,transform:`translateY(${fe}px)`,pointerEvents:N>=.96?"none":"auto"},transition:{duration:.28,ease:"easeOut"},children:e.jsx("div",{className:"mt-2 text-[13px] leading-5 text-white/52",children:v(I.detailKey)})}),R?null:e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-2",children:e.jsx(tl,{active:C>0||ue,label:le,onClick:()=>y(!0)})}),e.jsx("div",{className:"mt-3 overflow-x-auto pb-1",children:e.jsx(bl,{users:w.snapshot.users,selectedUserIds:w.selectedUserIds,onChange:w.setSelectedUserIds,compact:!0})})]})]})}),e.jsx(ll,{open:n,onOpenChange:Z=>{Z||o()},presentation:"mobile_sheet",tasks:w.snapshot.tasks,projects:w.snapshot.dashboard.projects,activeRunCount:w.snapshot.activeTaskRuns.length,maxActiveTasks:s.execution.maxActiveTasks,timeAccountingMode:s.execution.timeAccountingMode,pending:a,errorMessage:r,initialTaskId:l.taskId??null,defaultProjectId:l.projectId??null,onStartExisting:x,onCreateAndStart:f}),e.jsx("main",{className:"overflow-x-clip px-4 py-2.5 lg:pb-24",style:{paddingBottom:"calc(var(--forge-mobile-nav-clearance) + 2.5rem)",paddingLeft:"max(1rem, calc(var(--forge-safe-area-left) + 1rem))",paddingRight:"max(1rem, calc(var(--forge-safe-area-right) + 1rem))"},children:e.jsx(sl,{routeKey:k,tone:q?"psyche":"core",children:t})}),e.jsx(Bx,{})]}),e.jsx(Lt,{open:P,onOpenChange:y,children:e.jsxs(Dt,{children:[e.jsx($t,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.72)] backdrop-blur-sm"}),e.jsxs(Ot,{className:"fixed left-1/2 top-[10vh] z-50 w-[min(42rem,calc(100vw-1.5rem))] -translate-x-1/2 rounded-[30px] border border-white/10 bg-[rgba(10,15,28,0.97)] p-4 shadow-[0_32px_90px_rgba(0,0,0,0.45)] sm:p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(Rt,{className:"font-display text-[1.25rem] tracking-[-0.04em] text-white",children:"Background activity"}),e.jsx(Gt,{className:"mt-1 text-[13px] leading-6 text-white/56",children:"Follow active wiki ingest jobs and reopen completed reviews without leaving your current context."})]}),e.jsx(_t,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-[12px] font-medium text-white/70 transition hover:bg-white/[0.08] hover:text-white",children:"Close"})})]}),e.jsx("div",{className:"mt-4 max-h-[65vh] overflow-y-auto",children:J.isLoading?e.jsx(xt,{eyebrow:"Background",title:"Loading activity",description:"Checking the latest queued and completed ingest jobs."}):J.isError?e.jsx(Oe,{eyebrow:"Background",error:J.error,onRetry:()=>void J.refetch()}):oe.length===0?e.jsx("div",{className:"rounded-[24px] border border-dashed border-white/10 px-4 py-10 text-center text-[13px] leading-6 text-white/42",children:"No background ingest jobs yet."}):e.jsx("div",{className:"grid gap-3",children:oe.map(Z=>{const He=["queued","processing"].includes(Z.job.status);return e.jsx(Le,{to:$x(Z),onClick:()=>y(!1),className:"rounded-[24px] border border-white/8 bg-white/[0.03] px-4 py-4 transition hover:bg-white/[0.06]",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-[11px] uppercase tracking-[0.16em] text-white/42",children:"Wiki ingest"}),e.jsx("div",{className:"mt-2 text-[14px] font-semibold text-white",children:Z.job.titleHint||Z.job.latestMessage||"Background ingest"}),e.jsxs("div",{className:"mt-1 text-[12px] leading-5 text-white/56",children:[Z.job.status," · ",Z.job.phase," ·"," ",Z.job.progressPercent,"% ·"," ",Ox(Z.job.updatedAt)]}),e.jsxs("div",{className:"mt-2 text-[12px] leading-5 text-white/46",children:[Z.job.createdPageCount," pages ·"," ",Z.job.createdEntityCount," entities ·"," ",Z.job.acceptedCount," accepted ·"," ",Z.job.rejectedCount," rejected"]})]}),e.jsx("div",{className:"shrink-0",children:He?e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-xs text-white/58",children:[e.jsx(ps,{className:"size-3.5 animate-spin"}),"Running"]}):e.jsx(O,{tone:"meta",children:Z.job.phase})})]})},Z.job.id)})})})]})]})}),e.jsx(iu,{className:"fixed z-40 lg:bottom-6 lg:right-6",goals:w.snapshot.dashboard.goals,projects:w.snapshot.dashboard.projects,tags:w.snapshot.tags,users:w.snapshot.users,defaultUserId:w.selectedUserIds.length===1?w.selectedUserIds[0]:null,onCreateGoal:w.createGoal,onCreateProject:w.createProject,onCreateTask:w.createTask})]})}function Qx(){var q;cu();const t=c.useRef(`forge_session_${Math.random().toString(36).slice(2,10)}`),s=c.useRef(null),i=c.useRef(null),n=We(),[a,r]=c.useState(Fx),[l,d]=c.useState(!1),[o,x]=c.useState({}),[f,b]=c.useState(null),[m,h]=c.useState(null),p=pe({queryKey:["forge-shell-operator-session"],queryFn:Ci}),w=pe({queryKey:["forge-snapshot",...a],queryFn:()=>yd(a),enabled:p.isSuccess}),v=pe({queryKey:["forge-settings"],queryFn:Wa,enabled:p.isSuccess});c.useEffect(()=>{_x(a)},[a]),c.useEffect(()=>{p.isSuccess&&n.invalidateQueries({predicate:G=>{const[Q]=G.queryKey;return Q==="notes-index"||Q==="project-board"||Q==="task-context"||typeof Q=="string"&&Q.startsWith("forge-")}})},[p.isSuccess,n,a]),c.useEffect(()=>{var ne;const G=(ne=w.data)==null?void 0:ne.metrics.totalXp;if(typeof G!="number")return;if(i.current===null){i.current=G;return}const Q=G-i.current;i.current=G,Q!==0&&(h({deltaXp:Q,totalXp:G}),s.current!==null&&window.clearTimeout(s.current),s.current=window.setTimeout(()=>{h(null),s.current=null},2600))},[(q=w.data)==null?void 0:q.metrics.totalXp]),c.useEffect(()=>()=>{s.current!==null&&window.clearTimeout(s.current)},[]),c.useEffect(()=>{if(!p.isSuccess)return;let G=!1,Q=!1,ne=!1;const H=()=>{G=!0},_=(C,J)=>kx({sessionId:t.current,eventType:C,metrics:J}).catch(()=>{});_("session_started",{visible:document.visibilityState==="visible",interacted:!1});const U=window.setTimeout(()=>{document.visibilityState==="visible"&&G&&!Q&&(Q=!0,_("dwell_120_seconds",{visible:!0,interacted:!0}))},12e4),R=()=>{const C=Math.max(1,document.documentElement.scrollHeight-window.innerHeight),J=Math.round(window.scrollY/C*100);J>=75&&G&&!ne&&(ne=!0,_("scroll_depth_75",{visible:document.visibilityState==="visible",interacted:!0,scrollDepth:J}))};return window.addEventListener("pointerdown",H),window.addEventListener("keydown",H),window.addEventListener("scroll",R,{passive:!0}),()=>{window.clearTimeout(U),window.removeEventListener("pointerdown",H),window.removeEventListener("keydown",H),window.removeEventListener("scroll",R)}},[p.isSuccess]);const I=ge({mutationFn:G=>Ea(G),onSuccess:async()=>{await n.invalidateQueries({queryKey:["forge-snapshot"]})}}),k=ge({mutationFn:G=>Dd(G),onSuccess:async()=>{await n.invalidateQueries({queryKey:["forge-snapshot"]})}}),S=ge({mutationFn:G=>$d(G),onSuccess:async()=>{await n.invalidateQueries({queryKey:["forge-snapshot"]})}}),M=ge({mutationFn:({goalId:G,patch:Q})=>vx(G,Q),onSuccess:async()=>{await n.invalidateQueries({queryKey:["forge-snapshot"]})}}),P=ge({mutationFn:({projectId:G,patch:Q})=>Od(G,Q),onSuccess:async()=>{await n.invalidateQueries({queryKey:["forge-snapshot"]})}}),y=ge({mutationFn:({taskId:G,status:Q})=>Yi(G,{status:Q}),onSuccess:async()=>{await n.invalidateQueries({queryKey:["forge-snapshot"]})}}),N=ge({mutationFn:({taskId:G,input:Q})=>Sx(G,Q),onSuccess:async()=>{await n.invalidateQueries({queryKey:["forge-snapshot"]})}}),A=ge({mutationFn:G=>Ix(G),onSuccess:async()=>{await n.invalidateQueries({queryKey:["forge-snapshot"]})}}),T=ge({mutationFn:({runId:G,actor:Q,note:ne})=>zd(G,{actor:Q,note:ne??""}),onSuccess:async()=>{await n.invalidateQueries({queryKey:["forge-snapshot"]})}}),F=ge({mutationFn:({runId:G,actor:Q,note:ne})=>Rd(G,{actor:Q,note:ne??""}),onSuccess:async()=>{await n.invalidateQueries({queryKey:["forge-snapshot"]})}}),u=ge({mutationFn:async G=>{var U,R;const Q=(U=w.data)==null?void 0:U.dashboard.projects.find(C=>C.id===G.projectId);if(!Q)throw new Error("Select a project before starting work.");const ne=((R=v.data)==null?void 0:R.settings.profile.operatorName)??"Albert",H=await Ea({title:G.title,description:G.description,owner:ne,userId:Q.userId??(a.length===1?a[0]:null),goalId:Q.goalId,projectId:Q.id,priority:"medium",status:"in_progress",effort:"deep",energy:"steady",dueDate:"",points:60,tagIds:[],notes:[]});if(!await j(H.task.id,{actor:ne,timerMode:G.timerMode,plannedDurationSeconds:G.plannedDurationSeconds,isCurrent:!0,leaseTtlSeconds:1800,note:""}))throw new Error("The task was created, but live work did not start because the calendar override was cancelled.");return H.task},onSuccess:async()=>{await n.invalidateQueries({queryKey:["forge-snapshot"]})}}),j=async(G,Q)=>{try{return await N.mutateAsync({taskId:G,input:Q}),!0}catch(ne){if(ne instanceof qa&&ne.code==="task_run_calendar_blocked"&&typeof window<"u"){const H=window.prompt("Calendar rules block this task right now. Add a reason to override and start anyway.");return!H||H.trim().length===0?!1:(await N.mutateAsync({taskId:G,input:{...Q,overrideReason:H.trim()}}),!0)}throw ne}};if(c.useEffect(()=>{const G=w.data;if(!G||G.activeTaskRuns.length===0)return;const Q=window.setInterval(()=>{if(document.visibilityState==="visible"){for(const ne of G.activeTaskRuns)Cx(ne.id,{actor:ne.actor,leaseTtlSeconds:ne.leaseTtlSeconds,note:ne.note}).catch(()=>{});n.invalidateQueries({queryKey:["forge-snapshot"]})}},3e4);return()=>window.clearInterval(Q)},[n,w.data]),p.isLoading||w.isLoading||v.isLoading)return e.jsx("div",{className:"grid min-h-screen place-items-center p-6",children:e.jsx(xt,{eyebrow:"Forge shell",title:"Loading Forge",description:"Checking your operator session and loading your latest snapshot."})});if(p.isError)return e.jsx("div",{className:"grid min-h-screen place-items-center p-6",children:e.jsx(Oe,{eyebrow:"Forge operator session",error:p.error,onRetry:()=>void n.invalidateQueries({queryKey:["forge-shell-operator-session"]})})});if(v.isError)return e.jsx("div",{className:"grid min-h-screen place-items-center p-6",children:e.jsx(Oe,{eyebrow:"Forge settings",error:v.error,onRetry:()=>void n.invalidateQueries({queryKey:["forge-settings"]})})});if(w.isError||!w.data||!v.data)return e.jsx("div",{className:"grid min-h-screen place-items-center p-6",children:e.jsx(Oe,{eyebrow:"Forge state",error:w.error,onRetry:()=>void n.invalidateQueries({queryKey:["forge-snapshot"]})})});const L={snapshot:w.data,selectedUserIds:a,setSelectedUserIds:r,refresh:async()=>{await n.invalidateQueries({queryKey:["forge-snapshot"]})},createTask:async G=>{await I.mutateAsync(G)},startTaskNow:async(G,Q={})=>{const ne=v.data.settings.profile.operatorName;await j(G,{actor:ne,timerMode:Q.timerMode??"planned",plannedDurationSeconds:Q.plannedDurationSeconds===void 0?1200:Q.plannedDurationSeconds,isCurrent:!0,leaseTtlSeconds:1800,note:""})},createGoal:async G=>{await k.mutateAsync(G)},createProject:async G=>{await S.mutateAsync(G)},patchGoal:async(G,Q)=>{await M.mutateAsync({goalId:G,patch:Q})},patchProject:async(G,Q)=>{await P.mutateAsync({projectId:G,patch:Q})},patchTaskStatus:async(G,Q)=>{await y.mutateAsync({taskId:G,status:Q})},openStartWork:(G={})=>{x(G),b(null),d(!0)}};return e.jsx(Fh,{locale:v.data.settings.localePreference,children:e.jsx(qd.Provider,{value:L,children:e.jsxs(e.Fragment,{children:[e.jsx(Ux,{settings:v.data.settings,timerPending:A.isPending||T.isPending||F.isPending,startWorkOpen:l,startWorkPending:N.isPending||u.isPending,startWorkError:f,startWorkDefaults:o,onOpenStartWork:G=>{x(G??{}),b(null),d(!0)},onCloseStartWork:()=>{d(!1),b(null)},onStartExistingTask:async(G,Q)=>{try{const ne=v.data.settings.profile.operatorName;await j(G,{actor:ne,timerMode:Q.timerMode,plannedDurationSeconds:Q.plannedDurationSeconds,isCurrent:!0,leaseTtlSeconds:1800,note:""})&&(d(!1),b(null))}catch(ne){b(ne instanceof Error?ne.message:"Could not start work.")}},onCreateAndStartTask:async G=>{try{await u.mutateAsync(G),d(!1),b(null)}catch(Q){b(Q instanceof Error?Q.message:"Could not create and start the task.")}},onFocusRun:async G=>{await A.mutateAsync(G)},onPauseRun:async G=>{const Q=w.data.activeTaskRuns.find(ne=>ne.id===G);await T.mutateAsync({runId:G,actor:Q==null?void 0:Q.actor,note:Q==null?void 0:Q.note})},onCompleteRun:async G=>{const Q=w.data.activeTaskRuns.find(ne=>ne.id===G);await F.mutateAsync({runId:G,actor:Q==null?void 0:Q.actor,note:Q==null?void 0:Q.note})},children:e.jsx(mm,{context:L})}),m?e.jsx("div",{className:"pointer-events-none fixed inset-x-0 bottom-24 z-50 flex justify-center px-4 lg:bottom-6",children:e.jsxs("div",{className:re("inline-flex items-center gap-2 rounded-full border px-4 py-2 text-sm font-medium shadow-[0_18px_48px_rgba(3,8,18,0.38)] backdrop-blur-xl",m.deltaXp>0?"border-emerald-400/30 bg-emerald-500/14 text-emerald-100":"border-rose-400/30 bg-rose-500/14 text-rose-100"),children:[e.jsx(Gi,{className:"size-4 shrink-0"}),e.jsxs("span",{children:[m.deltaXp>0?`XP +${m.deltaXp}`:`XP ${m.deltaXp}`," ","· ",Kd(m.totalXp)," total"]})]})}):null]})})})}function Ye(){return c.useContext(qd)??hm()}function cn(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g," ")}function Wx({eyebrow:t,titleText:s,entityKind:i,copyMode:n}){if(!t||n==="title_only"||typeof t!="string")return null;const a=cn(t),r=s?cn(s):null,l=i?cn(Ts(i).label):null;return!a||r&&(a===r||r.includes(a)||a.includes(r))||l&&a===l?null:t}function Ke({eyebrow:t,entityKind:s,title:i,titleText:n,description:a,badge:r,actions:l,copyMode:d="title_only"}){const o=s?Ts(s):null,x=o==null?void 0:o.icon,f=Wx({eyebrow:t,titleText:n,entityKind:s,copyMode:d}),b=!!(o||f||r);return e.jsxs("section",{className:"grid w-full max-w-full min-w-0 gap-1.5 rounded-[24px] bg-[var(--hero-gradient)] px-4 py-2.5 shadow-[var(--card-shadow)] lg:grid-cols-[minmax(0,1fr)_auto] lg:px-5 lg:py-3",children:[e.jsxs("div",{className:"min-w-0",children:[b?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[o&&x?e.jsx("div",{className:re("inline-flex size-8 shrink-0 items-center justify-center rounded-full border bg-white/[0.04] shadow-[inset_0_1px_0_rgba(255,255,255,0.08)]",o.subtleBadgeClassName),"aria-label":o.label,title:o.label,children:e.jsx(x,{className:re("size-4",o.iconClassName)})}):null,f?e.jsx("div",{className:"type-label text-[var(--secondary)]",children:f}):null,r?e.jsx(O,{tone:"signal",className:"bg-white/[0.08] text-white/78",children:r}):null]}):null,e.jsx("div",{className:re("max-w-4xl text-[clamp(1.2rem,1.85vw,1.7rem)] leading-[1] text-white",b?"mt-1.5":""),children:i}),e.jsx("div",{className:"mt-1 hidden max-w-3xl text-[13px] leading-5 text-white/54 sm:block",children:a})]}),l?e.jsx("div",{className:"flex min-w-0 flex-wrap items-start gap-2 lg:justify-end",children:l}):null]})}function Ms(t){return t.entityType==="goal"?`/goals/${t.entityId}`:t.entityType==="project"?`/projects/${t.entityId}`:t.entityType==="task"?`/tasks/${t.entityId}`:t.entityType==="strategy"?`/strategies/${t.entityId}`:t.entityType==="task_run"&&typeof t.metadata.taskId=="string"?`/tasks/${t.metadata.taskId}`:null}function Aa(t){return t.entityType==="goal"?"Open goal":t.entityType==="project"?"Open project":t.entityType==="strategy"?"Open strategy":t.entityType==="task"||t.entityType==="task_run"?"Open task":null}const ui=yh(),fl=[ui.accessor("title",{header:"Event",cell:t=>{const s=Ms(t.row.original);return s?e.jsx(Le,{to:s,className:"font-medium text-white transition hover:text-[var(--primary)]",children:t.getValue()}):e.jsx("div",{className:"font-medium text-white",children:t.getValue()})}}),ui.accessor("source",{header:"Source",cell:t=>e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/50",children:t.getValue()})}),ui.display({id:"owner",header:"Owner",cell:t=>t.row.original.user?e.jsx($e,{user:t.row.original.user,compact:!0}):e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/32",children:"Unowned"})}),ui.accessor("createdAt",{header:"When",cell:t=>e.jsx("div",{className:"text-sm text-white/55",children:er(t.getValue())})}),ui.display({id:"actions",header:"Open",cell:t=>{const s=Ms(t.row.original);return s?e.jsx(Le,{to:s,className:"inline-flex text-[11px] uppercase tracking-[0.16em] text-[var(--primary)] transition hover:text-white",children:"Open"}):e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/32",children:"Archive only"})}})];function Gx({rows:t,onRemove:s}){const i=s?[...fl,ui.display({id:"remove",header:"Correct",cell:a=>e.jsx(W,{variant:"ghost",className:"h-auto px-0 py-0 text-[11px] uppercase tracking-[0.16em] text-white/55",onClick:()=>{s(a.row.original.id)},children:"Remove log"})})]:fl,n=jh({columns:i,data:t,getCoreRowModel:Nh()});return e.jsx(se,{className:"overflow-hidden p-0",children:e.jsxs("table",{className:"w-full border-collapse",children:[e.jsx("thead",{children:n.getHeaderGroups().map(a=>e.jsx("tr",{className:"bg-white/[0.03]",children:a.headers.map(r=>e.jsx("th",{className:"px-5 py-4 text-left font-label text-[11px] uppercase tracking-[0.18em] text-white/40",children:r.isPlaceholder?null:Yr(r.column.columnDef.header,r.getContext())},r.id))},a.id))}),e.jsx("tbody",{children:n.getRowModel().rows.map(a=>e.jsx("tr",{className:"bg-white/[0.015] transition hover:bg-white/[0.035]",children:a.getVisibleCells().map(r=>e.jsx("td",{className:"px-5 py-4 align-top",children:Yr(r.column.columnDef.cell,r.getContext())},r.id))},a.id))})]})})}function Hx(){var b;const t=Ye(),s=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],[i]=ft(),n=We(),a=i.get("entityId")??void 0,r=i.get("entityType")??void 0,l=i.get("eventId"),d=pe({queryKey:["activity-archive",r,a,...s],queryFn:()=>bx({limit:100,entityType:r,entityId:a,userIds:s})}),o=ge({mutationFn:m=>_d(m),onSuccess:async()=>{await Promise.all([n.invalidateQueries({queryKey:["activity-archive"]}),n.invalidateQueries({queryKey:["forge-snapshot"]}),n.invalidateQueries({queryKey:["task-context"]}),n.invalidateQueries({queryKey:["project-board"]})])}}),x=((b=d.data)==null?void 0:b.activity)??[];if(d.isLoading)return e.jsx(xt,{eyebrow:"Evidence archive",title:"Loading activity",description:"Pulling the visible audit trail, grouped evidence, and correction history."});if(d.isError)return e.jsx(Oe,{eyebrow:"Evidence archive",error:d.error,onRetry:()=>void d.refetch()});if(x.length===0)return e.jsx(gt,{eyebrow:"Evidence archive",title:a?"No evidence matched this filter":"No activity recorded yet",description:a?"Forge could not find visible events for this specific entity yet. Try a broader archive view or create some work first.":"As you complete work, log runs, or make corrections, the audit trail will appear here."});const f=x.reduce((m,h)=>{const p=h.createdAt.slice(0,10);return m[p]=[...m[p]??[],h],m},{});return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{title:"Activity",description:a?"This filtered archive shows the evidence connected to the item you opened, so you can confirm what changed and when.":"Activity is your visible audit trail. Use it to inspect progress, confirm corrections, and trace work back to the goal, project, or task it came from.",badge:`${x.length} recent events`}),e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]",children:[e.jsx(Gx,{rows:x,onRemove:async m=>{await o.mutateAsync(m)}}),e.jsx("div",{className:"grid gap-4",children:Object.entries(f).slice(0,6).map(([m,h])=>e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:m}),e.jsx("div",{className:"mt-4 grid gap-3",children:h.slice(0,3).map(p=>e.jsxs("div",{className:`rounded-[18px] p-4 ${l===p.id?"bg-[rgba(192,193,255,0.12)] shadow-[inset_0_0_0_1px_rgba(192,193,255,0.2)]":"bg-white/[0.04]"}`,children:[e.jsx("div",{className:"font-medium text-white",children:p.title}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:p.description}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.16em] text-white/35",children:er(p.createdAt)}),Ms(p)&&Aa(p)?e.jsx(Le,{to:Ms(p),className:"mt-3 inline-flex text-[11px] uppercase tracking-[0.16em] text-[var(--primary)]",children:Aa(p)}):null]},p.id))})]},m))})]})]})}function mn(t){return t.trim().toLowerCase()}function wl(t,s){return t.includes(s)?t:[...t,s]}function st({options:t,selectedValues:s,onChange:i,placeholder:n="Search or create…",emptyMessage:a="No matching entries yet.",createLabel:r="Create",onCreate:l,className:d}){const[o,x]=c.useState(""),[f,b]=c.useState(!1),[m,h]=c.useState(0),[p,w]=c.useState(!1),[v,I]=c.useState(null),[k,S]=c.useState([]),M=c.useMemo(()=>{const j=new Map;return[...k,...t].forEach(L=>{j.set(L.value,L)}),Array.from(j.values())},[k,t]),P=c.useMemo(()=>s.map(j=>M.find(L=>L.value===j)??{value:j,label:j}),[M,s]),y=mn(o),N=c.useMemo(()=>{const j=M.filter(L=>!s.includes(L.value));return y?j.filter(L=>`${L.label} ${L.description??""} ${L.searchText??""}`.toLowerCase().includes(y)).slice(0,8):j.slice(0,8)},[M,y,s]),A=M.some(j=>mn(j.label)===y),T=j=>{i(wl(s,j)),x(""),I(null),h(0),b(!1)},F=j=>{i(s.filter(L=>L!==j))},u=async()=>{const j=o.trim();if(!(!l||!j)){w(!0);try{const L=await l(j);S(q=>q.some(G=>G.value===L.value)?q:[L,...q]),i(wl(s,L.value)),x(""),I(null),h(0),b(!1)}catch(L){I(L instanceof Error?L.message:"Unable to create that link right now.")}finally{w(!1)}}};return e.jsxs("div",{className:re("relative grid gap-2",d),children:[e.jsxs("div",{className:"rounded-[22px] border border-white/10 bg-white/[0.04] px-3 py-3",children:[P.length>0?e.jsx("div",{className:"mb-2 flex flex-wrap gap-2",children:P.map(j=>e.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-2",children:[j.kind?e.jsx(ke,{kind:j.kind,label:j.label,compact:!0,className:"max-w-[16rem]"}):j.badge?j.badge:e.jsx("span",{className:"inline-flex items-center gap-2 rounded-full bg-white/[0.08] px-3 py-1.5 text-sm text-white/78",children:e.jsx("span",{className:"max-w-[16rem] truncate",children:j.label})}),e.jsx("button",{type:"button",className:"rounded-full text-white/50 transition hover:text-white","aria-label":`Remove ${j.label}`,onClick:()=>F(j.value),children:e.jsx(mt,{className:"size-3.5"})})]},j.value))}):null,e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dt,{className:"size-4 text-white/34"}),e.jsx("input",{value:o,onChange:j=>{x(j.target.value),I(null),b(!0),h(0)},onFocus:()=>b(!0),onBlur:()=>{window.setTimeout(()=>b(!1),120)},onKeyDown:j=>{if(j.key==="Backspace"&&!o&&s.length>0){F(s[s.length-1]);return}if(j.key==="ArrowDown"){j.preventDefault(),b(!0),h(G=>N.length===0?0:Math.min(N.length-1,G+1));return}if(j.key==="ArrowUp"){j.preventDefault(),h(G=>Math.max(0,G-1));return}if(j.key==="Escape"){b(!1);return}if(j.key!=="Enter")return;j.preventDefault();const L=N[m];if(L){T(L.value);return}const q=M.find(G=>mn(G.label)===y);if(q&&!s.includes(q.value)){T(q.value);return}u()},placeholder:n,className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]})]}),f?e.jsxs("div",{className:"absolute top-full z-20 mt-1.5 max-h-64 w-full overflow-y-auto rounded-[22px] border border-white/10 bg-[rgba(10,15,27,0.96)] p-2 shadow-[0_26px_60px_rgba(4,8,18,0.32)] backdrop-blur-xl",children:[N.map((j,L)=>e.jsx("button",{type:"button",className:re("flex w-full items-start justify-between gap-3 rounded-[18px] px-3 py-2.5 text-left transition",L===m?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>h(L),onMouseDown:q=>q.preventDefault(),onClick:()=>T(j.value),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:j.kind?e.jsx(ke,{kind:j.kind,label:j.label,compact:!0,gradient:!1}):j.menuBadge?j.menuBadge:j.badge?j.badge:j.label}),j.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/46",children:j.description}):null]})},j.value)),!A&&y&&l?e.jsxs("button",{type:"button",disabled:p,className:"mt-1 flex w-full items-center gap-2 rounded-[18px] px-3 py-2.5 text-left text-sm text-[var(--secondary)] transition hover:bg-white/[0.06] disabled:opacity-50",onMouseDown:j=>j.preventDefault(),onClick:()=>void u(),children:[e.jsx(Wt,{className:"size-4"}),e.jsx("span",{className:"truncate",children:p?"Creating…":`${r} "${o.trim()}"`})]}):null,N.length===0&&(!y||A||!l)?e.jsx("div",{className:"px-3 py-2.5 text-sm text-white/42",children:a}):null]}):null,v?e.jsx("div",{className:"text-sm text-rose-300",children:v}):null]})}const Xx={goal:"goal",project:"project",task:"task",strategy:"strategy",habit:"habit"};function Js(t){const s=new Date(t);return new Date(s.getTime()-s.getTimezoneOffset()*6e4).toISOString().slice(0,16)}function vl(t,s){var r,l,d,o,x;const i=new Date,n=new Date(i.getTime()+30*6e4),a=new Date(n.getTime()+60*6e4);return{title:(s==null?void 0:s.title)??(t==null?void 0:t.title)??"",description:(s==null?void 0:s.description)??(t==null?void 0:t.description)??"",location:(s==null?void 0:s.location)??(t==null?void 0:t.location)??"",placeAddress:((r=s==null?void 0:s.place)==null?void 0:r.address)??((l=t==null?void 0:t.place)==null?void 0:l.address)??"",placeTimezone:((d=s==null?void 0:s.place)==null?void 0:d.timezone)??((o=t==null?void 0:t.place)==null?void 0:o.timezone)??"",startAtLocal:t?Js(t.startAt):s!=null&&s.startAt?Js(s.startAt):Js(n.toISOString()),endAtLocal:t?Js(t.endAt):s!=null&&s.endAt?Js(s.endAt):Js(a.toISOString()),timezone:(s==null?void 0:s.timezone)??(t==null?void 0:t.timezone)??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",availability:(s==null?void 0:s.availability)??(t==null?void 0:t.availability)??"busy",preferredCalendarId:s&&"preferredCalendarId"in s?s.preferredCalendarId:(t==null?void 0:t.calendarId)??void 0,categoriesText:((x=s==null?void 0:s.categories)==null?void 0:x.join(", "))??(t==null?void 0:t.categories.join(", "))??"",linkQuery:"",links:(s==null?void 0:s.links)??(t==null?void 0:t.links.map(f=>({entityType:f.entityType,entityId:f.entityId,relationshipType:f.relationshipType,label:`${f.entityType.replaceAll("_"," ")} · ${f.entityId}`})))??[]}}function Jx({open:t,onOpenChange:s,writableCalendars:i,linkOptions:n,event:a,seed:r,onSubmit:l,pending:d=!1}){const[o,x]=c.useState(()=>vl(a,r)),[f,b]=c.useState(null);c.useEffect(()=>{t&&(x(vl(a,r)),b(null))},[a,t,r]);const m=c.useMemo(()=>n.map(p=>{const w=Xx[p.entityType];return{value:`${p.entityType}:${p.entityId}`,label:p.label,description:p.subtitle,searchText:`${p.label} ${p.subtitle} ${p.entityType}`,kind:w,menuBadge:w?e.jsx(ke,{kind:w,label:p.label,compact:!0,gradient:!1}):void 0,badge:w?e.jsx(ke,{kind:w,label:p.label,compact:!0}):void 0}}),[n]),h=c.useMemo(()=>[{id:"identity",eyebrow:"Event",title:a?"Refine the Forge event":"Create a Forge calendar event",description:"This event belongs to Forge first. If you choose a writable calendar, Forge will also project it to the connected provider.",render:(p,w)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(Y,{label:"Title",children:e.jsx(ie,{value:p.title,onChange:v=>w({title:v.target.value}),placeholder:"Weekly research supervision"})}),e.jsx(Y,{label:"Description",children:e.jsx(Ce,{value:p.description,onChange:v=>w({description:v.target.value}),placeholder:"Agenda, context, or outcomes you want this event to carry."})}),e.jsx(Y,{label:"Location",children:e.jsx(ie,{value:p.location,onChange:v=>w({location:v.target.value}),placeholder:"Clinic room 2 or Zoom"})}),e.jsx(Y,{label:"Place address",children:e.jsx(ie,{value:p.placeAddress,onChange:v=>w({placeAddress:v.target.value}),placeholder:"Bahnhofstrasse 10, Zurich"})}),e.jsx(Y,{label:"Place timezone",children:e.jsx(ie,{value:p.placeTimezone,onChange:v=>w({placeTimezone:v.target.value}),placeholder:"Europe/Zurich"})})]})},{id:"timing",eyebrow:"Timing",title:"Set the time and visibility",description:"Forge stores the real event window, timezone, and whether it should behave like a busy or free slot for scheduling rules.",render:(p,w)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Y,{label:"Starts",children:e.jsx(ie,{type:"datetime-local",value:p.startAtLocal,onChange:v=>w({startAtLocal:v.target.value})})}),e.jsx(Y,{label:"Ends",children:e.jsx(ie,{type:"datetime-local",value:p.endAtLocal,onChange:v=>w({endAtLocal:v.target.value})})})]}),e.jsx(Y,{label:"Timezone",children:e.jsx(ie,{value:p.timezone,onChange:v=>w({timezone:v.target.value}),placeholder:"Europe/Zurich"})}),e.jsx(Y,{label:"Availability",children:e.jsx(tt,{value:p.availability,onChange:v=>w({availability:v}),options:[{value:"busy",label:"Busy",description:"This event should block timebox recommendations and rule checks."},{value:"free",label:"Free",description:"This event stays visible in the calendar without blocking work."}]})})]})},{id:"links",eyebrow:"Meaning",title:"Connect the event to Forge entities",description:"Attach this event to strategies, goals, projects, tasks, or habits so the calendar carries multi-user operating context instead of staying isolated.",render:(p,w)=>e.jsx("div",{className:"grid gap-4",children:e.jsx(Y,{label:"Search Forge entities",description:"Search across human and bot-owned entities; the linked records use the same icon, color, and owner system as the rest of Forge.",children:e.jsx(st,{options:m,selectedValues:p.links.map(v=>`${v.entityType}:${v.entityId}`),onChange:v=>{w({links:v.map(I=>{const[k,...S]=I.split(":"),M=S.join(":"),P=n.find(y=>y.entityType===k&&y.entityId===M);return P?{entityType:P.entityType,entityId:P.entityId,relationshipType:"context",label:P.label}:null}).filter(I=>I!==null)})},placeholder:"Search strategies, goals, projects, tasks, habits, human, or bot owners",emptyMessage:"No matching Forge entities found."})})})},{id:"projection",eyebrow:"Projection",title:"Choose where this event should live remotely",description:"You can keep the event local to Forge, or choose a writable connected calendar so Forge also keeps a synced remote copy.",render:(p,w)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"grid gap-3",children:[i.length>0?e.jsxs("button",{type:"button",onClick:()=>w({preferredCalendarId:void 0}),className:`rounded-[22px] border px-4 py-4 text-left transition ${p.preferredCalendarId===void 0?"border-[rgba(125,211,252,0.28)] bg-[rgba(125,211,252,0.14)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(us,{className:"size-4"}),"Default synced calendar"]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/55",children:"Let Forge use the default writable connected calendar automatically."})]}):null,e.jsxs("button",{type:"button",onClick:()=>w({preferredCalendarId:null}),className:`rounded-[22px] border px-4 py-4 text-left transition ${p.preferredCalendarId===null?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.14)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(vt,{className:"size-4"}),"Forge only"]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/55",children:"Keep the event in Forge without creating a remote provider copy yet."})]}),i.map(v=>e.jsxs("button",{type:"button",onClick:()=>w({preferredCalendarId:v.id}),className:`rounded-[22px] border px-4 py-4 text-left transition ${p.preferredCalendarId===v.id?"border-[rgba(125,211,252,0.28)] bg-[rgba(125,211,252,0.14)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(us,{className:"size-4"}),v.title]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/55",children:v.description||`${v.timezone} · writable`})]},v.id))]}),e.jsxs("div",{className:"grid gap-2 rounded-[22px] border border-white/8 bg-white/[0.04] p-4 text-sm text-white/66",children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium text-white",children:[e.jsx(wm,{className:"size-4 text-[var(--primary)]"}),"Categories and filtering"]}),e.jsx(ie,{value:p.categoriesText,onChange:v=>w({categoriesText:v.target.value}),placeholder:"meeting, clinic, research"})]})]})}],[a,n,m,i]);return e.jsx(it,{open:t,onOpenChange:s,eyebrow:a?"Edit event":"New event",title:a?"Edit calendar event":"Create calendar event",description:"Forge-owned events can stay local or publish to a connected provider calendar.",value:o,onChange:x,steps:h,onSubmit:async()=>{if(!o.title.trim()){b("Add an event title before saving.");return}if(!o.startAtLocal||!o.endAtLocal){b("Set both the start and end time before saving.");return}if(new Date(o.endAtLocal).getTime()<=new Date(o.startAtLocal).getTime()){b("The event end time must be after the start time.");return}b(null),await l({title:o.title.trim(),description:o.description.trim(),location:o.location.trim(),place:{label:o.location.trim(),address:o.placeAddress.trim(),timezone:o.placeTimezone.trim(),latitude:null,longitude:null,source:o.placeAddress.trim()?"manual":"",externalPlaceId:""},startAt:new Date(o.startAtLocal).toISOString(),endAt:new Date(o.endAtLocal).toISOString(),timezone:o.timezone.trim()||"UTC",availability:o.availability,categories:o.categoriesText.split(",").map(p=>p.trim()).filter(Boolean),links:o.links.map(p=>({entityType:p.entityType,entityId:p.entityId,relationshipType:p.relationshipType})),...o.preferredCalendarId!==void 0?{preferredCalendarId:o.preferredCalendarId}:{}})},submitLabel:a?"Save event":"Create event",pending:d,pendingLabel:a?"Saving":"Creating",error:f})}function Yx({open:t,onOpenChange:s,initialTitle:i,pending:n=!1,onSubmit:a}){const[r,l]=c.useState(i),[d,o]=c.useState(null);return c.useEffect(()=>{t&&(l(i),o(null))},[i,t]),e.jsx(it,{open:t,onOpenChange:s,eyebrow:"Calendar",title:"Quick rename",description:"Rename the event without reopening the full event guide.",value:{title:r},onChange:x=>l(x.title),steps:[{id:"rename",eyebrow:"Rename",title:"Update the event title",description:"Keep the rename fast and direct. Everything else on the event stays unchanged.",render:(x,f)=>e.jsx(Y,{label:"Event title",children:e.jsx(ie,{value:x.title,onChange:b=>f({title:b.target.value}),placeholder:"Weekly research supervision"})})}],submitLabel:"Save title",pending:n,pendingLabel:"Saving",error:d,onSubmit:async()=>{const x=r.trim();if(!x){o("Add a title before saving.");return}o(null),await a(x),s(!1)}})}const yl=[{value:"main_activity",label:"Main activity"},{value:"secondary_activity",label:"Secondary activity"},{value:"third_activity",label:"Third activity"},{value:"rest",label:"Rest"},{value:"holiday",label:"Holiday"},{value:"custom",label:"Custom"}],jl=[{value:"busy",label:"Busy"},{value:"free",label:"Free"}],Yt={allowWorkBlockKinds:[],blockWorkBlockKinds:[],allowCalendarIds:[],blockCalendarIds:[],allowEventTypes:[],blockEventTypes:[],allowEventKeywords:[],blockEventKeywords:[],allowAvailability:[],blockAvailability:[]};function Ys(t){return t.join(", ")}function Vs(t){return t.split(",").map(s=>s.trim()).filter(Boolean)}function ia({label:t,selected:s,onToggle:i,options:n}){return e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:t}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(a=>{const r=s.includes(a.value);return e.jsx("button",{type:"button",onClick:()=>i(a.value),className:`rounded-full px-3 py-2 text-sm transition ${r?"bg-[var(--primary)]/18 text-[var(--primary)] shadow-[inset_0_0_0_1px_rgba(192,193,255,0.24)]":"bg-white/[0.05] text-white/62 hover:bg-white/[0.08]"}`,children:a.label},a.value)})})]})}function pr({title:t,subtitle:s,initialRules:i,initialPlannedDurationSeconds:n,onSave:a,saveLabel:r="Save scheduling rules",allowPlannedDuration:l=!1}){const[d,o]=c.useState((i==null?void 0:i.allowWorkBlockKinds)??Yt.allowWorkBlockKinds),[x,f]=c.useState((i==null?void 0:i.blockWorkBlockKinds)??Yt.blockWorkBlockKinds),[b,m]=c.useState((i==null?void 0:i.allowAvailability)??Yt.allowAvailability),[h,p]=c.useState((i==null?void 0:i.blockAvailability)??Yt.blockAvailability),[w,v]=c.useState(Ys((i==null?void 0:i.allowCalendarIds)??Yt.allowCalendarIds)),[I,k]=c.useState(Ys((i==null?void 0:i.blockCalendarIds)??Yt.blockCalendarIds)),[S,M]=c.useState(Ys((i==null?void 0:i.allowEventTypes)??Yt.allowEventTypes)),[P,y]=c.useState(Ys((i==null?void 0:i.blockEventTypes)??Yt.blockEventTypes)),[N,A]=c.useState(Ys((i==null?void 0:i.allowEventKeywords)??Yt.allowEventKeywords)),[T,F]=c.useState(Ys((i==null?void 0:i.blockEventKeywords)??Yt.blockEventKeywords)),[u,j]=c.useState(n?String(Math.round(n/60)):"30"),[L,q]=c.useState(!1),G=c.useMemo(()=>({allowWorkBlockKinds:d,blockWorkBlockKinds:x,allowCalendarIds:Vs(w),blockCalendarIds:Vs(I),allowEventTypes:Vs(S),blockEventTypes:Vs(P),allowEventKeywords:Vs(N),blockEventKeywords:Vs(T),allowAvailability:b,blockAvailability:h}),[b,w,N,S,d,h,I,T,P,x]),Q=Object.values(G).every(H=>H.length===0),ne=(H,_,U)=>{_(H.includes(U)?H.filter(R=>R!==U):[...H,U])};return e.jsxs(se,{className:"grid gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:t}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:s})]}),l?e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Planned duration"}),e.jsx(ie,{type:"number",min:15,step:15,value:u,onChange:H=>j(H.target.value),placeholder:"30"})]}):null,e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx(ia,{label:"Allow work blocks",selected:d,onToggle:H=>ne(d,o,H),options:yl}),e.jsx(ia,{label:"Block work blocks",selected:x,onToggle:H=>ne(x,f,H),options:yl}),e.jsx(ia,{label:"Allow availability",selected:b,onToggle:H=>ne(b,m,H),options:jl}),e.jsx(ia,{label:"Block availability",selected:h,onToggle:H=>ne(h,p,H),options:jl})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Allow calendar ids"}),e.jsx(ie,{value:w,onChange:H=>v(H.target.value),placeholder:"calendar_123, primary"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Block calendar ids"}),e.jsx(ie,{value:I,onChange:H=>k(H.target.value),placeholder:"calendar_456"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Allow event types"}),e.jsx(ie,{value:S,onChange:H=>M(H.target.value),placeholder:"focus, personal"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Block event types"}),e.jsx(ie,{value:P,onChange:H=>y(H.target.value),placeholder:"out-of-office, main-work"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Allow event keywords"}),e.jsx(ie,{value:N,onChange:H=>A(H.target.value),placeholder:"creative, writing"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Block event keywords"}),e.jsx(ie,{value:T,onChange:H=>F(H.target.value),placeholder:"psychiatrist, clinic, rest"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(W,{pending:L,pendingLabel:"Saving",onClick:async()=>{q(!0);try{await a({schedulingRules:Q?Yt:G,plannedDurationSeconds:l?Math.max(15,Number(u||30))*60:void 0})}finally{q(!1)}},children:r}),e.jsx(W,{variant:"secondary",onClick:async()=>{q(!0);try{o([]),f([]),m([]),p([]),v(""),k(""),M(""),y(""),A(""),F(""),await a({schedulingRules:null,plannedDurationSeconds:l?Math.max(15,Number(u||30))*60:void 0})}finally{q(!1)}},children:"Clear custom rules"})]})]})}function Vx({open:t,onOpenChange:s,tasks:i,onSave:n}){const a=c.useMemo(()=>i.filter(o=>o.status!=="done"),[i]),[r,l]=c.useState("");c.useEffect(()=>{if(t){if(a.length===0){l("");return}l(o=>o&&a.some(x=>x.id===o)?o:a[0].id)}},[a,t]);const d=a.find(o=>o.id===r)??null;return e.jsx(Ra,{open:t,onOpenChange:s,eyebrow:"Calendar",title:"Adjust task scheduling rules",description:"Choose a task, then tell Forge which work blocks, calendar conditions, or keywords should allow or block that work.",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsx(se,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"rounded-[18px] bg-[var(--primary)]/14 p-3 text-[var(--primary)]",children:e.jsx(vt,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Guided rule editing"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:"Use this when a task should only run in certain blocks such as Secondary Activity, or should stay blocked during clinic, rest, or other provider events."})]})]})}),a.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Task"}),e.jsx("select",{value:r,onChange:o=>l(o.target.value),className:"rounded-[22px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none",children:a.map(o=>e.jsx("option",{value:o.id,children:o.title},o.id))})]}),d?e.jsx(pr,{title:"Task rules",subtitle:"These rules are saved directly on the task. They drive blocked-now checks and future timebox recommendations.",initialRules:d.schedulingRules,initialPlannedDurationSeconds:d.plannedDurationSeconds,allowPlannedDuration:!0,saveLabel:"Save task rules",onSave:async({schedulingRules:o,plannedDurationSeconds:x})=>{await n({taskId:d.id,schedulingRules:o,plannedDurationSeconds:x===void 0?d.plannedDurationSeconds:x??null}),s(!1)}}):null]}):e.jsxs(se,{className:"rounded-[28px] border border-white/8 bg-white/[0.04]",children:[e.jsx("div",{className:"font-medium text-white",children:"No schedulable tasks yet"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:"Create or reopen a task first, then come back here to define work-block and calendar eligibility."}),e.jsx("div",{className:"mt-4",children:e.jsx(W,{variant:"secondary",onClick:()=>s(!1),children:"Close"})})]})]})})}const Zx=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],_n=[{kind:"main_activity",label:"Main activity",title:"Main Activity",startMinute:480,endMinute:720,color:"#f97316",blockingState:"blocked"},{kind:"secondary_activity",label:"Secondary activity",title:"Secondary Activity",startMinute:780,endMinute:1020,color:"#22c55e",blockingState:"allowed"},{kind:"third_activity",label:"Third activity",title:"Third Activity",startMinute:1020,endMinute:1260,color:"#38bdf8",blockingState:"allowed"},{kind:"rest",label:"Rest",title:"Rest",startMinute:1260,endMinute:1380,color:"#a855f7",blockingState:"blocked"},{kind:"holiday",label:"Holiday",title:"Holiday",startMinute:0,endMinute:1440,color:"#14b8a6",blockingState:"blocked"}];function Nl(t=new Date){const s=new Date(t),i=s.getUTCDay(),n=i===0?-6:1-i;return s.setUTCDate(s.getUTCDate()+n),s.setUTCHours(0,0,0,0),s}function aa(t,s){const i=new Date(t);return i.setUTCDate(i.getUTCDate()+s),i}function zi(t){return new Intl.DateTimeFormat("en",{weekday:"short",month:"short",day:"numeric"}).format(t)}function kl(t){const s=Math.floor(t/60).toString().padStart(2,"0"),i=String(t%60).padStart(2,"0");return`${s}:${i}`}function eg({open:t,onOpenChange:s,tasks:i,from:n,to:a,onCreateTimebox:r}){const l=c.useMemo(()=>i.filter(v=>v.status!=="done"),[i]),[d,o]=c.useState({taskId:"",selectedTimeboxId:""}),[x,f]=c.useState(null),[b,m]=c.useState(!1);c.useEffect(()=>{var I;if(!t)return;const v=((I=l[0])==null?void 0:I.id)??"";f(null),o({taskId:v,selectedTimeboxId:""})},[l,t]);const h=l.find(v=>v.id===d.taskId)??null,p=pe({queryKey:["forge-calendar-suggestions-dialog",d.taskId,n,a],queryFn:()=>$p({taskId:d.taskId,from:n,to:a,limit:8}),enabled:t&&d.taskId.length>0});c.useEffect(()=>{var I;if(!t)return;const v=((I=p.data)==null?void 0:I.timeboxes)??[];if(!v.length){o(k=>k.selectedTimeboxId?{...k,selectedTimeboxId:""}:k);return}o(k=>k.selectedTimeboxId&&v.some(S=>S.id===k.selectedTimeboxId)?k:{...k,selectedTimeboxId:v[0].id})},[t,p.data]);const w=c.useMemo(()=>[{id:"task",eyebrow:"Planning",title:"Choose the task you want to place into the week",description:"Forge will use the task's current planned duration and scheduling rules when it searches for valid slots.",render:(v,I)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(Y,{label:"Task",children:e.jsx("select",{value:v.taskId,onChange:k=>I({taskId:k.target.value,selectedTimeboxId:""}),className:"rounded-[22px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none",children:l.map(k=>e.jsx("option",{value:k.id,children:k.title},k.id))})}),h?e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:h.title}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(O,{className:"bg-white/[0.08] text-white/74",children:h.plannedDurationSeconds?`${Math.round(h.plannedDurationSeconds/60)} min target`:"No duration yet"}),e.jsx(O,{className:"bg-white/[0.08] text-white/74",children:h.schedulingRules?"Custom scheduling rules":"Inherits project rules"})]})]}):null]})},{id:"slot",eyebrow:"Suggestion",title:"Pick one of Forge's recommended timeboxes",description:"The slots below come from your connected calendar, work blocks, and the current task rules.",render:(v,I)=>{var S;const k=((S=p.data)==null?void 0:S.timeboxes)??[];return p.isLoading?e.jsx("div",{className:"text-sm text-white/62",children:"Looking for valid upcoming slots…"}):k.length?e.jsx("div",{className:"grid gap-3",children:k.map(M=>{const P=v.selectedTimeboxId===M.id;return e.jsxs("button",{type:"button",onClick:()=>I({selectedTimeboxId:M.id}),className:`rounded-[24px] 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]"}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium",children:M.title}),e.jsx(O,{className:"bg-white/[0.08] text-white/76",children:M.source})]}),e.jsxs("div",{className:"mt-2 text-sm leading-6 text-white/58",children:[zi(new Date(M.startsAt))," ·"," ",new Date(M.startsAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," ","-"," ",new Date(M.endsAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]},M.id)})}):e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"rounded-[24px] border border-amber-400/20 bg-amber-400/10 px-4 py-4 text-sm leading-6 text-amber-100/86",children:"Forge could not find a valid slot in the selected window. Adjust work blocks or task rules, then try again."}),e.jsx(W,{variant:"secondary",onClick:()=>void p.refetch(),children:"Refresh suggestions"})]})}}],[l,h,p]);return e.jsx(it,{open:t,onOpenChange:s,eyebrow:"Calendar",title:"Plan a task timebox",description:"Pick a task, review Forge's slot recommendations, and schedule it directly into the calendar.",value:d,onChange:o,steps:w,submitLabel:"Schedule timebox",pending:b,pendingLabel:"Scheduling",error:x,onSubmit:async()=>{var I;const v=(((I=p.data)==null?void 0:I.timeboxes)??[]).find(k=>k.id===d.selectedTimeboxId);if(!v){f("Pick one suggested slot before scheduling the timebox.");return}try{m(!0),f(null),await r({taskId:v.taskId,projectId:v.projectId,title:v.title,startsAt:v.startsAt,endsAt:v.endsAt,source:"suggested"}),s(!1)}catch(k){f(k instanceof Error?k.message:"Forge could not create the selected timebox.")}finally{m(!1)}}})}function Sl(t){if(t)return{title:t.title,kind:t.kind,color:t.color,timezone:t.timezone,weekDays:t.weekDays,startMinute:t.startMinute,endMinute:t.endMinute,startsOn:t.startsOn,endsOn:t.endsOn,blockingState:t.blockingState};const s=_n[0];return{title:s.title,kind:s.kind,color:s.color,timezone:typeof Intl<"u"&&Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC",weekDays:[1,2,3,4,5],startMinute:s.startMinute,endMinute:s.endMinute,startsOn:null,endsOn:null,blockingState:s.blockingState}}function Cl(t){return t??""}function tg({open:t,onOpenChange:s,onSubmit:i,pending:n=!1,template:a=null}){const[r,l]=c.useState(()=>Sl(a)),[d,o]=c.useState(null),x=a!==null;c.useEffect(()=>{t&&(o(null),l(Sl(a)))},[t,a]);const f=c.useMemo(()=>[{id:"preset",eyebrow:"Preset",title:"Start from a recurring block that already matches the rhythm",description:"Use a preset to seed the schedule, then tune the dates and recurrence in the next step.",render:(b,m)=>e.jsx("div",{className:"grid gap-4",children:e.jsx(Y,{label:"Block type",children:e.jsx(tt,{value:b.kind,columns:3,onChange:h=>{const p=_n.find(w=>w.kind===h);if(p){const w=p.kind==="holiday"?[0,1,2,3,4,5,6]:[1,2,3,4,5];m({kind:p.kind,title:p.title,color:p.color,weekDays:w,startMinute:p.startMinute,endMinute:p.endMinute,blockingState:p.blockingState});return}m({kind:"custom",title:"Custom block",color:"#7dd3fc"})},options:[..._n.map(h=>({value:h.kind,label:h.title,description:`${kl(h.startMinute)}-${kl(h.endMinute)}`})),{value:"custom",label:"Custom",description:"Build a different recurring window."}]})})})},{id:"shape",eyebrow:"Schedule",title:"Define when this recurring block should exist",description:"Weekdays and times describe the recurring pattern. Optional start and end dates bound when the template is active.",render:(b,m)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(Y,{label:"Block title",children:e.jsx(ie,{value:b.title,onChange:h=>m({title:h.target.value}),placeholder:"Main Activity"})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Y,{label:"Start minute",children:e.jsx(ie,{type:"number",min:0,max:1440,step:15,value:b.startMinute,onChange:h=>m({startMinute:Number(h.target.value)||0})})}),e.jsx(Y,{label:"End minute",children:e.jsx(ie,{type:"number",min:0,max:1440,step:15,value:b.endMinute,onChange:h=>m({endMinute:Number(h.target.value)||0})})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Y,{label:"Start date",children:e.jsx(ie,{type:"date",value:Cl(b.startsOn),onChange:h=>m({startsOn:h.target.value.trim()||null})})}),e.jsx(Y,{label:"End date",children:e.jsx(ie,{type:"date",value:Cl(b.endsOn),onChange:h=>m({endsOn:h.target.value.trim()||null})})})]}),e.jsx("div",{className:"text-sm leading-6 text-white/54",children:"Leave the end date empty to keep repeating indefinitely. Holiday blocks work well with all seven weekdays and `0-1440`."}),e.jsx(Y,{label:"Weekdays",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:Zx.map((h,p)=>{const w=b.weekDays.includes(p);return e.jsx("button",{type:"button",onClick:()=>m({weekDays:w?b.weekDays.filter(v=>v!==p):[...b.weekDays,p].sort((v,I)=>v-I)}),className:`rounded-full px-3 py-2 text-sm transition ${w?"bg-[var(--primary)]/18 text-[var(--primary)] shadow-[inset_0_0_0_1px_rgba(192,193,255,0.24)]":"bg-white/[0.05] text-white/62 hover:bg-white/[0.08]"}`,children:h},h)})})})]})},{id:"policy",eyebrow:"Policy",title:"Tell Forge whether this block allows or blocks work",description:"Use blocked mode for time that should normally stop optional work. Use allowed mode for protected focus windows.",render:(b,m)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(Y,{label:"Work effect",children:e.jsx(tt,{value:b.blockingState,onChange:h=>m({blockingState:h}),options:[{value:"blocked",label:"Blocks work",description:"Starting blocked tasks should require an explicit override."},{value:"allowed",label:"Allows work",description:"Use this for protected windows where the right tasks should fit."}]})}),e.jsx(Y,{label:"Color",children:e.jsxs("div",{className:"flex items-center gap-3 rounded-[22px] border border-white/8 bg-white/6 px-4 py-3",children:[e.jsx("input",{className:"h-10 w-12 rounded-lg border border-white/10 bg-transparent",type:"color",value:b.color,onChange:h=>m({color:h.target.value})}),e.jsx(ie,{className:"border-none bg-transparent px-0 py-0",value:b.color,onChange:h=>m({color:h.target.value})})]})})]})}],[]);return e.jsx(it,{open:t,onOpenChange:s,eyebrow:"Calendar",title:x?"Edit work block":"Create a work block",description:x?"Adjust the recurring pattern, date bounds, or work policy for this block.":"Build recurring half-day, holiday, or custom blocks so Forge can understand when work should be protected or blocked.",value:r,onChange:l,steps:f,submitLabel:x?"Save changes":"Save work block",pending:n,pendingLabel:x?"Saving changes":"Saving",error:d,onSubmit:async()=>{if(!r.title.trim()){o("Give the block a title so it stays readable in the calendar.");return}if(r.weekDays.length===0){o("Select at least one weekday for the recurring block.");return}if(r.endMinute<=r.startMinute){o("The end minute needs to be later than the start minute.");return}if(r.startsOn&&r.endsOn&&r.endsOn<r.startsOn){o("The end date needs to be on or after the start date.");return}try{o(null),await i({...r,title:r.title.trim()}),s(!1)}catch(b){o(b instanceof Error?b.message:"Forge could not save this work block.")}}})}function Kt({className:t}){return e.jsx("div",{className:re("surface-pulse rounded-2xl bg-white/[0.05]",t)})}function It({header:t=!0,sideRail:s=!0,className:i,eyebrow:n,title:a,description:r,columns:l=2,blocks:d=4}){const o=Array.from({length:Math.max(2,d)});return e.jsxs("div",{className:re("grid gap-5",i),"aria-hidden":"true",children:[t?e.jsxs(se,{className:"grid gap-4",children:[e.jsx(Kt,{className:re("h-3",n?"w-40":"w-32")}),e.jsx(Kt,{className:re("h-12",a?"max-w-2xl":"max-w-3xl")}),e.jsx(Kt,{className:re("h-5",r?"max-w-3xl":"max-w-2xl")})]}):null,e.jsxs("section",{className:re("grid gap-5",s?"xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]":""),children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(se,{className:"grid gap-4",children:[e.jsx(Kt,{className:"h-3 w-28"}),e.jsx(Kt,{className:"h-28 w-full"})]}),e.jsxs(se,{className:"grid gap-4",children:[e.jsx(Kt,{className:"h-3 w-40"}),e.jsx("div",{className:re("grid gap-3",l>1?"md:grid-cols-2":""),children:o.map((x,f)=>e.jsx(Kt,{className:"h-28 w-full"},f))})]})]}),s?e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(se,{className:"grid gap-4",children:[e.jsx(Kt,{className:"h-3 w-24"}),e.jsx(Kt,{className:"h-20 w-full"})]}),e.jsxs(se,{className:"grid gap-4",children:[e.jsx(Kt,{className:"h-3 w-36"}),e.jsx(Kt,{className:"h-16 w-full"}),e.jsx(Kt,{className:"h-16 w-full"})]})]}):null]})]})}function Wd({open:t,title:s,subtitle:i,items:n,position:a,onClose:r}){return c.useEffect(()=>{if(!t)return;let l=!1;const d=window.setTimeout(()=>{l=!0},0),o=f=>{f.key==="Escape"&&r()},x=()=>{l&&r()};return window.addEventListener("keydown",o),window.addEventListener("pointerdown",x),()=>{window.clearTimeout(d),window.removeEventListener("keydown",o),window.removeEventListener("pointerdown",x)}},[r,t]),!t||!a||typeof document>"u"?null:Bo.createPortal(e.jsx("div",{className:"fixed inset-0 z-[70]","aria-hidden":"true",children:e.jsxs("div",{className:"fixed z-[71] w-[min(22rem,calc(100vw-1.5rem))] rounded-[26px] border border-white/10 bg-[rgba(10,15,27,0.97)] p-2 shadow-[0_28px_80px_rgba(4,8,18,0.4)] backdrop-blur-xl",style:{left:Math.min(a.x,window.innerWidth-24-352),top:Math.min(a.y,window.innerHeight-24-320)},onPointerDown:l=>l.stopPropagation(),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-[20px] bg-white/[0.03] px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:s}),i?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/50",children:i}):null]}),e.jsx("button",{type:"button",className:"rounded-full bg-white/[0.04] p-2 text-white/55 transition hover:bg-white/[0.08] hover:text-white",onClick:r,children:e.jsx(mt,{className:"size-4"})})]}),e.jsx("div",{className:"mt-2 grid gap-1",children:n.map(l=>{const d=l.icon;return e.jsxs("button",{type:"button",disabled:l.disabled,onClick:()=>{l.disabled||(l.onSelect(),r())},className:re("flex w-full items-start gap-3 rounded-[20px] px-4 py-3 text-left transition",l.disabled?"cursor-not-allowed bg-white/[0.02] text-white/28":l.tone==="danger"?"bg-rose-400/[0.05] text-rose-100 hover:bg-rose-400/[0.12]":"bg-white/[0.03] text-white/76 hover:bg-white/[0.08] hover:text-white"),children:[d?e.jsx("span",{className:re("mt-0.5 rounded-[14px] p-2",l.disabled?"bg-white/[0.03] text-white/28":l.tone==="danger"?"bg-rose-400/[0.12] text-rose-100":"bg-[var(--primary)]/12 text-[var(--primary)]"),children:e.jsx(d,{className:"size-4"})}):null,e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium",children:l.label}),l.description?e.jsx("span",{className:"mt-1 block text-xs leading-5 text-white/48",children:l.description}):null]})]},l.id)})})]})}),document.body)}const Gd="forge.calendar-display-preferences",Il=["#7dd3fc","#34d399","#f59e0b","#fb7185","#60a5fa","#a3e635","#f97316","#22c55e"],hn={useCalendarColors:!0,calendarColors:{}};function Hd(t){return typeof t=="string"&&/^#[0-9a-fA-F]{6}$/.test(t)}function Xd(){if(typeof window>"u")return hn;const t=window.localStorage.getItem(Gd);if(!t)return hn;try{const s=JSON.parse(t);return{useCalendarColors:s.useCalendarColors??!0,calendarColors:s.calendarColors&&typeof s.calendarColors=="object"?Object.fromEntries(Object.entries(s.calendarColors).filter(i=>Hd(i[1]))):{}}}catch{return hn}}function sg(t){typeof window>"u"||window.localStorage.setItem(Gd,JSON.stringify(t))}function Jd(t){return Il[t%Il.length]??"#7dd3fc"}function Yd(t,s){return Object.fromEntries(t.map((i,n)=>[i.id,Hd(s[i.id])?s[i.id]:Jd(n)]))}function Tl(t){let s=0;for(let i=0;i<t.length;i+=1)s=s*31+t.charCodeAt(i)>>>0;return Jd(s)}const na=Qo(t=>({entry:null,setEntry:s=>t({entry:s}),clear:()=>t({entry:null}),completePaste:()=>t(s=>{var i;return{entry:((i=s.entry)==null?void 0:i.mode)==="cut"?null:s.entry}})})),ig={goal:"goal",project:"project",task:"task",habit:"habit"};function ag(t){const s=new Date(t);s.setUTCHours(9,0,0,0);const i=new Date(s.getTime()+3600*1e3);return{startAt:s.toISOString(),endAt:i.toISOString(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",availability:"busy"}}function Pl(t){const s=typeof t.location=="string"?t.location:"",i=t.place??{label:s,address:"",timezone:"",latitude:null,longitude:null,source:"",externalPlaceId:""};return{...t,place:{label:i.label||s,address:i.address??"",timezone:i.timezone??"",latitude:i.latitude??null,longitude:i.longitude??null,source:i.source??"",externalPlaceId:i.externalPlaceId??""}}}function Ml(t,s){const i=new Date(t.startAt),a=new Date(t.endAt).getTime()-i.getTime(),r=new Date(s);r.setUTCHours(i.getUTCHours(),i.getUTCMinutes(),0,0);const l=new Date(r.getTime()+a);return{startAt:r.toISOString(),endAt:l.toISOString()}}function El(t){return{type:"calendar_event",eventId:t.id,title:t.title,description:t.description,location:t.location,startAt:t.startAt,endAt:t.endAt,timezone:t.timezone,availability:t.availability,preferredCalendarId:t.calendarId,categories:t.categories,links:t.links.map(s=>({entityType:s.entityType,entityId:s.entityId,relationshipType:s.relationshipType}))}}function ng(t){switch(t){case"apple":return"Apple";case"google":return"Google";case"caldav":return"CalDAV";case"native":return"Forge";default:return"Derived"}}function rg(t,s){var i;if(t.calendarId){const n=(i=s.get(t.calendarId))==null?void 0:i.trim();if(n)return n}return t.originType==="native"?"Forge only":ng(t.originType)}function Al(t){switch(t){case"main_activity":return"Main activity";case"secondary_activity":return"Secondary activity";case"third_activity":return"Third activity";case"rest":return"Rest";case"holiday":return"Holiday";default:return"Custom"}}function Ll(t){return t.startsOn&&t.endsOn?`${t.startsOn} to ${t.endsOn}`:t.startsOn?`From ${t.startsOn}`:t.endsOn?`Until ${t.endsOn}`:"Repeats with no end date"}function lg(){var Pt,Mt,Et;const t=ht(),s=Ye(),i=Array.isArray(s.selectedUserIds)?s.selectedUserIds:[],n=Nt(i),a=We(),r=na(te=>te.entry),l=na(te=>te.setEntry),d=na(te=>te.clear),o=na(te=>te.completePaste),[x,f]=c.useState(()=>Nl()),[b,m]=c.useState(null),[h,p]=c.useState(null),[w,v]=c.useState(!1),[I,k]=c.useState(null),[S,M]=c.useState(!1),[P,y]=c.useState(!1),[N,A]=c.useState(!1),[T,F]=c.useState(null),[u,j]=c.useState(null),L=c.useMemo(()=>Xd(),[]),[q,G]=c.useState(null),[Q,ne]=c.useState(null),[H,_]=c.useState(null),U=c.useMemo(()=>{const te=x.toISOString(),we=aa(x,7).toISOString();return{from:te,to:we}},[x]),R=pe({queryKey:["forge-calendar-overview",U.from,U.to,...i],queryFn:()=>Qa({...U,userIds:i})}),C=["forge-calendar-overview",U.from,U.to,...i],J=te=>{if(te.deletedAt)return!1;const we=new Date(te.startAt).getTime();return we>=new Date(U.from).getTime()&&we<new Date(U.to).getTime()},ee=te=>{a.setQueryData(C,we=>we&&te(we))},le=async()=>{await Promise.all([a.invalidateQueries({queryKey:["forge-calendar-overview"]}),a.invalidateQueries({queryKey:["forge-snapshot"]}),a.invalidateQueries({queryKey:["task-context"]}),a.invalidateQueries({queryKey:["project-board"]})])},oe=ge({mutationFn:te=>Ip({...te,userId:te.userId??n}),onSuccess:le}),ue=ge({mutationFn:({templateId:te,patch:we})=>Tp(te,we),onSuccess:le}),me=ge({mutationFn:Pp,onSuccess:le}),$=ge({mutationFn:te=>Lp({...te,userId:n}),onSuccess:le}),ce=ge({mutationFn:({timeboxId:te,startsAt:we,endsAt:Me})=>Dp(te,{startsAt:we,endsAt:Me}),onSuccess:le}),E=ge({mutationFn:te=>Mp({...te,userId:te.userId??n}),onMutate:async te=>{var xe,Ie,Ee,et,Fe,ut,Te;_({tone:"saving",message:"Saving event changes in the background…"}),await a.cancelQueries({queryKey:C});const we=a.getQueryData(C),Me=(we==null?void 0:we.calendar.calendars.find(rt=>rt.canWrite&&rt.selectedForSync))??(we==null?void 0:we.calendar.calendars.find(rt=>rt.canWrite))??null,Ve=new Date().toISOString(),Se={id:`calendar_event_optimistic_${Date.now()}`,connectionId:(Me==null?void 0:Me.connectionId)??null,calendarId:te.preferredCalendarId===void 0?(Me==null?void 0:Me.id)??null:te.preferredCalendarId,remoteId:null,ownership:"forge",originType:"native",status:"confirmed",title:te.title,description:te.description??"",location:te.location??"",place:{label:((xe=te.place)==null?void 0:xe.label)??te.location??"",address:((Ie=te.place)==null?void 0:Ie.address)??"",timezone:((Ee=te.place)==null?void 0:Ee.timezone)??te.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",latitude:((et=te.place)==null?void 0:et.latitude)??null,longitude:((Fe=te.place)==null?void 0:Fe.longitude)??null,source:((ut=te.place)==null?void 0:ut.source)??"forge",externalPlaceId:((Te=te.place)==null?void 0:Te.externalPlaceId)??""},startAt:te.startAt,endAt:te.endAt,timezone:te.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",isAllDay:te.isAllDay??!1,availability:te.availability??"busy",eventType:te.eventType??"general",categories:te.categories??[],sourceMappings:[],links:(te.links??[]).map((rt,kt)=>({id:`calendar_event_link_optimistic_${Date.now()}_${kt}`,entityType:rt.entityType,entityId:rt.entityId,relationshipType:rt.relationshipType??"context",createdAt:Ve,updatedAt:Ve})),remoteUpdatedAt:null,deletedAt:null,createdAt:Ve,updatedAt:Ve};return we&&J(Se)&&ee(rt=>({...rt,calendar:{...rt.calendar,events:[Se,...rt.calendar.events]}})),{previous:we,optimisticEventId:Se.id}},onError:(te,we,Me)=>{Me!=null&&Me.previous&&a.setQueryData(C,Me.previous),_({tone:"error",message:te instanceof Error?te.message:"Forge could not sync that event change."})},onSuccess:({event:te},we,Me)=>{_(null),ee(Ve=>({...Ve,calendar:{...Ve.calendar,events:(J(te)?[te,...Ve.calendar.events.filter(Se=>Se.id!==(Me==null?void 0:Me.optimisticEventId))]:Ve.calendar.events.filter(Se=>Se.id!==(Me==null?void 0:Me.optimisticEventId))).filter((Se,xe,Ie)=>Ie.findIndex(Ee=>Ee.id===Se.id)===xe)}}))},onSettled:le}),z=ge({mutationFn:({eventId:te,patch:we})=>Ep(te,we),onMutate:async({eventId:te,patch:we})=>{_({tone:"saving",message:"Saving event changes in the background…"}),await a.cancelQueries({queryKey:C});const Me=a.getQueryData(C);return Me&&ee(Ve=>{var Ee;const Se=Ve.calendar.events.find(et=>et.id===te);if(!Se)return Ve;const xe=Pl(Se),Ie={...xe,...we,place:we.place?{...xe.place,...we.place}:xe.place,calendarId:we.preferredCalendarId===void 0?xe.calendarId:we.preferredCalendarId,links:((Ee=we.links)==null?void 0:Ee.map((et,Fe)=>{var ut,Te;return{id:((ut=xe.links[Fe])==null?void 0:ut.id)??`calendar_event_link_optimistic_${Date.now()}_${Fe}`,entityType:et.entityType,entityId:et.entityId,relationshipType:et.relationshipType??"context",createdAt:((Te=xe.links[Fe])==null?void 0:Te.createdAt)??xe.createdAt,updatedAt:new Date().toISOString()}}))??xe.links,updatedAt:new Date().toISOString()};return{...Ve,calendar:{...Ve.calendar,events:Ve.calendar.events.map(et=>et.id===te?Ie:et).filter(J)}}}),{previous:Me}},onError:(te,we,Me)=>{Me!=null&&Me.previous&&a.setQueryData(C,Me.previous),_({tone:"error",message:te instanceof Error?te.message:"Forge could not sync that event change."})},onSuccess:({event:te})=>{_(null),ee(we=>({...we,calendar:{...we.calendar,events:we.calendar.events.map(Me=>Me.id===te.id?te:Me).filter(J)}}))},onSettled:le}),K=ge({mutationFn:Ap,onMutate:async te=>{_({tone:"saving",message:"Removing the event in the background…"}),await a.cancelQueries({queryKey:C});const we=a.getQueryData(C);return we&&ee(Me=>({...Me,calendar:{...Me.calendar,events:Me.calendar.events.filter(Ve=>Ve.id!==te)}})),{previous:we}},onError:(te,we,Me)=>{Me!=null&&Me.previous&&a.setQueryData(C,Me.previous),_({tone:"error",message:te instanceof Error?te.message:"Forge could not delete that event."})},onSuccess:()=>{_(null)},onSettled:le}),je=(Pt=R.data)==null?void 0:Pt.calendar,V=c.useMemo(()=>Array.from({length:7},(te,we)=>aa(x,we)),[x]),D=c.useMemo(()=>je?{...je,events:je.events.map(Pl)}:{generatedAt:"",providers:[],connections:[],calendars:[],events:[],workBlockTemplates:[],workBlockInstances:[],timeboxes:[]},[je]),X=c.useMemo(()=>new Map(D.calendars.map(te=>[te.id,te.title])),[D.calendars]),he=c.useMemo(()=>Yd(D.calendars,L.calendarColors),[L.calendarColors,D.calendars]),ye=E.isPending||z.isPending||K.isPending,ze=D.timeboxes.filter(te=>te.status==="planned"),fe=D.calendars.filter(te=>te.canWrite),Pe=(te,we)=>we?`${te} · ${we}`:te,Ge=[...s.snapshot.goals.map(te=>({entityType:"goal",entityId:te.id,label:te.title,subtitle:Pe("Goal",Qt(te.user))})),...s.snapshot.projects.map(te=>({entityType:"project",entityId:te.id,label:te.title,subtitle:Pe("Project",Qt(te.user))})),...s.snapshot.tasks.map(te=>({entityType:"task",entityId:te.id,label:te.title,subtitle:Pe("Task",Qt(te.user))})),...s.snapshot.strategies.map(te=>({entityType:"strategy",entityId:te.id,label:te.title,subtitle:Pe("Strategy",Qt(te.user))})),...s.snapshot.habits.map(te=>({entityType:"habit",entityId:te.id,label:te.title,subtitle:Pe("Habit",Qt(te.user))}))],Z=c.useMemo(()=>new Map(Ge.map(te=>[`${te.entityType}:${te.entityId}`,te.label])),[Ge]),He=D.connections.length===0?"No providers connected":`${D.connections.filter(te=>te.status==="connected").length}/${D.connections.length} healthy`,Ue=(r==null?void 0:r.items.filter(te=>te.type==="calendar_event"))??[],Qe=te=>{F(null),G(ag(te)),A(!0)},ct=async(te,we)=>{const Me=Ml({startAt:te.startAt,endAt:te.endAt},we);await z.mutateAsync({eventId:te.id,patch:Me})},zt=async te=>{if(Ue.length!==0){for(const we of Ue){const Me=Ml(we,te);(r==null?void 0:r.mode)==="cut"?await z.mutateAsync({eventId:we.eventId,patch:Me}):await E.mutateAsync({title:we.title,description:we.description,location:we.location,startAt:Me.startAt,endAt:Me.endAt,timezone:we.timezone,availability:we.availability,preferredCalendarId:we.preferredCalendarId,categories:we.categories,links:we.links})}o()}},qt=c.useMemo(()=>{if(!Q)return[];if(Q.kind==="day"){const we=V.find(Me=>Me.toISOString().slice(0,10)===Q.dayKey);return we?[{id:"create-event",label:"Create event",description:"Open the event guide with this day already selected.",icon:ys,onSelect:()=>Qe(we)},{id:"create-work-block",label:"Create work block",description:"Open the guided work-block flow while you are looking at this day.",icon:Bi,onSelect:()=>{k(null),v(!0)}},{id:"paste",label:(r==null?void 0:r.mode)==="cut"?"Paste moved event":"Paste copied event",description:Ue.length>0?`${Ue.length} calendar item${Ue.length===1?"":"s"} ready to paste here.`:r?"The current clipboard entry does not contain calendar events.":"Copy or cut an event first, then paste it into this day.",icon:vm,disabled:Ue.length===0,onSelect:()=>void zt(we)}]:[]}if(Q.kind==="work-block"){const we=D.workBlockTemplates.find(Me=>Me.id===Q.templateId);return we?[{id:"edit-work-block",label:"Edit",description:"Adjust the recurring pattern, date bounds, or work policy.",icon:ys,onSelect:()=>{k(we),v(!0)}},{id:"delete-work-block",label:"Delete",description:"Remove this recurring work block from Forge.",icon:bt,tone:"danger",onSelect:()=>{(I==null?void 0:I.id)===we.id&&k(null),me.mutateAsync(we.id)}}]:[]}const te=D.events.find(we=>we.id===Q.eventId);return te?[{id:"rename",label:"Quick rename",description:"Change the event title without opening the full event flow.",icon:ys,onSelect:()=>j(te)},{id:"copy",label:"Copy",description:"Put this event on the Forge clipboard so you can paste it into another day.",icon:Wo,onSelect:()=>l({id:`clipboard_${te.id}_${Date.now()}`,mode:"copy",source:"calendar",label:te.title,createdAt:new Date().toISOString(),items:[El(te)]})},{id:"cut",label:"Cut",description:"Move this event by pasting it into another day.",icon:ym,onSelect:()=>l({id:`clipboard_cut_${te.id}_${Date.now()}`,mode:"cut",source:"calendar",label:te.title,createdAt:new Date().toISOString(),items:[El(te)]})},{id:"delete",label:"Delete",description:"Remove the event from Forge and delete any connected remote projection.",icon:bt,tone:"danger",onSelect:()=>{(r==null?void 0:r.mode)==="cut"&&Ue.some(we=>we.eventId===te.id)&&d(),K.mutateAsync(te.id)}}]:[]},[d,Ue,r,V,K,me,Q,D.events,D.workBlockTemplates,I,l]);return R.isLoading?e.jsx(It,{}):R.isError||!R.data?e.jsx(Oe,{eyebrow:"Calendar",error:R.error??new Error("Calendar data is unavailable"),onRetry:()=>void R.refetch()}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{entityKind:"project",titleText:"Calendar",title:"Calendar",description:"See the real week first, then open guided flows for work blocks, task rules, timeboxing, and provider setup.",badge:`${D.connections.length} connection${D.connections.length===1?"":"s"}`}),e.jsxs(se,{className:"grid gap-4 rounded-[32px] border border-white/8 bg-[linear-gradient(180deg,rgba(17,28,39,0.985),rgba(10,17,29,0.985))]",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Week view"}),e.jsx("p",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/60",children:"The calendar is the priority surface here. Connected provider events, recurring work blocks, and owned task timeboxes all stay visible together."}),H?e.jsx("div",{className:`mt-3 inline-flex max-w-full items-center gap-2 rounded-full px-3 py-1.5 text-xs ${H.tone==="error"?"border border-rose-400/20 bg-rose-400/10 text-rose-200":"border border-[var(--primary)]/18 bg-[var(--primary)]/12 text-[var(--primary)]"}`,children:H.message}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(O,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[e.jsx(us,{className:"mr-1 size-3.5"}),"Week of ",zi(x)]}),ye?e.jsxs(O,{className:"bg-white/[0.08] text-white/78",children:[e.jsx(ps,{className:"mr-1 size-3.5 animate-spin"}),"Syncing changes"]}):null,r?e.jsxs(O,{className:"bg-white/[0.08] text-white/74",children:[r.mode==="cut"?"Cut":"Copied"," · ",r.label]}):null,e.jsx(W,{variant:"secondary",onClick:()=>f(aa(x,-7)),children:"Previous"}),e.jsx(W,{variant:"secondary",onClick:()=>f(Nl()),children:"This week"}),e.jsx(W,{variant:"secondary",onClick:()=>f(aa(x,7)),children:"Next"})]})]}),e.jsx("div",{className:"grid gap-3 [grid-template-columns:repeat(auto-fit,minmax(min(100%,17rem),1fr))] 2xl:[grid-template-columns:repeat(7,minmax(0,1fr))]",children:V.map(te=>{const we=te.toISOString().slice(0,10),Me=D.events.filter(xe=>xe.startAt.slice(0,10)===we&&!xe.deletedAt),Ve=D.workBlockInstances.filter(xe=>xe.dateKey===we),Se=D.timeboxes.filter(xe=>xe.startsAt.slice(0,10)===we);return e.jsxs("div",{"data-calendar-day":we,onClick:xe=>{xe.target.closest("[data-calendar-item='true']")||ne({kind:"day",dayKey:we,position:{x:xe.clientX,y:xe.clientY}})},onDragOver:xe=>{xe.preventDefault()},onDrop:xe=>{xe.preventDefault();const Ie=xe.dataTransfer.getData("text/forge-event-id")||h;if(Ie){const Bt=D.events.find(ds=>ds.id===Ie);Bt&&ct(Bt,te),p(null);return}const Ee=xe.dataTransfer.getData("text/forge-timebox-id")||b;if(!Ee)return;const et=D.timeboxes.find(Bt=>Bt.id===Ee);if(!et)return;const Fe=new Date(et.startsAt),Te=new Date(et.endsAt).getTime()-Fe.getTime(),rt=new Date(te);rt.setUTCHours(Fe.getUTCHours(),Fe.getUTCMinutes(),0,0);const kt=new Date(rt.getTime()+Te);ce.mutateAsync({timeboxId:Ee,startsAt:rt.toISOString(),endsAt:kt.toISOString()}),m(null)},className:"min-w-0 overflow-hidden rounded-[24px] border border-white/6 bg-white/[0.03] p-3 transition hover:border-white/12 hover:bg-white/[0.045]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[18px] bg-[rgba(10,16,30,0.96)] px-3 py-2 text-sm font-medium text-white",children:[e.jsx("span",{className:"min-w-0 truncate",children:zi(te)}),e.jsx("button",{type:"button","aria-label":`Open actions for ${zi(te)}`,className:"rounded-full bg-white/[0.06] p-2 text-white/58 transition hover:bg-white/[0.1] hover:text-white",onClick:xe=>{xe.stopPropagation(),ne({kind:"day",dayKey:we,position:{x:xe.clientX,y:xe.clientY}})},children:e.jsx(ja,{className:"size-4"})})]}),e.jsxs("div",{className:"mt-3 grid min-w-0 gap-2",children:[Ve.map(xe=>e.jsxs("div",{"data-calendar-item":"true",className:"min-w-0 overflow-hidden rounded-[18px] px-3 py-2 text-sm text-white",style:{backgroundColor:`${xe.color}22`,border:`1px solid ${xe.color}55`},children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"min-w-0 [overflow-wrap:anywhere] font-medium",children:xe.title}),e.jsxs("div",{className:"mt-1 flex min-w-0 flex-wrap items-center gap-1.5",children:[e.jsx(O,{size:"sm",className:"shrink-0 bg-white/[0.08] text-white/78",children:xe.blockingState}),e.jsx(O,{size:"sm",className:"shrink-0 bg-white/[0.08] text-white/78",children:Al(xe.kind)})]})]}),e.jsx("button",{type:"button","aria-label":`Open actions for ${xe.title}`,className:"rounded-full bg-white/[0.05] p-1.5 text-white/56 transition hover:bg-white/[0.1] hover:text-white",onClick:Ie=>{Ie.stopPropagation(),ne({kind:"work-block",templateId:xe.templateId,position:{x:Ie.clientX,y:Ie.clientY}})},children:e.jsx(ja,{className:"size-4"})})]}),e.jsxs("div",{className:"mt-1 text-white/60",children:[new Date(xe.startAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," ","-"," ",new Date(xe.endAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),e.jsx("div",{className:"mt-2 text-xs text-white/48",children:Ll(D.workBlockTemplates.find(Ie=>Ie.id===xe.templateId)??{id:xe.templateId,title:xe.title,kind:xe.kind,color:xe.color,startsOn:null,endsOn:null,blockingState:xe.blockingState,createdAt:xe.createdAt,updatedAt:xe.updatedAt})})]},xe.id)),Me.map(xe=>e.jsxs("div",{"data-calendar-item":"true",draggable:!0,onDragStart:Ie=>{p(xe.id),Ie.dataTransfer.setData("text/forge-event-id",xe.id)},onClick:Ie=>{Ie.stopPropagation(),F(xe),G(null),A(!0)},className:`min-w-0 cursor-move overflow-hidden rounded-[18px] px-3 py-2 text-left text-sm text-white/82 transition ${L.useCalendarColors?"hover:brightness-110":"border border-white/10 bg-white/[0.05] hover:border-white/18 hover:bg-white/[0.08] hover:shadow-[0_12px_32px_rgba(4,9,20,0.22)]"}`,style:L.useCalendarColors?{backgroundColor:`${(xe.calendarId?he[xe.calendarId]:null)??Tl(`origin:${xe.originType}`)}1f`,border:`1px solid ${(xe.calendarId?he[xe.calendarId]:null)??Tl(`origin:${xe.originType}`)}55`}:void 0,children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"line-clamp-2 [overflow-wrap:anywhere] font-medium",children:xe.title}),e.jsxs("div",{className:"mt-1 text-white/55",children:[new Date(xe.startAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," ","-"," ",new Date(xe.endAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsx("button",{type:"button","aria-label":`Open quick actions for ${xe.title}`,className:"rounded-full bg-white/[0.05] p-1.5 text-white/56 transition hover:bg-white/[0.1] hover:text-white",onClick:Ie=>{Ie.stopPropagation(),ne({kind:"event",eventId:xe.id,position:{x:Ie.clientX,y:Ie.clientY}})},children:e.jsx(ja,{className:"size-4"})})})]}),e.jsxs("div",{className:"mt-2 flex min-w-0 flex-wrap items-center gap-1.5",children:[e.jsx(O,{size:"sm",className:"max-w-full bg-white/[0.08] px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] text-white/70",children:rg(xe,X)}),xe.calendarId&&L.useCalendarColors?e.jsx("span",{"aria-hidden":"true",className:"size-2.5 shrink-0 rounded-full",style:{backgroundColor:he[xe.calendarId]}}):null]}),xe.place.address||xe.place.timezone?e.jsxs("div",{className:"mt-2 text-xs leading-5 text-white/50",children:[xe.place.address||xe.location,xe.place.address&&xe.place.timezone?" · ":"",xe.place.timezone]}):null,xe.links.length>0?e.jsx("div",{className:"mt-2 flex min-w-0 flex-wrap gap-1.5",children:xe.links.slice(0,3).map(Ie=>{const Ee=ig[Ie.entityType];return Ee?e.jsx(ke,{kind:Ee,label:Z.get(`${Ie.entityType}:${Ie.entityId}`)??Ie.entityType,compact:!0,gradient:!1},Ie.id):e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:Ie.entityType},Ie.id)})}):null]},xe.id)),Se.map(xe=>e.jsxs("div",{"data-calendar-item":"true",draggable:!0,onDragStart:Ie=>{m(xe.id),Ie.dataTransfer.setData("text/forge-timebox-id",xe.id)},className:"min-w-0 overflow-hidden cursor-move rounded-[18px] bg-[var(--primary)]/14 px-3 py-2 text-sm text-[var(--primary)] shadow-[inset_0_0_0_1px_rgba(192,193,255,0.18)]",children:[e.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[e.jsx("div",{className:"min-w-0 [overflow-wrap:anywhere] font-medium",children:xe.title}),e.jsx(O,{size:"sm",className:"shrink-0 bg-white/[0.08] text-white/78",children:xe.status})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-white/70",children:[e.jsx(yi,{className:"size-3.5"}),new Date(xe.startsAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," ","-"," ",new Date(xe.endsAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]},xe.id)),Ve.length===0&&Me.length===0&&Se.length===0?e.jsx("div",{className:"min-h-[10rem] rounded-[18px] border border-dashed border-white/8 px-3 py-4 text-sm leading-8 text-white/42",children:"Nothing scheduled here yet. Click inside this day to create, block, or paste."}):null]})]},we)})})]}),e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs(se,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-[18px] bg-[var(--primary)]/14 p-3 text-[var(--primary)]",children:e.jsx(ys,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Create event"}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:"Add a native Forge event with linked context."})]})]}),e.jsx("p",{className:"mt-4 text-sm leading-6 text-white/62",children:"Create a real calendar event even with no provider connected, then project it remotely whenever you choose."}),e.jsx("div",{className:"mt-4",children:e.jsxs(W,{onClick:()=>{k(null),F(null),G(null),A(!0)},children:[e.jsx(ys,{className:"size-4"}),"Open event guide"]})})]}),e.jsxs(se,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-[18px] bg-[var(--primary)]/14 p-3 text-[var(--primary)]",children:e.jsx(Bi,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Create work block"}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:"Block main activity or protect creative windows."})]})]}),e.jsx("p",{className:"mt-4 text-sm leading-6 text-white/62",children:"Open the guided flow to create half-day presets, holidays, or custom recurring work blocks."}),e.jsx("div",{className:"mt-4",children:e.jsxs(W,{onClick:()=>{k(null),v(!0)},children:[e.jsx(Bi,{className:"size-4"}),"Open work-block guide"]})})]}),e.jsxs(se,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-[18px] bg-[var(--primary)]/14 p-3 text-[var(--primary)]",children:e.jsx(vt,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Plan timebox"}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:"Let Forge recommend valid upcoming slots."})]})]}),e.jsx("p",{className:"mt-4 text-sm leading-6 text-white/62",children:"Choose a task, review the suggested windows, and schedule directly into the calendar."}),e.jsx("div",{className:"mt-4",children:e.jsxs(W,{onClick:()=>y(!0),children:[e.jsx(vt,{className:"size-4"}),"Open planning guide"]})})]}),e.jsxs(se,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-[18px] bg-[var(--primary)]/14 p-3 text-[var(--primary)]",children:e.jsx(rs,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Manage provider settings"}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:He})]})]}),e.jsx("p",{className:"mt-4 text-sm leading-6 text-white/62",children:"Provider connections and setup instructions now live in Settings so the calendar view can stay focused on the week."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsxs(W,{variant:"secondary",onClick:()=>t("/settings/calendar"),children:[e.jsx(Ni,{className:"size-4"}),"Open calendar settings"]}),e.jsxs(W,{variant:"secondary",onClick:()=>t("/settings/calendar?intent=connect"),children:[e.jsx(rs,{className:"size-4"}),"Connect provider"]})]})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(se,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"This week"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:"Quick status for the currently visible week."})]}),e.jsxs(W,{variant:"secondary",onClick:()=>void R.refetch(),children:[e.jsx(ps,{className:"size-4"}),"Refresh view"]})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-sm text-white/54",children:"Provider events"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:D.events.length})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-sm text-white/54",children:"Work blocks"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:D.workBlockInstances.length})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-sm text-white/54",children:"Planned timeboxes"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:ze.length})]})]})]}),e.jsxs(se,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Guided actions"}),e.jsxs("div",{className:"mt-3 grid gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>M(!0),className:"rounded-[22px] border border-white/8 bg-white/[0.04] px-4 py-4 text-left transition hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:"Adjust task blocking rules"}),e.jsx(O,{className:"bg-white/[0.08] text-white/74",children:"Guided"})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Decide which work blocks, calendar conditions, and event keywords should block or allow a task."})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:"Active templates"}),e.jsx(O,{className:"bg-white/[0.08] text-white/74",children:D.workBlockTemplates.length})]}),e.jsxs("div",{className:"mt-3 grid gap-2",children:[D.workBlockTemplates.slice(0,4).map(te=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/74",children:[e.jsx("div",{className:"font-medium text-white",children:te.title}),e.jsxs("div",{className:"mt-1 text-white/56",children:[Al(te.kind)," · ",te.weekDays.length," day",te.weekDays.length===1?"":"s"," · ",te.blockingState]}),e.jsx("div",{className:"mt-1 text-white/46",children:Ll(te)}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(W,{variant:"secondary",size:"sm",onClick:()=>{k(te),v(!0)},children:[e.jsx(ys,{className:"size-3.5"}),"Edit"]}),e.jsxs(W,{variant:"secondary",size:"sm",onClick:()=>void me.mutateAsync(te.id),children:[e.jsx(bt,{className:"size-3.5"}),"Delete"]})]})]},te.id)),D.workBlockTemplates.length===0?e.jsx("div",{className:"text-sm text-white/52",children:"No recurring templates yet. Open the work-block guide to create the first one."}):null]})]})]})]})]})]}),e.jsx(tg,{open:w,onOpenChange:te=>{v(te),te||k(null)},pending:oe.isPending||ue.isPending,template:I,onSubmit:async te=>{if(I){await ue.mutateAsync({templateId:I.id,patch:te});return}await oe.mutateAsync(te)}}),e.jsx(Vx,{open:S,onOpenChange:M,tasks:s.snapshot.tasks,onSave:async({taskId:te,schedulingRules:we,plannedDurationSeconds:Me})=>{await Yi(te,{schedulingRules:we,plannedDurationSeconds:Me}),await s.refresh(),await le(),await a.invalidateQueries({queryKey:["task-context",te]})}}),e.jsx(eg,{open:P,onOpenChange:y,tasks:s.snapshot.tasks,from:U.from,to:U.to,onCreateTimebox:async te=>{await $.mutateAsync(te)}}),e.jsx(Jx,{open:N,onOpenChange:te=>{A(te),te||(F(null),G(null))},writableCalendars:fe,linkOptions:Ge,event:T,seed:q??void 0,onSubmit:async te=>{if(T){const we=T.id;A(!1),F(null),G(null),z.mutateAsync({eventId:we,patch:te}).catch(()=>{});return}else{A(!1),F(null),G(null),E.mutateAsync(te).catch(()=>{});return}},pending:E.isPending||z.isPending}),e.jsx(Yx,{open:u!==null,onOpenChange:te=>{te||j(null)},initialTitle:(u==null?void 0:u.title)??"",pending:z.isPending,onSubmit:async te=>{if(!u)return;const we=u.id;j(null),z.mutateAsync({eventId:we,patch:{title:te}}).catch(()=>{})}}),e.jsx(Wd,{open:Q!==null,title:(Q==null?void 0:Q.kind)==="event"?((Mt=D.events.find(te=>te.id===Q.eventId))==null?void 0:Mt.title)??"Event actions":(Q==null?void 0:Q.kind)==="work-block"?((Et=D.workBlockTemplates.find(te=>te.id===Q.templateId))==null?void 0:Et.title)??"Work block actions":(Q==null?void 0:Q.kind)==="day"?zi(V.find(te=>te.toISOString().slice(0,10)===Q.dayKey)??x):"Calendar actions",subtitle:(Q==null?void 0:Q.kind)==="day"?"Choose what to create or paste into this day.":(Q==null?void 0:Q.kind)==="work-block"?"Edit or remove this recurring work block.":r?`Clipboard ready: ${r.label}`:"Quick calendar event actions.",items:qt,position:(Q==null?void 0:Q.position)??null,onClose:()=>ne(null)})]})}const og={spark:"Spark stage",story:"Story stage",state:"State stage",lens:"Lens stage",pivot:"Pivot stage"};function dg(t,s){return`${t}:${s}`}function Tt(t,s,i){return(t==null?void 0:t[dg(s,i)])??{count:0,latestNoteId:null,latestCreatedAt:null}}function Vd(t){return`${t} Note${t===1?"":"s"}`}function qs(t){return t.replaceAll("_"," ")}function Ui(t){if(!t)return null;const s=t.trim().toLowerCase(),i=og[s];return i||s.split(/[_\-\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function cg(t,s){const i=Ui(s);return i?t==="trigger_report"?`This note is pinned to the ${i.toLowerCase()} of the report, so it stays attached to that part of the reflective chain.`:`This note is pinned to the "${i}" section of the ${qs(t)} instead of only the whole entity.`:null}function Es(t,s){switch(t){case"goal":return`/goals/${s}`;case"project":return`/projects/${s}`;case"task":return`/tasks/${s}`;case"strategy":return`/strategies/${s}`;case"psyche_value":return`/psyche/values?focus=${s}#values-atlas`;case"behavior_pattern":return`/psyche/patterns?focus=${s}#pattern-lanes`;case"behavior":return`/psyche/behaviors?focus=${s}#behavior-columns`;case"belief_entry":return`/psyche/schemas-beliefs?focus=${s}`;case"mode_profile":return`/psyche/modes?focus=${s}`;case"trigger_report":return`/psyche/reports/${s}`;default:return null}}function Zd(t,s){switch(t){case"goal":case"project":case"task":case"strategy":case"trigger_report":{const i=Es(t,s);return i?`${i}#notes`:null}default:return`/notes?entityType=${encodeURIComponent(t)}&entityId=${encodeURIComponent(s)}`}}function Dl(t){return t.links.find(s=>Es(s.entityType,s.entityId)!==null)??t.links[0]??null}function ra(t,s){const i=[],n=/(!?\[\[([^\]]+)\]\]|\[([^\]]+)\]\(([^)]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|\*([^*]+)\*)/g;let a=0,r=null,l=0;for(;(r=n.exec(t))!==null;){if(r.index>a&&(i.push(e.jsx(c.Fragment,{children:t.slice(a,r.index)},`${s}-text-${l}`)),l+=1),r[1]&&r[2]){const d=r[2].trim(),o=r[1].startsWith("!"),x=d.indexOf("|"),f=x>=0?d.slice(0,x).trim():d,b=x>=0?d.slice(x+1).trim():f;if(f.toLowerCase().startsWith("forge:")){const[,m,h]=f.split(":"),p=m&&h?Es(m,h):null,w=p?Ws(p):null;i.push(w?e.jsxs("a",{href:w,className:"inline-flex items-center gap-1 rounded-full bg-amber-400/10 px-2 py-0.5 text-[0.9em] text-amber-100 transition hover:bg-amber-400/18",children:[e.jsx("span",{className:"text-[0.72em] uppercase tracking-[0.14em] text-amber-200/72",children:"Forge"}),e.jsx("span",{children:b})]},`${s}-forge-${l}`):e.jsx("span",{className:"inline-flex items-center gap-1 rounded-full bg-white/[0.06] px-2 py-0.5 text-[0.9em] text-white/66",children:b},`${s}-forge-${l}`))}else{const m=Ws(`/wiki/page/${encodeURIComponent(f)}`);i.push(e.jsxs("a",{href:m,className:re("inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[0.9em] transition",o?"bg-cyan-400/14 text-cyan-50 hover:bg-cyan-400/22":"bg-white/[0.06] text-[var(--secondary)] hover:bg-white/[0.1]"),children:[o?e.jsx("span",{className:"text-[0.72em] uppercase tracking-[0.14em] text-cyan-100/68",children:"Embed"}):null,e.jsx("span",{children:b})]},`${s}-wiki-${l}`))}}else if(r[3]&&r[4]){const d=r[4].trim(),o=/^https?:\/\//i.test(d);i.push(e.jsx("a",{href:d,className:"text-[var(--secondary)] underline decoration-[rgba(125,211,252,0.4)] underline-offset-4 transition hover:text-white",target:o?"_blank":void 0,rel:o?"noreferrer":void 0,children:r[3]},`${s}-link-${l}`))}else r[5]?i.push(e.jsx("code",{className:"rounded bg-white/[0.08] px-1.5 py-0.5 text-[0.92em] text-white/90",children:r[5]},`${s}-code-${l}`)):r[6]?i.push(e.jsx("strong",{className:"font-semibold text-white",children:r[6]},`${s}-strong-${l}`)):r[7]&&i.push(e.jsx("em",{className:"italic text-white/88",children:r[7]},`${s}-em-${l}`));a=n.lastIndex,l+=1}return a<t.length&&i.push(e.jsx(c.Fragment,{children:t.slice(a)},`${s}-tail-${l}`)),i}function mg(t){const s=t.replace(/\r/g,"").split(`
|
|
2
|
+
`),i=[];let n=0;for(;n<s.length;){const a=s[n]??"",r=a.trim();if(!r){n+=1;continue}if(r.startsWith("```")){const o=[];for(n+=1;n<s.length&&!(s[n]??"").trim().startsWith("```");)o.push(s[n]??""),n+=1;n+=1,i.push(e.jsx("pre",{className:"overflow-x-auto rounded-[18px] bg-[rgba(6,10,18,0.88)] px-4 py-3 text-xs leading-6 text-white/86",children:e.jsx("code",{children:o.join(`
|
|
3
|
+
`)})},`code-${n}`));continue}const l=a.match(/^(#{1,6})\s+(.*)$/);if(l){const o=l[1].length,x=o===1?"text-xl":o===2?"text-lg":o===3?"text-base":"text-sm";i.push(e.jsx("div",{className:re("font-semibold text-white",x),children:ra(l[2],`heading-${n}`)},`heading-${n}`)),n+=1;continue}if(/^>\s?/.test(a)){const o=[];for(;n<s.length&&/^>\s?/.test(s[n]??"");)o.push((s[n]??"").replace(/^>\s?/,"")),n+=1;i.push(e.jsx("blockquote",{className:"border-l-2 border-[var(--secondary)]/50 pl-4 text-sm leading-7 text-white/72",children:ra(o.join(" "),`quote-${n}`)},`quote-${n}`));continue}if(/^[-*+]\s+/.test(a)||/^\d+\.\s+/.test(a)){const o=/^\d+\.\s+/.test(a),x=[];for(;n<s.length&&(/^[-*+]\s+/.test(s[n]??"")||/^\d+\.\s+/.test(s[n]??""));)x.push((s[n]??"").replace(/^[-*+]\s+/,"").replace(/^\d+\.\s+/,"")),n+=1;const f=o?"ol":"ul";i.push(e.jsx(f,{className:re("space-y-1 pl-5 text-sm leading-7 text-white/74",o?"list-decimal":"list-disc"),children:x.map((b,m)=>e.jsx("li",{children:ra(b,`list-${n}-${m}`)},`item-${n}-${m}`))},`list-${n}`));continue}const d=[];for(;n<s.length;){const o=s[n]??"";if(!o.trim()||o.trim().startsWith("```")||/^#{1,6}\s+/.test(o)||/^>\s?/.test(o)||/^[-*+]\s+/.test(o)||/^\d+\.\s+/.test(o))break;d.push(o.trim()),n+=1}i.push(e.jsx("p",{className:"text-sm leading-7 text-white/72",children:ra(d.join(" "),`paragraph-${n}`)},`paragraph-${n}`))}return i}function es({markdown:t,className:s}){return e.jsx("div",{className:re("grid gap-3",s),children:mg(t)})}const $l=[{value:"Working memory",label:"Working memory",description:"What you are actively working on right now."},{value:"Short-term memory",label:"Short-term memory",description:"What just happened and still needs near-term recall."},{value:"Episodic memory",label:"Episodic memory",description:"Long-term recall for what happened or what you did."},{value:"Semantic memory",label:"Semantic memory",description:"Long-term knowledge about what something is."},{value:"Procedural memory",label:"Procedural memory",description:"Long-term know-how and repeatable how-to knowledge."}];function ns(t){const s=new Set;return t.map(i=>i.trim()).filter(Boolean).filter(i=>{const n=i.toLowerCase();return s.has(n)?!1:(s.add(n),!0)})}function ec(t){const s=t.trim();if(!s)return null;const i=new Date(s);return Number.isNaN(i.getTime())?null:i.toISOString()}function tc(t){if(!t)return"";const s=new Date(t);if(Number.isNaN(s.getTime()))return"";const i=s.getFullYear(),n=String(s.getMonth()+1).padStart(2,"0"),a=String(s.getDate()).padStart(2,"0"),r=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${i}-${n}-${a}T${r}:${l}`}function sc(t,s){const i=Number(t);if(!Number.isFinite(i)||i<=0)return null;const n=s==="hours"?3600*1e3:1440*60*1e3;return new Date(Date.now()+i*n).toISOString()}function hg(t){const s=new Set($l.map(a=>a.value.toLowerCase())),i=$l.map(a=>({value:a.value,label:a.label,description:a.description,searchText:`${a.label} ${a.description}`,badge:e.jsx(O,{className:"bg-cyan-400/10 text-cyan-50",children:a.label}),menuBadge:e.jsx(O,{className:"bg-cyan-400/10 text-cyan-50",children:a.label})})),n=ns(t).filter(a=>!s.has(a.toLowerCase())).map(a=>({value:a,label:a,description:"Custom note tag",searchText:a,badge:e.jsx(O,{className:"bg-white/[0.08] text-white/78",children:a}),menuBadge:e.jsx(O,{className:"bg-white/[0.08] text-white/78",children:a})}));return[...i,...n]}function Qi({value:t,onChange:s,placeholder:i="Add a memory tag or create a custom tag"}){const n=hg(t);return e.jsx(st,{options:n,selectedValues:ns(t),onChange:a=>s(ns(a)),placeholder:i,emptyMessage:"No note tags yet.",createLabel:"Add custom tag",onCreate:async a=>{const r=a.trim();return{value:r,label:r,description:"Custom note tag",searchText:r,badge:e.jsx(O,{className:"bg-white/[0.08] text-white/78",children:r}),menuBadge:e.jsx(O,{className:"bg-white/[0.08] text-white/78",children:r})}}})}function ug(t,s,i){return t.links.filter(n=>!(n.entityType===s&&n.entityId===i))}function pg(t,s){return t.entityType===s.entityType&&t.entityId===s.entityId&&(t.anchorKey??null)===(s.anchorKey??null)}function un(t){const s=new Set;return t.filter(i=>{const n=`${i.entityType}:${i.entityId}:${i.anchorKey??""}`;return s.has(n)?!1:(s.add(n),!0)})}function Ol(t,s,i){return ec(t)??sc(s,i)}function Ga({entityType:t,entityId:s,anchorKey:i,includeAnchorlessWhenAnchored:n=!1,title:a="Notes",description:r="Markdown notes linked to this entity stay searchable, editable, and visible alongside the work.",invalidateQueryKeys:l=[],compact:d=!1}){var qt,Pt,Mt,Et,te,we,Me,Ve;const o=Ye(),x=We(),[f,b]=c.useState(""),[m,h]=c.useState(!1),[p,w]=c.useState(""),[v,I]=c.useState(!1),[k,S]=c.useState({entityType:"goal",entityId:""}),[M,P]=c.useState([]),[y,N]=c.useState([]),[A,T]=c.useState(""),[F,u]=c.useState(""),[j,L]=c.useState("days"),[q,G]=c.useState(null),[Q,ne]=c.useState(""),[H,_]=c.useState(!1),[U,R]=c.useState([]),[C,J]=c.useState({entityType:"goal",entityId:""}),[ee,le]=c.useState([]),[oe,ue]=c.useState(""),[me,$]=c.useState(""),[ce,E]=c.useState("days"),z=Ui(i),K=cg(t,i),je=pe({queryKey:["notes",t,s],queryFn:()=>Sd({linkedEntityType:t,linkedEntityId:s,limit:100})}),V=pe({queryKey:["forge-psyche-values"],queryFn:ls}),D=pe({queryKey:["forge-psyche-patterns"],queryFn:Xs}),X=pe({queryKey:["forge-psyche-behaviors"],queryFn:os}),he=pe({queryKey:["forge-psyche-beliefs"],queryFn:As}),ye=pe({queryKey:["forge-psyche-modes"],queryFn:Ls}),ze=pe({queryKey:["forge-psyche-reports"],queryFn:Ti}),fe=c.useMemo(()=>{var Se,xe,Ie,Ee,et,Fe,ut;return{goal:o.snapshot.goals.map(Te=>({id:Te.id,label:Je(Te.title,Te.user)})),project:o.snapshot.dashboard.projects.map(Te=>({id:Te.id,label:Je(Te.title,Te.user)})),task:o.snapshot.tasks.map(Te=>({id:Te.id,label:Je(Te.title,Te.user)})),strategy:o.snapshot.strategies.map(Te=>({id:Te.id,label:Je(Te.title,Te.user)})),habit:o.snapshot.habits.map(Te=>({id:Te.id,label:Je(Te.title,Te.user)})),tag:o.snapshot.tags.map(Te=>({id:Te.id,label:Je(Te.name,Te.user)})),note:(((Se=je.data)==null?void 0:Se.notes)??[]).map(Te=>({id:Te.id,label:Te.contentPlain||Te.contentMarkdown})),insight:[],psyche_value:(((xe=V.data)==null?void 0:xe.values)??[]).map(Te=>({id:Te.id,label:Je(Te.title,Te.user)})),behavior_pattern:(((Ie=D.data)==null?void 0:Ie.patterns)??[]).map(Te=>({id:Te.id,label:Je(Te.title,Te.user)})),behavior:(((Ee=X.data)==null?void 0:Ee.behaviors)??[]).map(Te=>({id:Te.id,label:Je(Te.title,Te.user)})),belief_entry:(((et=he.data)==null?void 0:et.beliefs)??[]).map(Te=>({id:Te.id,label:Je(Te.statement,Te.user)})),mode_profile:(((Fe=ye.data)==null?void 0:Fe.modes)??[]).map(Te=>({id:Te.id,label:Je(Te.title,Te.user)})),mode_guide_session:[],event_type:[],emotion_definition:[],trigger_report:(((ut=ze.data)==null?void 0:ut.reports)??[]).map(Te=>({id:Te.id,label:Je(Te.title,Te.user)})),calendar_event:[],work_block_template:[],task_timebox:[]}},[(qt=X.data)==null?void 0:qt.behaviors,(Pt=he.data)==null?void 0:Pt.beliefs,(Mt=ye.data)==null?void 0:Mt.modes,(Et=je.data)==null?void 0:Et.notes,(te=D.data)==null?void 0:te.patterns,(we=ze.data)==null?void 0:we.reports,o.snapshot.dashboard.projects,o.snapshot.goals,o.snapshot.habits,o.snapshot.strategies,o.snapshot.tags,o.snapshot.tasks,(Me=V.data)==null?void 0:Me.values]),Pe=async()=>{await Promise.all([x.invalidateQueries({queryKey:["notes",t,s]}),x.invalidateQueries({queryKey:["forge-snapshot"]}),...l.map(Se=>x.invalidateQueries({queryKey:Se}))])},Ge=ge({mutationFn:async Se=>mr({contentMarkdown:Se,tags:ns(y),destroyAt:Ol(A,F,j),links:un([{entityType:t,entityId:s,anchorKey:i??null},...M])}),onSuccess:async()=>{w(""),I(!1),P([]),S({entityType:"goal",entityId:""}),N([]),T(""),u(""),L("days"),await Pe()}}),Z=ge({mutationFn:async({noteId:Se,contentMarkdown:xe,links:Ie,tags:Ee,destroyAt:et})=>Cd(Se,{contentMarkdown:xe,links:Ie,tags:Ee,destroyAt:et}),onSuccess:async()=>{G(null),ne(""),_(!1),R([]),J({entityType:"goal",entityId:""}),le([]),ue(""),$(""),E("days"),await Pe()}}),He=ge({mutationFn:async Se=>Id(Se),onSuccess:Pe}),Ue=c.useMemo(()=>{var xe;return(((xe=je.data)==null?void 0:xe.notes)??[]).filter(Ie=>i===void 0?!0:Ie.links.some(Ee=>Ee.entityType===t&&Ee.entityId===s&&((Ee.anchorKey??null)===i||n&&(Ee.anchorKey??null)===null))).filter(Ie=>{const Ee=f.trim().toLowerCase();return Ee?`${Ie.contentPlain} ${Ie.author??""} ${(Ie.tags??[]).join(" ")}`.toLowerCase().includes(Ee):!0})},[i,s,t,n,(Ve=je.data)==null?void 0:Ve.notes,f]),Qe=(Se,xe,Ie)=>{const Ee=Se.entityId.trim();return Ee?(xe(un([...Ie,{entityType:Se.entityType,entityId:Ee,anchorKey:null}])),!0):!1},ct=Se=>{var Ie,Ee;const xe=(Ie=fe[Se.entityType])==null?void 0:Ie.find(et=>et.id===Se.entityId);return(Ee=xe==null?void 0:xe.label)!=null&&Ee.trim()?xe.label.trim():`Deleted ${qs(Se.entityType)}`},zt=(Se,xe,Ie,Ee,et)=>e.jsxs("div",{className:"rounded-[20px] bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Linked entities"}),e.jsxs(O,{className:"bg-white/[0.08] text-white/68",children:[Se.length," linked"]})]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:Se.map(Fe=>{const ut=Se.length>1;return e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full bg-white/[0.08] px-3 py-2 text-sm text-white/72",children:[e.jsxs("span",{children:[qs(Fe.entityType)," · ",ct(Fe)]}),Fe.anchorKey?e.jsx("span",{className:"rounded-full bg-white/[0.08] px-2 py-0.5 text-[11px] text-white/54",children:Ui(Fe.anchorKey)}):null,e.jsx("button",{type:"button",disabled:!ut,className:"text-white/44 transition hover:text-white disabled:cursor-not-allowed disabled:opacity-30",onClick:()=>xe(Se.filter(Te=>!pg(Te,Fe))),"aria-label":`Remove ${qs(Fe.entityType)} link to ${ct(Fe)}`,children:e.jsx(bt,{className:"size-3.5"})})]},`${et}-${Fe.entityType}-${Fe.entityId}-${Fe.anchorKey??""}`)})}),e.jsxs("div",{className:"mt-4 grid gap-3 md:grid-cols-[minmax(0,11rem)_minmax(0,1fr)_auto]",children:[e.jsx("select",{className:"rounded-[14px] bg-white/[0.06] px-3 py-3 text-white",value:Ie.entityType,onChange:Fe=>Ee({...Ie,entityType:Fe.target.value,entityId:""}),children:["goal","project","task","strategy","habit","tag","note","psyche_value","behavior_pattern","behavior","belief_entry","mode_profile","mode_guide_session","event_type","emotion_definition","trigger_report"].map(Fe=>e.jsx("option",{value:Fe,children:qs(Fe)},Fe))}),e.jsxs("select",{className:"min-w-0 rounded-[14px] bg-white/[0.06] px-3 py-3 text-white",value:Ie.entityId,onChange:Fe=>Ee({...Ie,entityId:Fe.target.value}),children:[e.jsx("option",{value:"",children:(fe[Ie.entityType]??[]).length>0?"Choose linked item":"No linked items available"}),(fe[Ie.entityType]??[]).map(Fe=>e.jsx("option",{value:Fe.id,children:Fe.label},Fe.id))]}),e.jsx(W,{variant:"secondary",disabled:!Ie.entityId,onClick:()=>{Qe(Ie,xe,Se)&&Ee({...Ie,entityId:""})},children:"Add link"})]})]});return e.jsx(se,{id:"notes",className:d?"min-w-0 overflow-hidden p-0":"min-w-0 overflow-hidden",children:e.jsxs("div",{className:d?"p-4":void 0,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:a}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:r}),z?e.jsxs("div",{className:"mt-3 inline-flex items-center gap-2 rounded-full bg-white/[0.05] px-3 py-2 text-xs text-white/64",children:[e.jsxs("span",{children:["Pinned to ",z]}),K?e.jsx(Xe,{content:K,label:`Explain ${z}`}):null]}):null]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:Vd(Ue.length)}),m?null:e.jsxs(W,{type:"button",size:"sm",onClick:()=>h(!0),children:[e.jsx(Wt,{className:"size-4"}),"Add note"]})]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-2 rounded-[22px] border border-white/8 bg-white/[0.04] px-3 py-3",children:[e.jsx(dt,{className:"size-4 text-white/34"}),e.jsx(ie,{value:f,onChange:Se=>b(Se.target.value),placeholder:"Search notes by content, author, or note tag",className:"border-0 bg-transparent px-0 py-0"})]}),m?e.jsxs("div",{className:"mt-4 rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/70",children:[e.jsx(Wt,{className:"size-4 text-[var(--secondary)]"}),"Add note"]}),e.jsxs(W,{type:"button",variant:"secondary",size:"sm",className:"gap-2",onClick:()=>I(Se=>!Se),children:[e.jsx(Wr,{className:"size-4"}),v?"Back to editor":"Preview"]})]}),e.jsx("div",{className:"mt-3",children:v?e.jsxs("div",{className:"rounded-[20px] bg-[rgba(9,14,25,0.78)] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Preview"}),e.jsx("div",{className:"mt-3",children:p.trim()?e.jsx(es,{markdown:p}):e.jsx("div",{className:"text-sm leading-6 text-white/42",children:"Markdown preview appears here once you have note content."})})]}):e.jsx(Ce,{value:p,onChange:Se=>w(Se.target.value),placeholder:"Write in Markdown. Summaries, blockers, what changed, and why all work well here.",className:"min-h-[12rem]"})}),e.jsx("div",{className:"mt-3",children:zt(un([{entityType:t,entityId:s,anchorKey:i??null},...M]),Se=>P(Se.filter(xe=>!(xe.entityType===t&&xe.entityId===s&&(xe.anchorKey??null)===(i??null)))),k,S,"composer-note-links")}),e.jsxs("div",{className:"mt-3 grid gap-3 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]",children:[e.jsx(Qi,{value:y,onChange:N}),e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Ephemeral auto-destroy"}),e.jsx("div",{className:"mt-2 text-xs leading-5 text-white/46",children:"Set an exact destroy time or a relative delay. Leaving both blank keeps the note durable."})]}),e.jsx(ie,{type:"datetime-local",value:A,onChange:Se=>T(Se.target.value)}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_10rem]",children:[e.jsx(ie,{type:"number",min:"1",value:F,onChange:Se=>u(Se.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:j,onChange:Se=>L(Se.target.value),children:[e.jsx("option",{value:"hours",children:"Hours"}),e.jsx("option",{value:"days",children:"Days"})]})]})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap justify-end gap-2",children:[e.jsx(W,{type:"button",variant:"secondary",onClick:()=>{h(!1),I(!1),w(""),P([]),S({entityType:"goal",entityId:""}),N([]),T(""),u(""),L("days")},children:"Cancel"}),e.jsx(W,{pending:Ge.isPending,pendingLabel:"Saving",disabled:p.trim().length===0,onClick:async()=>{await Ge.mutateAsync(p.trim()),h(!1)},children:"Save note"})]})]}):null,e.jsxs("div",{className:"mt-4 grid gap-3",children:[je.isLoading?e.jsx("div",{className:"rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/56",children:"Loading notes…"}):null,!je.isLoading&&Ue.length===0?e.jsx("div",{className:"rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/56",children:"No notes are linked here yet."}):null,Ue.map(Se=>{const xe=q===Se.id,Ie=ug(Se,t,s);return e.jsxs("article",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-xs uppercase tracking-[0.16em] text-white/38",children:[(Se.author??"Unknown author").toString()," •"," ",new Date(Se.updatedAt).toLocaleString()]}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[Ie.map(Ee=>e.jsxs(O,{className:"bg-white/[0.08] text-white/68",wrap:!0,children:[qs(Ee.entityType)," ·"," ",ct(Ee),Ee.anchorKey?` · ${Ui(Ee.anchorKey)}`:""]},`${Se.id}-${Ee.entityType}-${Ee.entityId}-${Ee.anchorKey??""}`)),(Se.tags??[]).map(Ee=>e.jsx(O,{className:"bg-cyan-400/10 text-cyan-50",wrap:!0,children:Ee},`${Se.id}-tag-${Ee}`)),Se.destroyAt?e.jsxs(O,{className:"bg-amber-400/10 text-amber-100",wrap:!0,children:["Ephemeral · deletes"," ",new Date(Se.destroyAt).toLocaleString()]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button",className:"inline-flex size-9 items-center justify-center rounded-full bg-white/[0.06] text-white/60 transition hover:bg-white/[0.1] hover:text-white",onClick:()=>{G(Se.id),ne(Se.contentMarkdown),_(!1),R(Se.links),J({entityType:"goal",entityId:""}),le(ns(Se.tags??[])),ue(tc(Se.destroyAt??null)),$(""),E("days")},children:e.jsx(Us,{className:"size-4"})}),e.jsx("button",{type:"button",className:"inline-flex size-9 items-center justify-center rounded-full bg-rose-500/10 text-rose-200 transition hover:bg-rose-500/16",onClick:()=>{He.mutateAsync(Se.id)},children:e.jsx(bt,{className:"size-4"})})]})]}),xe?e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"flex flex-wrap items-center justify-end gap-2",children:e.jsxs(W,{type:"button",variant:"secondary",size:"sm",className:"gap-2",onClick:()=>_(Ee=>!Ee),children:[e.jsx(Wr,{className:"size-4"}),H?"Back to editor":"Preview"]})}),e.jsx("div",{className:"mt-3",children:H?e.jsxs("div",{className:"rounded-[20px] bg-[rgba(9,14,25,0.78)] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Preview"}),e.jsx("div",{className:"mt-3",children:Q.trim()?e.jsx(es,{markdown:Q}):e.jsx("div",{className:"text-sm text-white/42",children:"No content yet."})})]}):e.jsx(Ce,{value:Q,onChange:Ee=>ne(Ee.target.value),className:"min-h-[12rem]"})}),e.jsxs("div",{className:"mt-3 grid gap-3 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]",children:[e.jsx(Qi,{value:ee,onChange:le}),e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Ephemeral auto-destroy"}),e.jsx("div",{className:"mt-2 text-xs leading-5 text-white/46",children:"Set an exact destroy time or a relative delay. Leaving both blank keeps the note durable."})]}),e.jsx(ie,{type:"datetime-local",value:oe,onChange:Ee=>ue(Ee.target.value)}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_10rem]",children:[e.jsx(ie,{type:"number",min:"1",value:me,onChange:Ee=>$(Ee.target.value),placeholder:"Destroy after"}),e.jsxs("select",{className:"rounded-[14px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:ce,onChange:Ee=>E(Ee.target.value),children:[e.jsx("option",{value:"hours",children:"Hours"}),e.jsx("option",{value:"days",children:"Days"})]})]})]})]}),e.jsx("div",{className:"mt-3",children:zt(U,R,C,J,`edit-note-links-${Se.id}`)}),e.jsxs("div",{className:"mt-3 flex flex-wrap justify-end gap-2",children:[e.jsx(W,{variant:"secondary",onClick:()=>{G(null),_(!1),le([]),ue(""),$(""),E("days")},children:"Cancel"}),e.jsx(W,{pending:Z.isPending,pendingLabel:"Saving",disabled:Q.trim().length===0||U.length===0,onClick:async()=>{await Z.mutateAsync({noteId:Se.id,contentMarkdown:Q.trim(),links:U,tags:ns(ee),destroyAt:Ol(oe,me,ce)})},children:"Save changes"})]})]}):e.jsx("div",{className:"mt-4",children:e.jsx(es,{markdown:Se.contentMarkdown})})]},Se.id)})]})]})})}function Ha({userId:t,domain:s,entityType:i,entityId:n,label:a,description:r,tags:l,size:d="sm"}){const o=ht(),x=We(),f=ge({mutationFn:async()=>{if(!t)throw new Error("Select a single owner before sending entities to Preferences.");return On({userId:t,domain:s,entityType:i,entityId:n,label:a,description:r,tags:l})},onSuccess:async({item:b})=>{await x.invalidateQueries({queryKey:["forge-preferences"]}),o(`/preferences?userId=${encodeURIComponent(t??"")}&domain=${encodeURIComponent(s)}&focusItem=${encodeURIComponent(b.id)}`)}});return e.jsxs(W,{variant:"secondary",size:d,disabled:!t,pending:f.isPending,pendingLabel:"Sending to Preferences",onClick:()=>void f.mutateAsync(),title:t?"Add this entity to the Preferences compare queue.":"Select a single user scope before sending entities to Preferences.",children:[e.jsx(Go,{className:"size-4"}),"Send to Preferences"]})}const Fl={active:"Active",paused:"Suspended",completed:"Finished",all:"All"};function xr({value:t,counts:s,onChange:i,className:n}){return e.jsx("div",{className:re("flex flex-wrap gap-2",n),children:Object.keys(Fl).map(a=>{const r=a===t;return e.jsxs("button",{type:"button",onClick:()=>i(a),className:re("inline-flex min-h-10 items-center gap-2 rounded-full border px-4 py-2 text-sm transition",r?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.16)] text-white shadow-[0_16px_36px_rgba(8,12,24,0.18)]":"border-white/8 bg-white/[0.04] text-white/62 hover:bg-white/[0.08] hover:text-white"),children:[e.jsx("span",{children:Fl[a]}),e.jsx("span",{className:re("rounded-full px-2 py-0.5 text-[11px]",r?"bg-white/12 text-white/88":"bg-white/8 text-white/54"),children:s[a]})]},a)})})}function ts({value:t,className:s,tone:i="primary"}){const n=`${Math.max(4,Math.min(100,t))}%`,a=i==="secondary"?"from-[var(--secondary)] to-[rgba(78,222,163,0.45)]":i==="tertiary"?"from-[var(--tertiary)] to-[rgba(255,185,95,0.45)]":"from-[var(--primary)] to-[rgba(192,193,255,0.45)]";return e.jsx("div",{className:re("h-1.5 rounded-full bg-white/[0.08]",s),children:e.jsx("div",{className:re("h-full rounded-full bg-gradient-to-r",a),style:{width:n}})})}function ic(t){const s=`${t.title} ${t.description} ${t.source??""}`.toLowerCase();return s.includes("playwright")||s.includes("operator console")||s.includes("retroactive work logging")}function Xa(t){return ic(t)?"Work log added":t.title}function Ja(t){return ic(t)?"This entry was added later so the work history stays complete and accurate.":t.description}function gr(t){return{active:t.filter(s=>s.status==="active").length,paused:t.filter(s=>s.status==="paused").length,completed:t.filter(s=>s.status==="completed").length,all:t.length}}function br(t,s){return s==="all"?t:t.filter(i=>i.status===s)}function xg(){const{t}=at(),s=Ye(),i=Hs(),n=ht(),a=We(),[r,l]=c.useState(!1),[d,o]=c.useState(!1),[x,f]=c.useState("active"),b=Nt(s.selectedUserIds),[m,h]=c.useState(null),p=ge({mutationFn:()=>yx(i.goalId),onSuccess:async()=>{await Promise.all([a.invalidateQueries({queryKey:["forge-snapshot"]}),a.invalidateQueries({queryKey:["project-board"]}),a.invalidateQueries({queryKey:["task-context"]})]),n("/goals")}}),w=s.snapshot.dashboard.goals.find(u=>u.id===i.goalId)??null,v=c.useMemo(()=>s.snapshot.dashboard.projects.filter(u=>u.goalId===i.goalId),[i.goalId,s.snapshot.dashboard.projects]),I=c.useMemo(()=>gr(v),[v]),k=c.useMemo(()=>br(v,x),[v,x]),S=new Set(v.map(u=>u.id)),M=new Set(s.snapshot.tasks.filter(u=>S.has(u.projectId??"")).map(u=>u.id)),P=s.snapshot.activity.filter(u=>u.entityId===i.goalId||S.has(u.entityId)||M.has(u.entityId)||u.entityType==="task_run"&&typeof u.metadata.taskId=="string"&&M.has(u.metadata.taskId));if(!w)return e.jsx(gt,{eyebrow:t("common.goalDetail.eyebrow"),title:t("common.goalDetail.missingTitle"),description:t("common.goalDetail.missingDescription"),action:e.jsx(Le,{to:"/goals",className:"inline-flex min-h-10 min-w-0 max-w-full items-center justify-center whitespace-nowrap rounded-full bg-[var(--primary)] px-4 py-2 text-sm font-medium text-slate-950 transition hover:opacity-90",children:t("common.goalDetail.backToGoals")})});const y=k.find(u=>u.nextTaskTitle)??k[0]??null,N=s.snapshot.overview.neglectedGoals.find(u=>u.goalId===w.id)??null,A=P[0]??null,T=async u=>{h(u);try{await s.patchProject(u,{status:"active"})}finally{h(null)}},F=async()=>{window.confirm(t("common.goalDetail.deleteGoalConfirm",{title:w.title}))&&await p.mutateAsync()};return e.jsxs("div",{className:"grid min-w-0 gap-5",children:[e.jsx(Ke,{entityKind:"goal",title:e.jsx(_e,{kind:"goal",label:w.title,variant:"heading",size:"lg"}),titleText:w.title,description:w.description?e.jsx(es,{markdown:w.description,className:"[&>p]:text-[13px] [&>p]:leading-6 [&>blockquote]:text-[13px] [&>ul]:text-[13px] [&>ol]:text-[13px]"}):"No strategic description yet.",badge:t(k.length===1?"common.goalDetail.heroBadgeOne":"common.goalDetail.heroBadgeOther",{count:k.length}),actions:e.jsx(Ha,{userId:b,domain:"projects",entityType:"goal",entityId:w.id,label:w.title,description:w.description})}),w.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($e,{user:w.user})]}):null,e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(W,{onClick:()=>l(!0),children:t("common.goalDetail.edit")}),e.jsx(W,{variant:"secondary",onClick:()=>o(!0),children:t("common.goalDetail.addProject")}),e.jsx(W,{variant:"ghost",className:"text-rose-200 hover:bg-rose-500/10",pending:p.isPending,pendingLabel:t("common.goalDetail.deleting"),onClick:()=>void F(),children:t("common.goalDetail.deleteGoal")})]}),e.jsxs("section",{className:"grid min-w-0 gap-5 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]",children:[e.jsxs(se,{children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.goalDetail.sectionProjects")}),e.jsx(xr,{value:x,counts:I,onChange:f,className:"justify-end"})]}),k.length===0?e.jsx("div",{className:"mt-4 rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/58",children:x==="active"?t("common.goalDetail.noProjects"):"No projects match this lifecycle filter yet. Switch filters or restart one to make it active again."}):e.jsx("div",{className:"mt-4 grid gap-4 lg:grid-cols-2",children:k.map(u=>e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-5 transition hover:bg-white/[0.08]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(ke,{kind:"project",compact:!0,gradient:!1}),u.user?e.jsx($e,{user:u.user,compact:!0}):null]}),e.jsx(O,{children:u.status})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Le,{to:`/projects/${u.id}`,className:"transition hover:opacity-90",children:e.jsx(_e,{kind:"project",label:u.title,variant:"heading",size:"lg"})})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:u.description}),e.jsx("div",{className:"mt-4",children:e.jsx(ts,{value:u.progress})}),e.jsx("div",{className:"mt-4 text-[11px] uppercase tracking-[0.16em] text-white/40",children:u.nextTaskTitle?t("common.goalDetail.nextMove",{value:u.nextTaskTitle}):t("common.goalDetail.addNextTask")}),e.jsxs("div",{className:"mt-4 flex flex-wrap justify-between gap-3",children:[e.jsx(Le,{to:`/projects/${u.id}`,children:e.jsx(W,{variant:"ghost",children:"Open project"})}),x!=="active"&&u.status!=="active"?e.jsx(W,{variant:"secondary",size:"sm",pending:m===u.id,pendingLabel:"Restarting…",onClick:()=>void T(u.id),children:"Restart"}):null]})]},u.id))})]}),e.jsx("div",{className:"grid min-w-0 gap-5",children:e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.goalDetail.sectionHealth")}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-2",children:[e.jsx(ke,{kind:"goal",compact:!0,gradient:!1}),e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:t("common.goalDetail.progressTitle",{progress:w.progress,count:w.completedTasks})}),e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:t("common.goalDetail.progressDetail",{xp:w.earnedPoints})}),e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:t(k.length===1?"common.goalDetail.heroBadgeOne":"common.goalDetail.heroBadgeOther",{count:k.length})})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:t("common.goalDetail.fieldProgress")}),e.jsxs("div",{className:"mt-2 font-display text-xl text-white",children:[w.progress,"%"]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:t("common.goalDetail.fieldCompletedTasks")}),e.jsx("div",{className:"mt-2 font-display text-xl text-white",children:w.completedTasks})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:t("common.goalDetail.fieldXpBanked")}),e.jsx("div",{className:"mt-2 font-display text-xl text-white",children:w.earnedPoints})]})]}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:t("common.goalDetail.signalNext")}),y?e.jsx(ke,{kind:"project",compact:!0,gradient:!1}):null]}),e.jsx("div",{className:"mt-2 font-medium text-white",children:(y==null?void 0:y.title)??t("common.goalDetail.noProject")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:y!=null&&y.nextTaskTitle?t("common.goalDetail.nextMove",{value:y.nextTaskTitle}):(y==null?void 0:y.description)||t("common.goalDetail.noProjectDetail")})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:t("common.goalDetail.signalRisk")}),e.jsx("div",{className:"mt-2 font-medium text-white",children:(N==null?void 0:N.title)??t("common.goalDetail.noRisk")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(N==null?void 0:N.summary)||t("common.goalDetail.noRiskDetail")})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:t("common.goalDetail.signalEvidence")}),e.jsx("div",{className:"mt-2 font-medium text-white",children:(A==null?void 0:A.title)??t("common.goalDetail.noEvidence")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(A==null?void 0:A.description)||t("common.goalDetail.noEvidenceDetail")})]})]})]})]})})]}),e.jsx(Ga,{entityType:"goal",entityId:w.id,title:"Goal notes",description:"Use notes to capture strategy changes, meaning shifts, and progress context that belongs at the goal level."}),e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.goalDetail.sectionEvidence")}),P.length===0?e.jsx("div",{className:"mt-4 rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/58",children:t("common.goalDetail.noEvidenceLogged")}):e.jsx("div",{className:"mt-4 grid gap-3 lg:grid-cols-2",children:P.slice(0,6).map(u=>e.jsxs(Le,{to:Ms(u)??`/activity?eventId=${u.id}`,className:"rounded-[18px] bg-white/[0.04] p-4 transition hover:bg-white/[0.08]",children:[e.jsx("div",{className:"font-medium text-white",children:Xa(u)}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:Ja(u)})]},u.id))})]}),e.jsx(ar,{open:r,editingGoal:w,tags:s.snapshot.tags,users:s.snapshot.users,defaultUserId:w.userId??b,onOpenChange:l,onSubmit:async(u,j)=>{j&&await s.patchGoal(j,u)}}),e.jsx(nr,{open:d,goals:s.snapshot.goals,users:s.snapshot.users,editingProject:null,initialGoalId:w.id,defaultUserId:w.userId??b,onOpenChange:o,onSubmit:async u=>{await s.createProject(u)}})]})}function yt({entityType:t,entityId:s,count:i,className:n=""}){const a=ht(),r=Zd(t,s);return r?e.jsxs("span",{role:"link",tabIndex:0,className:`inline-flex min-h-10 items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-3 py-2 text-xs text-white/72 transition hover:bg-white/[0.09] hover:text-white ${n}`,onClick:l=>{l.stopPropagation(),a(r)},onKeyDown:l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),l.stopPropagation(),a(r))},children:[e.jsx(Wn,{className:"size-3.5"}),Vd(i)]}):null}function gg({goals:t,tags:s,users:i,defaultUserId:n=null,pending:a=!1,onCreate:r,onUpdate:l}){const[d,o]=c.useState(!1),[x,f]=c.useState(null),b=t.find(m=>m.id===x)??null;return e.jsxs(e.Fragment,{children:[e.jsxs(se,{children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Goal arcs"}),e.jsx("h3",{className:"mt-2 font-display text-3xl text-white",children:"Strategic arcs before tickets"}),e.jsx("p",{className:"mt-3 max-w-3xl text-sm leading-7 text-white/60",children:"This is the long-horizon map. Each arc shows why it matters, how much ground has been covered, and which project should move next."})]}),e.jsx(W,{onClick:()=>{f(null),o(!0)},children:"Create goal"})]}),e.jsxs("div",{className:"mt-5 grid gap-3 xl:grid-cols-2",children:[t.length===0?e.jsx("div",{className:"rounded-[24px] bg-white/[0.04] p-5 text-sm leading-7 text-white/60 xl:col-span-2",children:"Start with a life goal. Once the destination is clear, you can attach projects and then fill those projects with tasks."}):null,t.map(m=>{const h=`${Math.max(6,Math.min(100,m.progress))}%`;return e.jsxs(Le,{to:`/goals/${m.id}`,className:"rounded-[24px] border border-white/6 bg-[linear-gradient(180deg,rgba(255,255,255,0.06),rgba(255,255,255,0.03))] p-4 transition hover:bg-[linear-gradient(180deg,rgba(255,255,255,0.09),rgba(255,255,255,0.04))]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(ke,{kind:"goal",compact:!0,gradient:!1}),e.jsx("div",{className:"mt-2",children:e.jsx(_e,{kind:"goal",label:m.title,variant:"heading",size:"lg",showKind:!1})}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/58",children:m.description||"No strategic note attached yet."})]}),e.jsx("button",{className:"rounded-full bg-white/6 p-2 text-white/60 transition hover:bg-white/10 hover:text-white",type:"button",onClick:p=>{p.preventDefault(),p.stopPropagation(),f(m.id),o(!0)},children:e.jsx(ys,{className:"size-4"})})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(O,{className:"bg-white/[0.08] text-white/70",children:m.horizon}),e.jsx(O,{className:m.status==="active"?"text-emerald-300":m.status==="paused"?"text-amber-300":"text-[var(--tertiary)]",children:m.status}),e.jsxs(O,{className:"bg-white/[0.08] text-white/70",children:[m.earnedPoints," / ",m.targetPoints," xp"]}),e.jsxs(O,{className:"bg-white/[0.08] text-white/70",children:[m.totalTasks," tasks"]})]}),e.jsx("div",{className:"mt-4 h-1.5 rounded-full bg-white/[0.08]",children:e.jsx("div",{className:"h-full rounded-full bg-[linear-gradient(90deg,var(--primary)_0%,var(--secondary)_100%)]",style:{width:h}})}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:m.tags.map(p=>e.jsx(O,{className:"bg-white/[0.06] text-white/58",children:p.name},p.id))}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] uppercase tracking-[0.16em] text-white/42",children:[e.jsx("span",{children:m.momentumLabel}),e.jsxs("span",{className:"inline-flex items-center gap-2",style:{color:m.themeColor},children:["Open arc",e.jsx(Gs,{className:"size-3.5"})]})]})]},m.id)})]})]}),e.jsx(ar,{open:d,pending:a,editingGoal:b,tags:s,users:i,defaultUserId:n,onOpenChange:m=>{o(m),m||f(null)},onSubmit:async(m,h)=>{if(h){await l(h,m);return}await r(m)}})]})}function bg(){const t=Ye(),[s,i]=c.useState("active"),[n,a]=c.useState(null),r=t.snapshot.dashboard.goals.length>0,l=gr(t.snapshot.dashboard.projects),d=br(t.snapshot.dashboard.projects,s),o=Nt(t.selectedUserIds),x=new Map(t.snapshot.dashboard.goals.map(b=>[b.id,d.filter(m=>m.goalId===b.id)])),f=async b=>{a(b);try{await t.patchProject(b,{status:"active"})}finally{a(null)}};return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{entityKind:"goal",title:e.jsx(_e,{kind:"goal",label:"Life Goals",variant:"heading",size:"lg"}),titleText:"Life Goals",description:"Life goals are the destinations you care about over the long run. Each one can hold several projects, and those projects turn direction into real work.",badge:`${t.snapshot.dashboard.goals.length} active goals`,actions:r?e.jsxs("div",{className:"inline-flex min-h-10 items-center rounded-full border border-white/8 bg-white/[0.04] px-4 py-2 text-sm whitespace-nowrap text-white/68",children:[t.snapshot.dashboard.projects.length," live project",t.snapshot.dashboard.projects.length===1?"":"s"," ","attached"]}):null}),e.jsx(gg,{goals:t.snapshot.dashboard.goals,tags:t.snapshot.tags,users:t.snapshot.users,defaultUserId:o,onCreate:t.createGoal,onUpdate:t.patchGoal}),r?e.jsx(xr,{value:s,counts:l,onChange:i}):null,r?null:e.jsx(gt,{eyebrow:"Life goals",title:"No life goals yet",description:"Define the first long-horizon direction above so Forge can attach projects, tasks, momentum, and evidence to something meaningful."}),r?e.jsx("div",{className:"grid gap-4",children:t.snapshot.dashboard.goals.map(b=>{const m=x.get(b.id)??[],h=Tt(t.snapshot.dashboard.notesSummaryByEntity,"goal",b.id);return e.jsx(Le,{to:`/goals/${b.id}`,className:"rounded-[28px] border border-white/6 bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.03))] p-4 transition hover:bg-[linear-gradient(180deg,rgba(255,255,255,0.08),rgba(255,255,255,0.04))] sm:p-5",children:e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)] xl:gap-5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[b.tags.slice(0,3).map(p=>e.jsx(O,{className:"bg-white/[0.08]",style:{color:p.color},children:p.name},p.id)),e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:b.horizon}),e.jsx($e,{user:b.user,compact:!0})]}),e.jsx("div",{className:"mt-4",children:e.jsx(_e,{kind:"goal",label:b.title,variant:"heading",size:"xl"})}),e.jsx("p",{className:"mt-3 max-w-2xl text-sm leading-7 text-white/58",children:b.description}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Progress"}),e.jsxs("div",{className:"mt-2 text-xl text-white",children:[b.progress,"%"]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Tasks done"}),e.jsxs("div",{className:"mt-2 text-xl text-white",children:[b.completedTasks,"/",Math.max(b.totalTasks,1)]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"XP banked"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:b.earnedPoints})]})]}),e.jsx("div",{className:"mt-4",children:e.jsx(ts,{value:b.progress})}),e.jsx("div",{className:"mt-4",children:e.jsx(yt,{entityType:"goal",entityId:b.id,count:h.count})})]}),e.jsxs("div",{className:"rounded-[24px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:"Projects carrying this direction"}),e.jsx("div",{className:"text-sm text-white/48",children:m.length})]}),m.length===0?e.jsx("div",{className:"mt-4 text-sm leading-6 text-white/56",children:s==="active"?"No active project is attached yet. Create one so this direction starts producing visible work.":"No projects in this lifecycle view are attached yet. Switch filters or restart one to bring it back into active motion."}):e.jsx("div",{className:"mt-4 grid gap-3",children:m.slice(0,3).map(p=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.05] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(ke,{kind:"project",compact:!0,gradient:!1}),e.jsx(_e,{kind:"project",label:p.title,className:"min-w-0",showIcon:!1})]}),e.jsx(O,{children:p.status})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:p.description}),e.jsxs("div",{className:"mt-3 text-sm text-white/42",children:["Next move:"," ",p.nextTaskTitle??"Define the first attached task"]}),s!=="active"&&p.status!=="active"?e.jsx("div",{className:"mt-4 flex justify-end",children:e.jsx(W,{variant:"secondary",size:"sm",pending:n===p.id,pendingLabel:"Restarting…",onClick:w=>{w.preventDefault(),w.stopPropagation(),f(p.id)},children:"Restart"})}):null]},p.id))})]})]})},b.id)})}):e.jsx(se,{children:e.jsx("div",{className:"rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/58",children:"Goal cards will appear here once the first long-horizon direction is created."})})]})}const pn={title:"",description:"",status:"active",userId:null,polarity:"positive",frequency:"daily",targetCount:1,weekDays:[],linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],linkedValueIds:[],linkedPatternIds:[],linkedBehaviorIds:[],linkedBeliefIds:[],linkedModeIds:[],linkedReportIds:[],linkedBehaviorId:"",rewardXp:12,penaltyXp:8,generatedHealthEventTemplate:{enabled:!1,workoutType:"workout",title:"",durationMinutes:45,xpReward:0,tags:[],links:[],notesTemplate:""}},fg=[{value:1,label:"Mon"},{value:2,label:"Tue"},{value:3,label:"Wed"},{value:4,label:"Thu"},{value:5,label:"Fri"},{value:6,label:"Sat"},{value:0,label:"Sun"}];function wg(t){return{title:t.title,description:t.description,status:t.status,userId:t.userId??null,polarity:t.polarity,frequency:t.frequency,targetCount:t.targetCount,weekDays:t.weekDays,linkedGoalIds:t.linkedGoalIds,linkedProjectIds:t.linkedProjectIds,linkedTaskIds:t.linkedTaskIds,linkedValueIds:t.linkedValueIds,linkedPatternIds:t.linkedPatternIds,linkedBehaviorIds:t.linkedBehaviorIds,linkedBeliefIds:t.linkedBeliefIds,linkedModeIds:t.linkedModeIds,linkedReportIds:t.linkedReportIds,linkedBehaviorId:t.linkedBehaviorId??"",rewardXp:t.rewardXp,penaltyXp:t.penaltyXp,generatedHealthEventTemplate:t.generatedHealthEventTemplate}}function vg({open:t,pending:s=!1,editingHabit:i,values:n,patterns:a,behaviors:r,beliefs:l,modes:d,reports:o,goals:x,projects:f,tasks:b,users:m,defaultUserId:h=null,onOpenChange:p,onSubmit:w}){const[v,I]=c.useState(pn),[k,S]=c.useState(null),[M,P]=c.useState({});c.useEffect(()=>{t&&(I(i?wg(i):{...pn,userId:h}),S(null),P({}))},[h,i,t]);const y=m.find(u=>u.id===h)??null,N=c.useMemo(()=>r.slice().sort((u,j)=>u.title.localeCompare(j.title)),[r]),A=u=>({linkedBehaviorIds:u,linkedBehaviorId:u[0]??""}),T=(u,j)=>u.includes(j)?u.filter(L=>L!==j):[...u,j],F=[{id:"intent",eyebrow:"Habit",title:"Name the recurring move",description:"Use habits for recurring commitments and recurring slips. Keep the title concrete so the daily check-in never needs interpretation.",render:(u,j)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Title",error:M.title??null,children:e.jsx(ie,{value:u.title,onChange:L=>j({title:L.target.value}),placeholder:"Train lower body"})}),e.jsx(Y,{label:"Description",children:e.jsx(Ce,{value:u.description,onChange:L=>j({description:L.target.value}),placeholder:"Write the habit description in Markdown. Define what counts, edge cases, and examples."})}),e.jsx(is,{value:u.userId,users:m,onChange:L=>j({userId:L}),label:"Owner user",defaultLabel:ss(y),help:"Habits can be owned by humans or bots. When one scoped user is active, Forge uses that as the default."})]})},{id:"shape",eyebrow:"Shape",title:"Set direction and cadence",description:"Forge uses polarity to decide whether doing the habit is good or bad, and cadence to know when it should show up.",render:(u,j)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Polarity",children:e.jsx(tt,{value:u.polarity,onChange:L=>j({polarity:L}),options:[{value:"positive",label:"Positive",description:"Doing it is aligned and should award XP."},{value:"negative",label:"Negative",description:"Doing it is a slip and should cost XP."}],columns:2})}),e.jsx(Y,{label:"Frequency",children:e.jsx(tt,{value:u.frequency,onChange:L=>j({frequency:L}),options:[{value:"daily",label:"Daily",description:"Track against each day."},{value:"weekly",label:"Weekly",description:"Track only on the selected weekdays."}],columns:2})}),u.frequency==="weekly"?e.jsx(Y,{label:"Weekdays",error:M.weekDays??null,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:fg.map(L=>{const q=u.weekDays.includes(L.value);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${q?"bg-white/16 text-white":"bg-white/6 text-white/58 hover:bg-white/10 hover:text-white"}`,onClick:()=>j({weekDays:q?u.weekDays.filter(G=>G!==L.value):[...u.weekDays,L.value].sort()}),children:L.label},L.value)})})}):null,e.jsx(Y,{label:"Status",children:e.jsx(tt,{value:u.status,onChange:L=>j({status:L}),options:[{value:"active",label:"Active",description:"Show it in the daily operating flow."},{value:"paused",label:"Paused",description:"Keep it visible but not currently due."},{value:"archived",label:"Archived",description:"Keep the record but retire it from active work."}]})})]})},{id:"generation",eyebrow:"Generation",title:"Decide whether this habit should create a workout record",description:"Use this when a completed habit should generate a structured sports or recovery session in Forge, then reconcile with HealthKit later if the same session gets imported.",render:(u,j)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Generate workout record",children:e.jsx(tt,{value:u.generatedHealthEventTemplate.enabled?"enabled":"disabled",onChange:L=>j({generatedHealthEventTemplate:{...u.generatedHealthEventTemplate,enabled:L==="enabled"}}),options:[{value:"disabled",label:"Disabled",description:"This habit only affects the habit ledger."},{value:"enabled",label:"Enabled",description:"A completed check-in creates a workout or recovery session."}],columns:2})}),u.generatedHealthEventTemplate.enabled?e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Workout type",children:e.jsx(ie,{value:u.generatedHealthEventTemplate.workoutType,onChange:L=>j({generatedHealthEventTemplate:{...u.generatedHealthEventTemplate,workoutType:L.target.value}}),placeholder:"mobility, walk, strength, recovery"})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Y,{label:"Duration (minutes)",children:e.jsx(ie,{type:"number",min:1,max:1440,value:u.generatedHealthEventTemplate.durationMinutes,onChange:L=>j({generatedHealthEventTemplate:{...u.generatedHealthEventTemplate,durationMinutes:Number(L.target.value)||45}})})}),e.jsx(Y,{label:"Workout XP",children:e.jsx(ie,{type:"number",min:0,max:500,value:u.generatedHealthEventTemplate.xpReward,onChange:L=>j({generatedHealthEventTemplate:{...u.generatedHealthEventTemplate,xpReward:Number(L.target.value)||0}})})})]}),e.jsx(Y,{label:"Generated session note",children:e.jsx(Ce,{value:u.generatedHealthEventTemplate.notesTemplate,onChange:L=>j({generatedHealthEventTemplate:{...u.generatedHealthEventTemplate,notesTemplate:L.target.value}}),placeholder:"Morning routine session generated from habit completion."})})]}):null]})},{id:"links",eyebrow:"Links",title:"Connect the habit to real Forge work",description:"Link habits to the goals, projects, and tasks they support so they stay anchored in the same operating graph as everything else.",render:(u,j)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Goals",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:x.map(L=>{const q=u.linkedGoalIds.includes(L.id);return e.jsx("button",{type:"button",onClick:()=>j({linkedGoalIds:T(u.linkedGoalIds,L.id)}),children:e.jsx(ke,{kind:"goal",label:L.title,gradient:q,className:q?"":"opacity-75"})},L.id)})})}),e.jsx(Y,{label:"Projects",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:f.map(L=>{const q=u.linkedProjectIds.includes(L.id);return e.jsx("button",{type:"button",onClick:()=>j({linkedProjectIds:T(u.linkedProjectIds,L.id)}),children:e.jsx(ke,{kind:"project",label:L.title,gradient:q,className:q?"":"opacity-75"})},L.id)})})}),e.jsx(Y,{label:"Tasks",children:e.jsx("div",{className:"flex max-h-48 flex-wrap gap-2 overflow-y-auto",children:b.map(L=>{const q=u.linkedTaskIds.includes(L.id);return e.jsx("button",{type:"button",onClick:()=>j({linkedTaskIds:T(u.linkedTaskIds,L.id)}),children:e.jsx(ke,{kind:"task",label:L.title,gradient:q,className:q?"":"opacity-75",wrap:!0})},L.id)})})}),e.jsx(Y,{label:"Values",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(L=>{const q=u.linkedValueIds.includes(L.id);return e.jsx("button",{type:"button",onClick:()=>j({linkedValueIds:T(u.linkedValueIds,L.id)}),children:e.jsx(ke,{kind:"value",label:L.title,gradient:q,className:q?"":"opacity-75"})},L.id)})})}),e.jsx(Y,{label:"Patterns",children:e.jsx("div",{className:"flex max-h-44 flex-wrap gap-2 overflow-y-auto",children:a.map(L=>{const q=u.linkedPatternIds.includes(L.id);return e.jsx("button",{type:"button",onClick:()=>j({linkedPatternIds:T(u.linkedPatternIds,L.id)}),children:e.jsx(ke,{kind:"pattern",label:L.title,gradient:q,className:q?"":"opacity-75",wrap:!0})},L.id)})})})]})},{id:"reward",eyebrow:"Reward",title:"Link the behavior and XP logic",description:"Habits can point back to a Psyche behavior. Reward XP is granted for aligned outcomes; penalty XP is applied for misaligned ones.",render:(u,j)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Linked behavior",children:e.jsx("div",{className:"flex max-h-44 flex-wrap gap-2 overflow-y-auto",children:N.map(L=>{const q=u.linkedBehaviorIds.includes(L.id);return e.jsx("button",{type:"button",onClick:()=>j(A(T(u.linkedBehaviorIds,L.id))),children:e.jsx(ke,{kind:"behavior",label:L.title,gradient:q,className:q?"":"opacity-75",wrap:!0})},L.id)})})}),e.jsx(Y,{label:"Beliefs",children:e.jsx("div",{className:"flex max-h-44 flex-wrap gap-2 overflow-y-auto",children:l.map(L=>{const q=u.linkedBeliefIds.includes(L.id);return e.jsx("button",{type:"button",onClick:()=>j({linkedBeliefIds:T(u.linkedBeliefIds,L.id)}),children:e.jsx(ke,{kind:"belief",label:L.statement,gradient:q,className:q?"":"opacity-75",wrap:!0})},L.id)})})}),e.jsx(Y,{label:"Modes",children:e.jsx("div",{className:"flex max-h-44 flex-wrap gap-2 overflow-y-auto",children:d.map(L=>{const q=u.linkedModeIds.includes(L.id);return e.jsx("button",{type:"button",onClick:()=>j({linkedModeIds:T(u.linkedModeIds,L.id)}),children:e.jsx(ke,{kind:"mode",label:L.title,gradient:q,className:q?"":"opacity-75",wrap:!0})},L.id)})})}),e.jsx(Y,{label:"Reports",children:e.jsx("div",{className:"flex max-h-44 flex-wrap gap-2 overflow-y-auto",children:o.map(L=>{const q=u.linkedReportIds.includes(L.id);return e.jsx("button",{type:"button",onClick:()=>j({linkedReportIds:T(u.linkedReportIds,L.id)}),children:e.jsx(ke,{kind:"report",label:L.title,gradient:q,className:q?"":"opacity-75",wrap:!0})},L.id)})})}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[e.jsx(Y,{label:"Target count",error:M.targetCount??null,children:e.jsx(ie,{type:"number",value:u.targetCount,onChange:L=>j({targetCount:Number(L.target.value)||1})})}),e.jsx(Y,{label:"Reward XP",error:M.rewardXp??null,children:e.jsx(ie,{type:"number",value:u.rewardXp,onChange:L=>j({rewardXp:Number(L.target.value)||1})})}),e.jsx(Y,{label:"Penalty XP",error:M.penaltyXp??null,children:e.jsx(ie,{type:"number",value:u.penaltyXp,onChange:L=>j({penaltyXp:Number(L.target.value)||1})})})]})]})}];return e.jsx(it,{open:t,onOpenChange:p,eyebrow:"Habit",title:i?"Edit habit":"Create habit",description:"Habits are recurring commitments or recurring slips with explicit XP consequences.",value:v,onChange:I,steps:F,pending:s,pendingLabel:i?"Save habit":"Create habit",submitLabel:i?"Save habit":"Create habit",error:k,onSubmit:async()=>{S(null);const u=Yh.safeParse(v);if(!u.success){P(Object.fromEntries(Object.entries(u.error.flatten().fieldErrors).map(([j,L])=>[j,L==null?void 0:L[0]]))),S("Some habit fields still need attention.");return}P({});try{await w(u.data,i==null?void 0:i.id),I(pn),p(!1)}catch(j){S(j instanceof Error?j.message:"Habit update failed.")}}})}const yg=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],jg=["S","M","T","W","T","F","S"];function Ng(t){return t.frequency==="daily"?`${t.targetCount}x daily`:`${t.targetCount}x weekly · ${t.weekDays.map(s=>yg[s]).join(", ")}`}function qi(t){return t.toISOString().slice(0,10)}function ac(t){const[s,i,n]=t.split("-").map(Number);return new Date(Date.UTC(s,i-1,n))}function nc(t){return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()))}function la(t,s){const i=new Date(t);return i.setUTCDate(i.getUTCDate()+s),i}function _l(t){const s=nc(t),i=(s.getUTCDay()+6)%7;return s.setUTCDate(s.getUTCDate()-i),s}function Li(t){const s=typeof t=="string"?ac(t):t;return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",timeZone:"UTC"}).format(s)}function Rn(t,s){return t.polarity==="positive"&&s==="done"||t.polarity==="negative"&&s==="missed"}function zn(t,s){return t.polarity==="positive"?s==="done"?"Done":"Missed":s==="done"?"Performed":"Resisted"}function rc(t){const s=qi(new Date),i=t.checkIns.find(n=>n.dateKey===s)??null;return t.dueToday?{tone:"pending",label:t.frequency==="daily"?"Waiting for today":"Awaiting this week's check-in",cardClass:"border-amber-300/24 shadow-[0_0_0_1px_rgba(251,191,36,0.12)]",overlayClass:"bg-[radial-gradient(circle_at_top_right,rgba(251,191,36,0.18),transparent_44%)]",pillClass:"border border-amber-300/16 bg-amber-300/12 text-amber-100"}:i?Rn(t,i.status)?{tone:"aligned",label:`${zn(t,i.status)} today`,cardClass:"border-emerald-300/20 shadow-[0_0_0_1px_rgba(52,211,153,0.08)]",overlayClass:"bg-[radial-gradient(circle_at_top_right,rgba(52,211,153,0.16),transparent_44%)]",pillClass:"border border-emerald-300/16 bg-emerald-300/12 text-emerald-100"}:{tone:"unaligned",label:`${zn(t,i.status)} today`,cardClass:"border-rose-300/20 shadow-[0_0_0_1px_rgba(251,113,133,0.08)]",overlayClass:"bg-[radial-gradient(circle_at_top_right,rgba(251,113,133,0.16),transparent_44%)]",pillClass:"border border-rose-300/16 bg-rose-300/12 text-rose-100"}:t.polarity==="positive"?{tone:"neutral",label:"No update due right now",cardClass:"",overlayClass:"bg-[radial-gradient(circle_at_top_right,rgba(52,211,153,0.09),transparent_40%)]",pillClass:"border border-white/10 bg-white/[0.06] text-white/62"}:{tone:"neutral",label:"No update due right now",cardClass:"",overlayClass:"bg-[radial-gradient(circle_at_top_right,rgba(251,113,133,0.09),transparent_40%)]",pillClass:"border border-white/10 bg-white/[0.06] text-white/62"}}function kg(t){return t>=10?{Icon:jm,className:"border border-amber-300/20 bg-amber-300/10 text-amber-100 shadow-[0_16px_32px_rgba(251,191,36,0.14)]",iconClass:"text-amber-200",valueClass:"text-amber-50",label:"Celebration pace"}:t>=5?{Icon:Nm,className:"border border-emerald-300/20 bg-emerald-300/10 text-emerald-100 shadow-[0_16px_32px_rgba(52,211,153,0.12)]",iconClass:"text-emerald-200",valueClass:"text-emerald-50",label:"Locked in"}:t>=1?{Icon:km,className:"border border-sky-300/18 bg-sky-300/10 text-sky-100 shadow-[0_16px_32px_rgba(125,211,252,0.1)]",iconClass:"text-sky-200",valueClass:"text-sky-50",label:"Building rhythm"}:{Icon:Sm,className:"border border-white/10 bg-white/[0.04] text-white/72 shadow-[0_16px_32px_rgba(15,23,42,0.16)]",iconClass:"text-white/55",valueClass:"text-white",label:"Cold start"}}function Sg(t){return t>=80?"bg-emerald-400/12 text-emerald-100":t>=50?"bg-amber-300/12 text-amber-100":"bg-rose-400/12 text-rose-100"}function Cg(t){var r;const s=new Date;if(t.frequency==="daily"){const l=nc(s),d=[];for(let o=-6;o<=0;o+=1){const x=la(l,o),f=qi(x),b=t.checkIns.find(p=>p.dateKey===f)??null,m=jg[x.getUTCDay()],h=o===0;d.push({id:f,label:m,current:h,actionDateKey:f,actionLabel:Li(x),state:b?Rn(t,b.status)?"aligned":"unaligned":"unknown",title:`${Li(x)} · ${b?zn(t,b.status):"Not informed"}`})}return{caption:"7-day rhythm",rangeLabel:"Past 7 days",showLabels:!0,startLabel:"",endLabel:"",cells:d}}const i=_l(s),n=new Map;for(const l of t.checkIns){const d=qi(_l(ac(l.dateKey))),o=n.get(d)??[];o.push(l),n.set(d,o)}const a=[];for(let l=-6;l<=0;l+=1){const d=la(i,l*7),o=qi(d),x=n.get(o)??[],f=t.weekDays.length>0?[...t.weekDays].sort((w,v)=>v-w)[0]:0,b=qi(la(d,f)),m=((r=x[0])==null?void 0:r.dateKey)??b,h=x.filter(w=>Rn(t,w.status)).length,p=x.length-h;a.push({id:o,label:"",current:l===0,actionDateKey:m,actionLabel:`Week of ${Li(d)}`,state:x.length===0?"unknown":h>=p?"aligned":"unaligned",title:`${Li(d)} week · ${x.length===0?"Not informed":h>=p?"Mostly aligned":"Mostly off track"}`})}return{caption:"7-week rhythm",rangeLabel:"Past 7 weeks",showLabels:!1,startLabel:Li(la(i,-42)),endLabel:"This week",cells:a}}function Ig(t,s){return re("h-8 w-full rounded-[10px] border transition",t==="aligned"&&"border-emerald-300/20 bg-emerald-300/75 shadow-[0_8px_18px_rgba(52,211,153,0.18)]",t==="unaligned"&&"border-rose-300/20 bg-rose-300/75 shadow-[0_8px_18px_rgba(251,113,133,0.18)]",t==="unknown"&&"border-white/8 bg-white/[0.08]",s&&"shadow-[0_0_0_1px_rgba(255,255,255,0.16)]")}function Tg({habit:t,onSelectCell:s}){const i=Cg(t),n=rc(t);return e.jsxs("div",{className:"w-full rounded-[18px] border border-white/8 bg-black/10 px-3 py-2.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"shrink-0",children:[e.jsx("div",{className:"font-label text-[10px] uppercase tracking-[0.16em] text-white/34",children:i.caption}),e.jsx("div",{className:"text-[11px] text-white/46",children:i.rangeLabel})]}),e.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:i.cells.map(a=>e.jsxs("button",{type:"button",className:"group flex min-w-0 flex-1 items-center gap-1 rounded-[10px] transition hover:bg-white/[0.04]",onClick:()=>s(t,a),title:`Log check-in for ${a.actionLabel}`,"aria-label":`Log check-in for ${a.actionLabel}`,children:[e.jsx("div",{className:re(Ig(a.state,a.current),"h-6 min-w-0 flex-1 rounded-[8px] transition duration-150 group-hover:-translate-y-0.5 group-hover:shadow-[0_10px_22px_rgba(15,23,42,0.22)]")}),i.showLabels?e.jsx("span",{className:"hidden text-[9px] uppercase tracking-[0.14em] text-white/26 transition group-hover:text-white/48 sm:inline",children:a.label}):null]},a.id))}),e.jsx("div",{className:re("shrink-0 rounded-full px-2.5 py-1 text-[10px] font-medium",n.pillClass),children:n.label})]}),i.showLabels?null:e.jsxs("div",{className:"mt-1 text-right text-[10px] uppercase tracking-[0.14em] text-white/26",children:[i.startLabel," - ",i.endLabel]})]})}function Pg(t){return t.polarity==="positive"?{alignedLabel:"Done",alignedDescription:"Log that the intended habit happened.",unalignedLabel:"Missed",unalignedDescription:"Log that the habit did not happen."}:{alignedLabel:"Resisted",alignedDescription:"Log that the unwanted behavior was resisted.",unalignedLabel:"Performed",unalignedDescription:"Log that the unwanted behavior happened."}}function Mg(){var q,G,Q,ne,H,_;const t=Ye(),s=We(),[i,n]=ft(),[a,r]=c.useState(null),[l,d]=c.useState(null),[o,x]=c.useState(null),[f,b]=c.useState(""),[m,h]=c.useState(!1),[p,w]=c.useState(null),v=xd(t.selectedUserIds),I=Nt(v),k=pe({queryKey:["forge-habits",...v],queryFn:async()=>(await Op({userIds:v})).habits}),S=pe({queryKey:["forge-psyche-overview",...v],queryFn:async()=>(await Ba(v)).overview});c.useEffect(()=>{i.get("create")==="1"&&(r(null),h(!0),n(U=>{const R=new URLSearchParams(U);return R.delete("create"),R},{replace:!0}))},[i,n]);const M=async()=>{await s.invalidateQueries({queryKey:["forge-habits"]}),await t.refresh()},P=ge({mutationFn:async({input:U,habitId:R})=>R?(await _p(R,U)).habit:(await Fp(U)).habit,onSuccess:async()=>{w(null),await M()},onError:U=>{w(U instanceof Error?U.message:"Habit save failed.")}}),y=ge({mutationFn:async({habitId:U,status:R,dateKey:C,note:J})=>zp(U,{status:R,dateKey:C,note:J}),onSuccess:async()=>{w(null),await M()},onError:U=>{w(U instanceof Error?U.message:"Habit check-in failed.")}}),N=ge({mutationFn:async U=>Rp(U),onSuccess:async()=>{w(null),await M()},onError:U=>{w(U instanceof Error?U.message:"Habit delete failed.")}}),A=c.useMemo(()=>(k.data??[]).filter(U=>U.status!=="archived"),[k.data]),T=c.useMemo(()=>A.filter(U=>U.dueToday),[A]),F=c.useMemo(()=>[...A].sort((U,R)=>U.dueToday!==R.dueToday?Number(R.dueToday)-Number(U.dueToday):U.dueToday&&R.dueToday?new Date(U.lastCheckInAt??0).getTime()-new Date(R.lastCheckInAt??0).getTime():U.title.localeCompare(R.title)),[A]),u=c.useMemo(()=>l?l.habit.checkIns.find(U=>U.dateKey===l.cell.actionDateKey)??null:null,[l]);if(c.useEffect(()=>{if(!l){x(null),b("");return}x((u==null?void 0:u.status)??null),b((u==null?void 0:u.note)??"")},[l,u]),k.error)throw k.error;const j=l?Pg(l.habit):null,L=o==="done"||o==="missed"||u!==null;return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{entityKind:"habit",title:e.jsx(_e,{kind:"habit",label:"Habits",variant:"heading",size:"lg"}),titleText:"Habits",description:"Habits track recurring commitments and recurring slips with explicit daily consequences, linked behaviors, and real XP movement.",badge:`${A.length} habits`,actions:e.jsxs(W,{onClick:()=>{r(null),h(!0)},children:[e.jsx(vt,{className:"size-4"}),"New habit"]})}),p?e.jsx(se,{className:"border-rose-400/22 bg-rose-400/8 text-rose-100",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ho,{className:"mt-0.5 size-4 shrink-0"}),e.jsx("div",{children:p})]})}):null,e.jsxs("section",{className:"grid gap-4 lg:grid-cols-3",children:[e.jsxs(se,{className:"border-amber-300/16 shadow-[0_0_0_1px_rgba(251,191,36,0.08)]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Due today"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-[var(--primary)]",children:T.length}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Habits that still need a check-in today."})]}),e.jsxs(se,{className:"border-emerald-300/16 shadow-[0_0_0_1px_rgba(52,211,153,0.08)]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Best streak"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-emerald-50",children:Math.max(0,...A.map(U=>U.streakCount))}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Longest current aligned streak across active habits."})]}),e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Average alignment"}),e.jsxs("div",{className:"mt-3 font-display text-4xl text-white",children:[A.length>0?Math.round(A.reduce((U,R)=>U+R.completionRate,0)/A.length):0,"%"]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Share of recent habit check-ins that matched the intended direction."})]})]}),k.isLoading?e.jsx(se,{children:"Loading habits..."}):A.length===0?e.jsx(gt,{eyebrow:"Habits",title:"No recurring habits yet",description:"Create the recurring commitments or recurring slips you want Forge to track explicitly. Positive habits pay out when completed. Negative habits invert that logic.",action:e.jsx(W,{onClick:()=>{r(null),h(!0)},children:"Create habit"})}):e.jsx("div",{className:"grid gap-4 xl:grid-cols-2",children:F.map(U=>{const R=rc(U),C=kg(U.streakCount),J=C.Icon,ee=Tt(t.snapshot.dashboard.notesSummaryByEntity,"habit",U.id).count,le=U.polarity==="positive"?{label:"Done",status:"done",Icon:Hi,className:"border-emerald-300/18 bg-emerald-300/14 text-emerald-50 shadow-[0_14px_28px_rgba(52,211,153,0.14)] hover:bg-emerald-300/20"}:{label:"Resisted",status:"missed",Icon:Bi,className:"border-emerald-300/18 bg-emerald-300/14 text-emerald-50 shadow-[0_14px_28px_rgba(52,211,153,0.14)] hover:bg-emerald-300/20"},oe=U.polarity==="positive"?{label:"Missed",status:"missed",Icon:Gr,className:"border-rose-300/18 bg-rose-300/14 text-rose-50 shadow-[0_14px_28px_rgba(251,113,133,0.14)] hover:bg-rose-300/20"}:{label:"Performed",status:"done",Icon:Vn,className:"border-rose-300/18 bg-rose-300/14 text-rose-50 shadow-[0_14px_28px_rgba(251,113,133,0.14)] hover:bg-rose-300/20"};return e.jsxs(se,{className:re("relative flex h-full flex-col overflow-hidden",R.cardClass),children:[e.jsx("div",{className:re("pointer-events-none absolute inset-0 opacity-100",R.overlayClass)}),e.jsxs("div",{className:"relative z-10 flex h-full flex-col",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(_e,{kind:"habit",label:U.title,variant:"heading",size:"sm"}),e.jsx($e,{user:U.user,compact:!0}),e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:U.status}),e.jsxs(O,{className:"bg-white/[0.08] text-white/72",children:[e.jsx(us,{className:"mr-1 size-3.5"}),Ng(U)]}),e.jsx(O,{className:U.polarity==="positive"?"bg-emerald-400/12 text-emerald-200":"bg-rose-400/12 text-rose-200",children:U.polarity==="positive"?"Positive":"Negative"}),U.dueToday?e.jsx(O,{className:"bg-amber-300/12 text-amber-100",children:"Needs check-in"}):null,U.linkedGoalIds.slice(0,1).map(ue=>{const me=t.snapshot.goals.find($=>$.id===ue);return me?e.jsxs(O,{className:"bg-amber-400/12 text-amber-100",children:["Goal · ",me.title]},me.id):null}),U.linkedProjectIds.slice(0,1).map(ue=>{const me=t.snapshot.dashboard.projects.find($=>$.id===ue);return me?e.jsxs(O,{className:"bg-sky-400/12 text-sky-100",children:["Project · ",me.title]},me.id):null}),U.linkedTaskIds.slice(0,1).map(ue=>{const me=t.snapshot.tasks.find($=>$.id===ue);return me?e.jsxs(O,{className:"bg-indigo-400/12 text-indigo-100",children:["Task · ",me.title]},me.id):null})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:U.description?e.jsx(es,{markdown:U.description,className:"[&>p]:text-sm [&>p]:leading-6 [&>blockquote]:text-sm [&>ul]:text-sm [&>ol]:text-sm"}):"No extra notes yet."})]}),e.jsxs("div",{className:"ml-auto inline-flex shrink-0 flex-col items-end gap-2 self-start text-right",children:[e.jsxs("div",{className:re("inline-flex flex-col self-end rounded-[20px] px-3 py-2.5 text-right",C.className),children:[e.jsxs("div",{className:"flex items-center justify-end gap-1.5 text-[10px] uppercase tracking-[0.16em]",children:[e.jsx("span",{children:"Streak"}),e.jsx(J,{className:re("size-3.5 shrink-0",C.iconClass)})]}),e.jsx("div",{className:re("mt-1.5 font-display text-[2.75rem] leading-none",C.valueClass),children:U.streakCount}),e.jsx("div",{className:"mt-1 text-[11px] leading-tight text-white/68",children:C.label})]}),e.jsxs("div",{className:"ml-auto grid grid-cols-2 gap-1.5",children:[e.jsx(W,{variant:"ghost",size:"sm",className:"h-7 min-w-0 rounded-[11px] border border-white/8 bg-white/[0.04] px-3 text-white/72 hover:bg-white/[0.08] hover:text-white",disabled:P.isPending,onClick:()=>{r(U),h(!0)},"aria-label":`Edit ${U.title}`,title:"Edit habit",children:e.jsx(Us,{className:"size-4"})}),e.jsx(W,{variant:"ghost",size:"sm",className:"h-7 min-w-0 rounded-[11px] border border-white/8 bg-white/[0.04] px-3 text-white/72 hover:bg-white/[0.08] hover:text-white",disabled:N.isPending,onClick:()=>{window.confirm(`Delete habit "${U.title}"?`)&&N.mutateAsync(U.id)},"aria-label":`Delete ${U.title}`,title:"Delete habit",children:e.jsx(bt,{className:"size-4"})})]})]})]}),e.jsxs("div",{className:"mt-auto grid gap-4 pt-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(O,{className:re("border-0",Sg(U.completionRate)),children:["Alignment ",U.completionRate,"%"]}),e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:U.polarity==="positive"?`+${U.rewardXp} XP done`:`+${U.rewardXp} XP resisted`}),e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:U.polarity==="positive"?`-${U.penaltyXp} XP missed`:`-${U.penaltyXp} XP performed`}),e.jsx(yt,{entityType:"habit",entityId:U.id,count:ee,className:"min-h-8 rounded-full border-white/8 bg-white/[0.04] px-3 py-1.5 text-[12px] text-white/68 hover:bg-white/[0.07]"}),U.linkedBehaviorTitles.slice(0,2).map(ue=>e.jsxs(O,{className:"bg-orange-400/12 text-orange-100",children:[e.jsx(Bi,{className:"mr-1 size-3.5"}),ue]},ue)),U.linkedProjectIds.slice(1,2).map(ue=>{const me=t.snapshot.dashboard.projects.find($=>$.id===ue);return me?e.jsxs(O,{className:"bg-sky-400/12 text-sky-100",children:["Project · ",me.title]},me.id):null}),U.linkedTaskIds.slice(1,2).map(ue=>{const me=t.snapshot.tasks.find($=>$.id===ue);return me?e.jsxs(O,{className:"bg-indigo-400/12 text-indigo-100",children:["Task · ",me.title]},me.id):null}),U.linkedValueIds.slice(0,2).map(ue=>{var $;const me=($=S.data)==null?void 0:$.values.find(ce=>ce.id===ue);return me?e.jsxs(O,{className:"bg-emerald-400/12 text-emerald-100",children:["Value · ",me.title]},me.id):null}),U.linkedPatternIds.slice(0,2).map(ue=>{var $;const me=($=S.data)==null?void 0:$.patterns.find(ce=>ce.id===ue);return me?e.jsxs(O,{className:"bg-cyan-400/12 text-cyan-100",children:["Pattern · ",me.title]},me.id):null}),U.linkedBeliefIds.slice(0,2).map(ue=>{var $;const me=($=S.data)==null?void 0:$.beliefs.find(ce=>ce.id===ue);return me?e.jsxs(O,{className:"bg-rose-400/12 text-rose-100",children:["Belief · ",me.statement]},me.id):null}),U.linkedModeIds.slice(0,2).map(ue=>{var $;const me=($=S.data)==null?void 0:$.modes.find(ce=>ce.id===ue);return me?e.jsxs(O,{className:"bg-violet-400/12 text-violet-100",children:["Mode · ",me.title]},me.id):null}),U.linkedReportIds.slice(0,2).map(ue=>{var $;const me=($=S.data)==null?void 0:$.reports.find(ce=>ce.id===ue);return me?e.jsxs(O,{className:"bg-fuchsia-400/12 text-fuchsia-100",children:["Report · ",me.title]},me.id):null})]}),e.jsx("div",{className:"grid gap-4",children:e.jsx(Tg,{habit:U,onSelectCell:(ue,me)=>{d({habit:ue,cell:me}),w(null)}})}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs(W,{variant:"secondary",className:re("h-11 rounded-[16px] border",le.className),disabled:y.isPending,onClick:()=>void y.mutateAsync({habitId:U.id,status:le.status}),children:[e.jsx(le.Icon,{className:"size-4"}),le.label]}),e.jsxs(W,{variant:"secondary",className:re("h-11 rounded-[16px] border",oe.className),disabled:y.isPending,onClick:()=>void y.mutateAsync({habitId:U.id,status:oe.status}),children:[e.jsx(oe.Icon,{className:"size-4"}),oe.label]})]})]})]})]},U.id)})}),e.jsx(vg,{open:m,pending:P.isPending,editingHabit:a,values:((q=S.data)==null?void 0:q.values)??[],patterns:((G=S.data)==null?void 0:G.patterns)??[],behaviors:((Q=S.data)==null?void 0:Q.behaviors)??[],beliefs:((ne=S.data)==null?void 0:ne.beliefs)??[],modes:((H=S.data)==null?void 0:H.modes)??[],reports:((_=S.data)==null?void 0:_.reports)??[],goals:t.snapshot.dashboard.goals,projects:t.snapshot.dashboard.projects,tasks:t.snapshot.tasks,users:t.snapshot.users,defaultUserId:(a==null?void 0:a.userId)??I,onOpenChange:h,onSubmit:async(U,R)=>{try{await P.mutateAsync({input:U,habitId:R})}catch(C){throw C instanceof qa,C}}}),e.jsx(Lt,{open:l!==null,onOpenChange:U=>{U||d(null)},children:e.jsxs(Dt,{children:[e.jsx($t,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.72)] backdrop-blur-xl"}),e.jsxs(Ot,{className:"fixed inset-x-4 top-1/2 z-50 mx-auto w-[min(42rem,calc(100vw-2rem))] max-w-[42rem] -translate-y-1/2 overflow-hidden rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(20,28,42,0.98),rgba(12,17,30,0.98))] shadow-[0_32px_90px_rgba(3,8,18,0.45)]",children:[e.jsx(Rt,{className:"sr-only",children:"Habit history"}),e.jsx(Gt,{className:"sr-only",children:"Log or revise a habit check-in for a selected history point."}),l&&j?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-b border-white/8 px-5 py-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Habit history"}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"text-lg font-semibold text-white",children:l.habit.title}),e.jsx(O,{className:"bg-white/[0.08] text-white/76",children:l.cell.actionLabel})]}),e.jsx("div",{className:"mt-3 text-sm text-white/56",children:l.habit.frequency==="daily"?"Log or revise the check-in for this specific day.":"Log or revise the representative check-in for this week."})]}),e.jsx(_t,{asChild:!0,children:e.jsx(W,{variant:"ghost",size:"sm",className:"h-10 w-10 rounded-[14px] border border-white/8 bg-white/[0.04] px-0 text-white/72 hover:bg-white/[0.08] hover:text-white","aria-label":"Close history modal",title:"Close",children:e.jsx(mt,{className:"size-4"})})})]})}),e.jsxs("div",{className:"grid gap-4 p-5",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("button",{type:"button","aria-pressed":o==="done",className:re("rounded-[22px] border px-4 py-4 text-left transition",o==="done"?"border-emerald-300/24 bg-emerald-300/14 text-white shadow-[0_16px_36px_rgba(52,211,153,0.14)]":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"),onClick:()=>x(U=>U==="done"?null:"done"),children:[e.jsxs("div",{className:"flex items-center gap-2 text-base font-medium",children:[e.jsx(Hi,{className:"size-4"}),j.alignedLabel]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:j.alignedDescription})]}),e.jsxs("button",{type:"button","aria-pressed":o==="missed",className:re("rounded-[22px] border px-4 py-4 text-left transition",o==="missed"?"border-rose-300/24 bg-rose-300/14 text-white shadow-[0_16px_36px_rgba(251,113,133,0.14)]":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"),onClick:()=>x(U=>U==="missed"?null:"missed"),children:[e.jsxs("div",{className:"flex items-center gap-2 text-base font-medium",children:[e.jsx(Gr,{className:"size-4"}),j.unalignedLabel]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:j.unalignedDescription})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-white",children:"Optional note"}),e.jsx(Ce,{value:f,onChange:U=>b(U.target.value),placeholder:"Add context for what happened on this day or week.",className:"min-h-24"})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-3",children:[e.jsx(W,{variant:"secondary",onClick:()=>d(null),disabled:y.isPending,children:"Cancel"}),e.jsx(W,{disabled:y.isPending||!L,pending:y.isPending,pendingLabel:"Saving",onClick:async()=>{L&&(o===null?(await qp(l.habit.id,l.cell.actionDateKey),await M()):await y.mutateAsync({habitId:l.habit.id,status:o,dateKey:l.cell.actionDateKey,note:f.trim()||void 0}),d(null))},children:"Save check-in"})]})]})]}):null]})]})})]})}const Eg={title:"",description:"",owner:"Albert",userId:null,goalId:"",projectId:"",priority:"medium",status:"focus",effort:"deep",energy:"steady",dueDate:"",points:60,tagIds:[],notes:[]},Ag={goalId:"",title:"",description:"",status:"active",userId:null,targetPoints:240,themeColor:"#c0c1ff",notes:[]},Lg={title:"",description:"",horizon:"year",status:"active",userId:null,targetPoints:400,themeColor:"#c8a46b",tagIds:[],notes:[]},Dg=["goal","project","task","tag","note","insight","psyche_value","behavior_pattern","behavior","belief_entry","mode_profile","mode_guide_session","event_type","emotion_definition","trigger_report"];function $g(t){return t!==null&&Dg.includes(t)}function fr(t,s,i=96){const n=t.trim()||s.trim();return n.length<=i?n:`${n.slice(0,i-1).trimEnd()}…`}function Og(t){return[t.summary.trim(),t.rationale.trim()?`Why it matters: ${t.rationale.trim()}`:""].filter(Boolean).join(`
|
|
4
|
+
|
|
5
|
+
`)}function wr(t){return!$g(t.entityType)||!t.entityId?null:{entityType:t.entityType,entityId:t.entityId,anchorKey:null}}function lc(t,s,i){var n,a;return t.entityType==="goal"&&t.entityId?t.entityId:t.entityType==="project"&&t.entityId?((n=s.find(r=>r.id===t.entityId))==null?void 0:n.goalId)??"":t.entityType==="task"&&t.entityId?((a=i.find(r=>r.id===t.entityId))==null?void 0:a.goalId)??"":""}function Fg(t,s){var i;return t.entityType==="project"&&t.entityId?t.entityId:t.entityType==="task"&&t.entityId?((i=s.find(n=>n.id===t.entityId))==null?void 0:i.projectId)??"":""}function oc(t,s,i){const n=[];return i.length>0&&n.push("task"),s.length>0&&n.push("project"),n.push("goal"),wr(t)&&n.push("note"),n}function _g(t,s,i){const n=oc(t,s,i);return n.includes("task")&&(t.entityType==="task"||t.entityType==="project")?"task":n.includes("project")&&t.entityType==="goal"?"project":n[0]??"goal"}function Rg(t,s,i){var d,o,x;const n=lc(t,s,i),r=Fg(t,i)||(n?((d=s.find(f=>f.goalId===n))==null?void 0:d.id)??"":"")||((o=s[0])==null?void 0:o.id)||"",l=r?((x=s.find(f=>f.id===r))==null?void 0:x.goalId)??n:n;return{...Eg,title:fr(t.recommendation,t.title),description:Og(t),goalId:l,projectId:r}}function zg(t,s,i,n){var l;const r=lc(t,i,n)||((l=s[0])==null?void 0:l.id)||"";return{...Ag,goalId:r,title:fr(t.title,t.recommendation),description:`${t.summary.trim()}
|
|
6
|
+
|
|
7
|
+
Recommendation: ${t.recommendation.trim()}`.trim()}}function qg(t){return{...Lg,title:fr(t.title,t.recommendation),description:`${t.summary.trim()}
|
|
8
|
+
|
|
9
|
+
Recommendation: ${t.recommendation.trim()}`.trim()}}function Bg(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(`
|
|
10
|
+
`)}function Rl(t,s,i,n){return{kind:_g(t,s,i),task:Rg(t,i,n),project:zg(t,s,i,n),goal:qg(t),noteMarkdown:Bg(t)}}function Kg(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 Ug({open:t,onOpenChange:s,insight:i,goals:n,projects:a,tasks:r,tags:l,pending:d=!1,onSubmit:o}){const x=c.useMemo(()=>oc(i,n,a),[n,i,a]),f=c.useMemo(()=>wr(i),[i]),[b,m]=c.useState(()=>Rl(i,n,a,r)),[h,p]=c.useState(null),[w,v]=c.useState({});c.useEffect(()=>{t&&(m(Rl(i,n,a,r)),p(null),v({}))},[n,i,t,a,r]);const I=b.task.projectId?a.find(P=>P.id===b.task.projectId)??null:null;c.useEffect(()=>{I&&b.task.goalId!==I.goalId&&m(P=>({...P,task:{...P.task,goalId:I.goalId}}))},[b.task.goalId,I]);const k=b.project.goalId?n.find(P=>P.id===b.project.goalId)??null:null,S=c.useMemo(()=>{var P,y,N;if(!f)return null;switch(f.entityType){case"goal":return((P=n.find(A=>A.id===f.entityId))==null?void 0:P.title)??"Linked goal";case"project":return((y=a.find(A=>A.id===f.entityId))==null?void 0:y.title)??"Linked project";case"task":return((N=r.find(A=>A.id===f.entityId))==null?void 0:N.title)??"Linked task";default:return`${f.entityType.replaceAll("_"," ")}`}},[n,a,f,r]),M=[{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:(P,y)=>e.jsx(Y,{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(tt,{value:P.kind,onChange:N=>y({kind:N}),options:x.map(N=>({value:N,...Kg(N)})),columns:x.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:(P,y)=>P.kind==="task"?e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Task title",error:w.title??null,children:e.jsx(ie,{value:P.task.title,onChange:N=>y({task:{...P.task,title:N.target.value}}),placeholder:"Turn the recommendation into a task"})}),e.jsx(Y,{label:"Description",children:e.jsx(Ce,{value:P.task.description,onChange:N=>y({task:{...P.task,description:N.target.value}}),placeholder:"Add the operational context for this task."})}),e.jsx(Y,{label:"Project",error:w.projectId??null,children:e.jsx("div",{className:"grid gap-3",children:a.map(N=>{const A=N.id===P.task.projectId;return e.jsxs("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${A?"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:{...P.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(ke,{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(Y,{label:"Owner",error:w.owner??null,children:e.jsx(ie,{value:P.task.owner,onChange:N=>y({task:{...P.task,owner:N.target.value}}),placeholder:"Albert"})}),e.jsx(Y,{label:"Tags",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:l.map(N=>{const A=P.task.tagIds.includes(N.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${A?"bg-white/16 text-white":"bg-white/6 text-white/58 hover:bg-white/10 hover:text-white"}`,onClick:()=>y({task:{...P.task,tagIds:A?P.task.tagIds.filter(T=>T!==N.id):[...P.task.tagIds,N.id]}}),children:N.name},N.id)})})})]}):P.kind==="project"?e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Project title",error:w.title??null,children:e.jsx(ie,{value:P.project.title,onChange:N=>y({project:{...P.project,title:N.target.value}}),placeholder:"Turn the insight into a project"})}),e.jsx(Y,{label:"Description",children:e.jsx(Ce,{value:P.project.description,onChange:N=>y({project:{...P.project,description:N.target.value}}),placeholder:"Describe the initiative this insight points to."})}),e.jsx(Y,{label:"Goal",error:w.goalId??null,children:e.jsx("div",{className:"grid gap-3",children:n.map(N=>{const A=N.id===P.project.goalId;return e.jsxs("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${A?"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:{...P.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)})})}),k?e.jsxs(Ps,{children:["This project will sit under the “",k.title,"” goal."]}):null]}):P.kind==="goal"?e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Goal title",error:w.title??null,children:e.jsx(ie,{value:P.goal.title,onChange:N=>y({goal:{...P.goal,title:N.target.value}}),placeholder:"Turn the insight into a life goal"})}),e.jsx(Y,{label:"Description",children:e.jsx(Ce,{value:P.goal.description,onChange:N=>y({goal:{...P.goal,description:N.target.value}}),placeholder:"Describe the strategic direction this insight suggests."})}),e.jsx(Y,{label:"Tags",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:l.map(N=>{const A=P.goal.tagIds.includes(N.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${A?"bg-white/16 text-white":"bg-white/6 text-white/58 hover:bg-white/10 hover:text-white"}`,onClick:()=>y({goal:{...P.goal,tagIds:A?P.goal.tagIds.filter(T=>T!==N.id):[...P.goal.tagIds,N.id]}}),children:N.name},N.id)})})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Linked note",description:"This stores the insight as durable Markdown evidence on the linked entity instead of creating a new work item.",hint:S?`This note will attach to ${S}.`:void 0,children:e.jsx(Ce,{value:P.noteMarkdown,onChange:N=>y({noteMarkdown:N.target.value}),placeholder:"Write the applied note content in Markdown",className:"min-h-64"})}),S?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:S})]}):null]})}];return e.jsx(it,{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:b,onChange:m,steps:M,submitLabel:"Apply insight",pending:d,error:h,onSubmit:async()=>{p(null),v({});try{if(b.kind==="task"){const P=fd.safeParse(b.task);if(!P.success){v(Object.fromEntries(Object.entries(P.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 o({kind:"task",input:P.data}),s(!1);return}if(b.kind==="project"){const P=bd.safeParse(b.project);if(!P.success){v(Object.fromEntries(Object.entries(P.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 o({kind:"project",input:P.data}),s(!1);return}if(b.kind==="goal"){const P=gd.safeParse(b.goal);if(!P.success){v(Object.fromEntries(Object.entries(P.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 o({kind:"goal",input:P.data}),s(!1);return}if(!b.noteMarkdown.trim()){p("The linked note needs Markdown content before it can be saved.");return}if(!f){p("This insight is not attached to a specific entity yet, so Forge cannot place a linked note for it.");return}await o({kind:"note",input:{contentMarkdown:b.noteMarkdown.trim()}}),s(!1)}catch(P){p(P instanceof Error?P.message:"Unable to apply this insight right now.")}}})}function zl(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 dc({open:t,onOpenChange:s,title:i="Store insight",description:n="Capture a clear observation, its recommendation, and where it belongs without dropping into a raw admin form.",eyebrow:a="Insight",pending:r=!1,submitLabel:l="Store insight",initialValue:d,lockedEntity:o,entityCandidates:x=[],onSubmit:f}){const[b,m]=c.useState(()=>zl(d,o)),[h,p]=c.useState(null);c.useEffect(()=>{t&&(m(zl(d,o)),p(null))},[d,o,t]);const w=c.useMemo(()=>{const k=new Set(["general"]);return x.forEach(S=>k.add(S.entityType)),o&&k.add(o.entityType),Array.from(k)},[x,o]),v=x.filter(k=>k.entityType===b.targetKind),I=[{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:(k,S)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{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(ie,{value:k.title,onChange:M=>S({title:M.target.value}),placeholder:"Weekly review needs a tighter end ritual"})}),e.jsx(Y,{label:"Timeframe",description:"Keep the horizon short and readable.",children:e.jsx(ie,{value:k.timeframeLabel,onChange:M=>S({timeframeLabel:M.target.value}),placeholder:"This week"})}),e.jsx(Y,{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:o?e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx(ke,{kind:o.kind,label:o.label}),o.description?e.jsx(Ps,{className:"mt-2",children:o.description}):null]}):e.jsxs(e.Fragment,{children:[e.jsx(tt,{value:k.targetKind,onChange:M=>S({targetKind:M,entityType:M==="general"?"":M,entityId:""}),options:w.map(M=>({value:M,label:M==="general"?"General insight":M==="trigger_report"?"Report":M.charAt(0).toUpperCase()+M.slice(1),description:M==="general"?"Store it in the broader insight feed.":`Attach it to a specific ${M==="trigger_report"?"report":M}.`})),columns:w.length>=3?3:2}),k.targetKind!=="general"?v.length>0?e.jsx("div",{className:"mt-4 grid gap-3 md:grid-cols-2",children:v.map(M=>{const P=k.entityType===M.entityType&&k.entityId===M.entityId;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:()=>S({entityType:M.entityType,entityId:M.entityId}),children:[e.jsx(ke,{kind:M.kind,label:M.label,compact:!0}),M.description?e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:M.description}):null]},`${M.entityType}:${M.entityId}`)})}):e.jsxs(Ps,{className:"mt-4",children:["No ",k.targetKind==="trigger_report"?"reports":`${k.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:(k,S)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{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(Ce,{value:k.summary,onChange:M=>S({summary:M.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(Y,{label:"Why this matters",description:"Optional context that helps explain the recommendation.",children:e.jsx(Ce,{value:k.rationale,onChange:M=>S({rationale:M.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:(k,S)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{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(Ce,{value:k.recommendation,onChange:M=>S({recommendation:M.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(Y,{label:"Confidence",description:"Choose how strongly this recommendation holds up right now.",children:e.jsx(tt,{value:String(k.confidence),onChange:M=>S({confidence:Number(M)}),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(it,{open:t,onOpenChange:s,eyebrow:a,title:i,description:n,value:b,onChange:m,steps:I,submitLabel:l,pending:r,error:h,onSubmit:async()=>{p(null);const k=Jh.safeParse({originType:b.originType,originAgentId:b.originAgentId,originLabel:b.originLabel,entityType:b.targetKind==="general"?"":b.entityType,entityId:b.targetKind==="general"?"":b.entityId,timeframeLabel:b.timeframeLabel,title:b.title,summary:b.summary,recommendation:b.recommendation,rationale:b.rationale,confidence:b.confidence,ctaLabel:b.ctaLabel});if(!k.success){p("This insight still needs a title, a summary, and a recommendation before it can be stored.");return}try{await f(k.data),s(!1)}catch(S){p(S instanceof Error?S.message:"Unable to store this insight right now.")}}})}function Qg(){var M,P,y,N;const t=We(),s=ht(),i=Ye(),n=Array.isArray(i.selectedUserIds)?i.selectedUserIds:[],{snapshot:a}=i,[r,l]=c.useState(!1),[d,o]=c.useState(null),x=pe({queryKey:["forge-insights",...n],queryFn:()=>Fu(n)}),f=ge({mutationFn:Md,onSuccess:async()=>{await t.invalidateQueries({queryKey:["forge-insights"]})}}),b=ge({mutationFn:({insightId:A,feedbackType:T})=>pl(A,T),onSuccess:async()=>{await t.invalidateQueries({queryKey:["forge-insights"]})}}),m=ge({mutationFn:({insightId:A})=>pp(A),onMutate:async({insightId:A})=>{await t.cancelQueries({queryKey:["forge-insights"]});const T=t.getQueryData(["forge-insights"]);if(T){const F=T.insights.feed.find(u=>u.id===A);t.setQueryData(["forge-insights"],{insights:{...T.insights,feed:T.insights.feed.filter(u=>u.id!==A),openCount:(F==null?void 0:F.status)==="open"?Math.max(0,T.insights.openCount-1):T.insights.openCount}})}return{previous:T}},onError:(A,T,F)=>{F!=null&&F.previous&&t.setQueryData(["forge-insights"],F.previous)},onSettled:async()=>{await t.invalidateQueries({queryKey:["forge-insights"]})}}),h=ge({mutationFn:async({insight:A,submission:T})=>{let F=null,u="Applied the insight.";if(T.kind==="task"){const j=await Ea(T.input);F=`/tasks/${j.task.id}`,u=`Created task: ${j.task.title}`}else if(T.kind==="project"){const j=await $d(T.input);F=`/projects/${j.project.id}`,u=`Created project: ${j.project.title}`}else if(T.kind==="goal"){const j=await Dd(T.input);F=`/goals/${j.goal.id}`,u=`Created goal: ${j.goal.title}`}else{const j=wr(A);if(!j)throw new Error("This insight is not linked to a concrete entity yet, so Forge cannot attach a linked note to it.");await mr({contentMarkdown:T.input.contentMarkdown,links:[j]}),F=Zd(j.entityType,j.entityId),u="Created a linked note from the insight."}return await pl(A.id,"applied",u),{href:F}},onSuccess:async({href:A})=>{await Promise.all([t.invalidateQueries({queryKey:["forge-insights"]}),t.invalidateQueries({queryKey:["forge-snapshot"]}),t.invalidateQueries({queryKey:["forge-xp-metrics"]}),t.invalidateQueries({queryKey:["forge-reward-ledger"]}),t.invalidateQueries({queryKey:["notes-index"]})]),o(null),A&&s(A)}}),p=(M=x.data)==null?void 0:M.insights,w=c.useMemo(()=>[...a.goals.slice(0,8).map(A=>({entityType:"goal",entityId:A.id,kind:"goal",label:A.title,description:A.description})),...a.projects.slice(0,8).map(A=>({entityType:"project",entityId:A.id,kind:"project",label:A.title,description:A.goalTitle})),...a.tasks.slice(0,10).map(A=>({entityType:"task",entityId:A.id,kind:"task",label:A.title,description:A.status.replaceAll("_"," ")}))],[a.goals,a.projects,a.tasks]),v=b.isPending?((P=b.variables)==null?void 0:P.insightId)??null:null,I=m.isPending?((y=m.variables)==null?void 0:y.insightId)??null:null,k=h.isPending?((N=h.variables)==null?void 0:N.insight.id)??null:null,S=a.metrics.topGoalId?a.goals.find(A=>A.id===a.metrics.topGoalId)??null:null;return x.isLoading?e.jsx(xt,{eyebrow:"Insights",title:"Loading the insight feed",description:"Pulling coaching, momentum analysis, and stored recommendations."}):x.isError||!p?e.jsx(Oe,{eyebrow:"Insights",error:x.error,onRetry:()=>void t.invalidateQueries({queryKey:["forge-insights"]})}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{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(se,{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(A=>e.jsxs("div",{className:"rounded-[16px] bg-white/[0.04] p-3",children:[e.jsx("div",{className:"h-12 rounded-[12px]",style:{background:A.intensity>=4?"rgba(192,193,255,0.95)":A.intensity===3?"rgba(192,193,255,0.7)":A.intensity===2?"rgba(192,193,255,0.45)":A.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:A.label})]},A.id))})]}),e.jsxs(se,{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(Xe,{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(id,{width:"100%",height:"100%",minWidth:280,minHeight:288,children:e.jsxs(kh,{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(ad,{dataKey:"label",tick:{fill:"rgba(255,255,255,0.42)",fontSize:11}}),e.jsx(nd,{hide:!0}),e.jsx(Vr,{dataKey:"xp",stroke:"#c0c1ff",fill:"url(#insight-xp)",strokeWidth:2}),e.jsx(Vr,{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(Xe,{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(Xe,{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(se,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{className:"bg-white/[0.08] text-white/60",children:"Deterministic coaching"}),e.jsx(Xe,{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}),S?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:S.title})]}),e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>s(`/goals/${S.id}`),children:"Open goal"})]}):null]})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(se,{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(se,{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(A=>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:A.title}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:A.summary}),A.user?e.jsx("div",{className:"mt-3",children:e.jsx($e,{user:A.user,compact:!0})}):null]}),e.jsx(O,{className:"text-white/70",children:A.status})]}),e.jsx("div",{className:"mt-3 text-sm text-white/58",children:A.recommendation}),e.jsxs("div",{className:"mt-3 text-xs uppercase tracking-[0.16em] text-white/38",children:[A.originLabel??A.originType," · confidence ",Math.round(A.confidence*100),"%"]}),A.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:A.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:[A.status!=="accepted"?e.jsx(W,{variant:"secondary",pending:v===A.id,onClick:()=>void b.mutateAsync({insightId:A.id,feedbackType:"accepted"}),children:"Accept"}):null,e.jsx(W,{pending:k===A.id,onClick:()=>o(A),children:"Apply"}),e.jsx(W,{variant:"ghost",pending:I===A.id,onClick:()=>void m.mutateAsync({insightId:A.id}),children:"Dismiss"})]})]})]},A.id))})]})]})]}),e.jsx(dc,{open:r,onOpenChange:l,entityCandidates:w,pending:f.isPending,onSubmit:async A=>{await f.mutateAsync(A)}}),d?e.jsx(Ug,{open:!!d,onOpenChange:A=>{A||o(null)},insight:d,goals:a.goals,projects:a.projects,tasks:a.tasks,tags:a.tags,pending:h.isPending,onSubmit:async A=>{await h.mutateAsync({insight:d,submission:A})}}):null]})}const hs=["backlog","focus","in_progress","blocked","done"];function cc(t){return t.startsWith("lane:")||t.includes(":lane:")}function Wg(t){var s,i;return((i=(s=t.data)==null?void 0:s.current)==null?void 0:i.type)==="lane"||cc(String(t.id))}function Gg(t){var s,i;return((i=(s=t.data)==null?void 0:s.current)==null?void 0:i.type)==="trash"}function Hg(t,s){const i=Math.max(0,Math.min(t.right,s.right)-Math.max(t.left,s.left)),n=Math.max(0,Math.min(t.bottom,s.bottom)-Math.max(t.top,s.top));return i*n}const Xg=t=>{const s=Th(t),i=s.find(l=>{const d=t.droppableContainers.find(o=>o.id===l.id);return d?Gg(d):!1});if(i)return[i];const n=s.find(l=>cc(String(l.id)));if(n)return[n];const r=t.droppableContainers.filter(l=>Wg(l)).map(l=>{const d=t.droppableRects.get(l.id);if(!d)return null;const o=Hg(t.collisionRect,d);return o<=0?null:{id:l.id,data:{droppableContainer:l,value:o}}}).filter(Boolean).sort((l,d)=>{var o,x;return(((o=d==null?void 0:d.data)==null?void 0:o.value)??0)-(((x=l==null?void 0:l.data)==null?void 0:x.value)??0)});return r.length>0?r:s.length>0?s:Ph(t)};function mc({task:t,goal:s,tags:i,isSelected:n,isDragging:a=!1,isOverlay:r=!1,style:l,setNodeRef:d,dragAttributes:o,dragListeners:x,isMobile:f=!1,onSelect:b,onStartTask:m,onQuickReopen:h,onStepTask:p,onOpenTask:w,onEditTask:v,notesSummaryByEntity:I}){const{t:k,formatDate:S}=at(),M=hs[hs.indexOf(t.status)-1]??null,P=hs[hs.indexOf(t.status)+1]??null,y=Tt(I,"task",t.id).count;return e.jsxs("article",{ref:d,style:l,className:re("w-full max-w-full min-w-0 overflow-hidden rounded-[18px] p-3 shadow-[inset_0_0_0_1px_rgba(255,255,255,0.04)] transition cursor-grab active:cursor-grabbing",f&&"touch-none select-none",r&&"rotate-[0.5deg] bg-[linear-gradient(180deg,rgba(192,193,255,0.24),rgba(192,193,255,0.1))] shadow-[0_28px_80px_rgba(8,12,24,0.42),inset_0_0_0_1px_rgba(192,193,255,0.26)]",a&&!r&&"opacity-35 shadow-[inset_0_0_0_1px_rgba(255,255,255,0.02)]",n?"bg-[linear-gradient(180deg,rgba(192,193,255,0.18),rgba(192,193,255,0.06))] shadow-[0_16px_40px_rgba(8,12,24,0.32),inset_0_0_0_1px_rgba(192,193,255,0.26)]":"bg-white/5"),"data-dragging":a?"true":"false","data-testid":`task-card-${t.id}`,onClick:()=>b(t.id),...o,...x,children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx(O,{className:"shrink-0 text-[11px] text-[var(--tertiary)]",children:t.priority}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[v?e.jsx("button",{type:"button","aria-label":`Edit ${t.title}`,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:N=>{N.preventDefault(),N.stopPropagation(),v(t.id)},children:e.jsx(Us,{className:"size-3.5"})}):null,w?e.jsx("button",{type:"button","aria-label":`Open ${t.title} details`,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:N=>{N.preventDefault(),N.stopPropagation(),w(t.id)},children:e.jsx(Ni,{className:"size-3.5"})}):null,f?e.jsxs("div",{className:"flex items-center gap-1",onClick:N=>N.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:!M,onClick:()=>{M&&(p==null||p(t.id,"previous"))},children:e.jsx(_a,{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:!P,onClick:()=>{P&&(p==null||p(t.id,"next"))},children:e.jsx(Si,{className:"size-3.5"})})]}):null,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:N=>{N.preventDefault(),N.stopPropagation(),m==null||m(t.id)},children:e.jsx(Cs,{className:"size-4 fill-current"})}):null,e.jsxs("span",{className:"text-[11px] text-white/44",children:[t.points," xp"]})]})]}),e.jsx(_e,{kind:"task",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||k("common.executionBoard.noExecutionNote")}),e.jsxs("div",{className:"mt-2.5 flex min-w-0 flex-wrap gap-1.5",children:[s?e.jsx(ke,{kind:"goal",label:s.title,compact:!0,wrap:!0,className:"min-w-0 max-w-full"}):null,e.jsx($e,{user:t.user,compact:!0}),e.jsx(yt,{entityType:"task",entityId:t.id,count:y}),t.time.totalCreditedSeconds>0?e.jsxs(O,{className:"bg-white/8 text-white/72",children:[Math.floor(t.time.totalCreditedSeconds/60)," min"]}):null,t.time.activeRunCount>0?e.jsxs(O,{className:"bg-emerald-500/12 text-emerald-200",children:[t.time.activeRunCount," live"]}):null,i.slice(0,2).map(N=>e.jsx(O,{className:"bg-white/8",style:{color:N.color},children:N.name},N.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"&&h?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:N=>{N.preventDefault(),N.stopPropagation(),h(t.id)},children:k("common.executionBoard.reopen")}):null,e.jsx("span",{children:S(t.dueDate)})]})]})]})}function ql(t){const{task:s,sortableId:i}=t,{attributes:n,listeners:a,setNodeRef:r,transform:l,transition:d,isDragging:o}=md({id:i,data:{type:"task",taskId:s.id,status:s.status}});return e.jsx(mc,{...t,setNodeRef:r,dragAttributes:n,dragListeners:a,isDragging:o,isMobile:t.isMobile,onStartTask:t.onStartTask,onStepTask:t.onStepTask,notesSummaryByEntity:t.notesSummaryByEntity,style:{transform:hd.Transform.toString(l),transition:d}})}function Bl({droppableId:t,status:s,title:i,detail:n,count:a,dragging:r,children:l}){const{setNodeRef:d,isOver:o}=cd({id:t,data:{type:"lane",status:s}});return e.jsx("div",{ref:d,className:re("w-full max-w-full min-w-0 overflow-hidden rounded-[24px] transition",o&&"scale-[1.005]"),"data-lane-id":s,"data-testid":`kanban-lane-${s}`,"data-lane-hover":o?"true":"false",children:e.jsxs(se,{className:re("h-full w-full max-w-full min-w-0 overflow-hidden p-3 transition-[background-color,box-shadow,border-color,transform]",r&&"border border-white/8",o?"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:n}),e.jsx("h3",{className:"mt-1 break-words text-[1.45rem] leading-[1] text-white",children:i})]}),e.jsx("div",{className:"shrink-0 font-display text-[1.45rem] text-[var(--primary)]",children:a})]}),e.jsx("div",{className:re("grid w-full max-w-full min-w-0 min-h-48 content-start gap-2 rounded-[18px] p-2 transition",o?"bg-[rgba(125,211,252,0.08)]":"bg-white/[0.02]"),children:l})]})})}function Jg({droppableId:t,title:s,detail:i}){const{setNodeRef:n,isOver:a}=cd({id:t,data:{type:"trash"}});return e.jsx("div",{ref:n,className:re("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",a?"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":a?"true":"false",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:re("flex size-12 items-center justify-center rounded-full border transition",a?"border-white/28 bg-white/12":"border-white/12 bg-white/6"),children:e.jsx(bt,{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:i})]})]})})}function hc({tasks:t,goals:s,tags:i,selectedTaskId:n,onMove:a,onSelectTask:r,onStartTask:l,onQuickReopenTask:d,onDeleteTask:o,onOpenTask:x,onEditTask:f,notesSummaryByEntity:b}){const{t:m}=at(),h=c.useId(),p=`${h}:trash`,[w,v]=c.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(max-width: 1023px)").matches),I=rd(ld(dd,{activationConstraint:{distance:6}})),[k,S]=c.useState(null),[M,P]=c.useState(null),[y,N]=c.useState(null),[A,T]=c.useState(()=>typeof window>"u"?!1:window.localStorage.getItem("forge.kanban-skip-delete-confirmation")==="true"),[F,u]=c.useState(!1),[j,L]=c.useState({}),q={backlog:{title:m("common.executionBoard.laneBacklogTitle"),detail:m("common.executionBoard.laneBacklogDetail")},focus:{title:m("common.executionBoard.laneFocusTitle"),detail:m("common.executionBoard.laneFocusDetail")},in_progress:{title:m("common.executionBoard.laneProgressTitle"),detail:m("common.executionBoard.laneProgressDetail")},blocked:{title:m("common.executionBoard.laneBlockedTitle"),detail:m("common.executionBoard.laneBlockedDetail")},done:{title:m("common.executionBoard.laneDoneTitle"),detail:m("common.executionBoard.laneDoneDetail")}},G=c.useMemo(()=>t.map(ee=>{const le=j[ee.id];return le?{...ee,status:le}:ee}),[j,t]),Q=k?G.find(ee=>ee.id===k)??null:null,ne=Q?s.find(ee=>ee.id===Q.goalId):void 0,H=Q?Q.tagIds.map(ee=>i.find(le=>le.id===ee)).filter(Boolean):[];c.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const ee=window.matchMedia("(max-width: 1023px)"),le=oe=>{v(oe?oe.matches:ee.matches)};return le(),typeof ee.addEventListener=="function"?(ee.addEventListener("change",le),()=>ee.removeEventListener("change",le)):(ee.addListener(le),()=>ee.removeListener(le))},[]),c.useEffect(()=>{if(!k){document.body.style.cursor="";return}return document.body.style.cursor="grabbing",()=>{document.body.style.cursor=""}},[k]),c.useEffect(()=>{L(ee=>{const le=new Set(t.map(me=>me.id));let oe=!1;const ue={};for(const[me,$]of Object.entries(ee)){const ce=t.find(E=>E.id===me);if(!le.has(me)||!ce||ce.status===$){oe=!0;continue}ue[me]=$}return oe?ue:ee})},[t]);function _(ee){var oe;const le=(oe=ee.active.data.current)==null?void 0:oe.taskId;typeof le=="string"&&S(le)}const U=ee=>{T(ee),typeof window<"u"&&window.localStorage.setItem("forge.kanban-skip-delete-confirmation","true")},R=async(ee,le)=>{if(o){N(ee.id);try{le&&U(!0),await o(ee.id),P(null),u(!1),L(oe=>{const ue={...oe};return delete ue[ee.id],ue})}finally{N(null)}}};async function C(ee){var z,K,je,V,D;const{active:le,over:oe}=ee;if(S(null),!oe||le.id===oe.id)return;const ue=typeof((z=le.data.current)==null?void 0:z.taskId)=="string"?le.data.current.taskId:String(le.id),me=G.find(X=>X.id===ue);if(!me)return;if(((K=oe.data.current)==null?void 0:K.type)==="trash"){if(!o)return;if(A){await R(me,!1);return}u(!1),P(me);return}const $=typeof((je=oe.data.current)==null?void 0:je.status)=="string"?oe.data.current.status:null,ce=typeof((V=oe.data.current)==null?void 0:V.taskId)=="string"?oe.data.current.taskId:String(oe.id),E=$??((D=G.find(X=>X.id===ce))==null?void 0:D.status)??me.status;if(E!==me.status&&hs.includes(E)){L(X=>({...X,[me.id]:E}));try{await a(me.id,E)}catch(X){throw L(he=>{const ye={...he};return delete ye[me.id],ye}),X}}}async function J(ee,le){const oe=G.find(ce=>ce.id===ee);if(!oe)return;const ue=hs.indexOf(oe.status),me=le==="previous"?ue-1:ue+1,$=hs[me]??null;if(!(!$||$===oe.status)){L(ce=>({...ce,[oe.id]:$}));try{await a(oe.id,$)}catch(ce){throw L(E=>{const z={...E};return delete z[oe.id],z}),ce}}}return e.jsxs(od,{sensors:I,collisionDetection:Xg,onDragStart:_,onDragCancel:()=>S(null),onDragEnd:ee=>void C(ee),children:[Q&&o?e.jsx(Jg,{droppableId:p,title:m("common.executionBoard.deleteDropTitle"),detail:m("common.executionBoard.deleteDropDetail")}):null,e.jsx("div",{className:"w-full max-w-full min-w-0 pb-2",children:w?e.jsx("div",{className:"grid w-full max-w-full min-w-0 gap-2",children:hs.map(ee=>{const le=G.filter(oe=>oe.status===ee);return e.jsx(Ln,{items:le.map(oe=>`${h}:task:${oe.id}`),strategy:Dn,children:e.jsxs(Bl,{droppableId:`${h}:lane:${ee}`,status:ee,title:q[ee].title,detail:q[ee].detail,count:le.length,dragging:k!==null,children:[le.map(oe=>e.jsx(ql,{sortableId:`${h}:task:${oe.id}`,task:oe,goal:s.find(ue=>ue.id===oe.goalId),tags:oe.tagIds.map(ue=>i.find(me=>me.id===ue)).filter(Boolean),isSelected:n===oe.id,isMobile:!0,onSelect:r,onStartTask:l,onQuickReopen:d,onStepTask:J,onOpenTask:x,onEditTask:f,notesSummaryByEntity:b},oe.id)),le.length===0?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:m("common.executionBoard.emptyLane")}):null]})},ee)})}):e.jsx("div",{className:"grid w-full min-w-0 gap-0.5 xl:grid-cols-[repeat(5,minmax(0,1fr))]",children:hs.map(ee=>{const le=G.filter(oe=>oe.status===ee);return e.jsx(Ln,{items:le.map(oe=>`${h}:task:${oe.id}`),strategy:Dn,children:e.jsxs(Bl,{droppableId:`${h}:lane:${ee}`,status:ee,title:q[ee].title,detail:q[ee].detail,count:le.length,dragging:k!==null,children:[le.map(oe=>e.jsx(ql,{sortableId:`${h}:task:${oe.id}`,task:oe,goal:s.find(ue=>ue.id===oe.goalId),tags:oe.tagIds.map(ue=>i.find(me=>me.id===ue)).filter(Boolean),isSelected:n===oe.id,onSelect:r,onStartTask:l,onQuickReopen:d,onStepTask:J,onOpenTask:x,onEditTask:f,notesSummaryByEntity:b},oe.id)),le.length===0?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:m("common.executionBoard.emptyLane")}):null]})},ee)})})}),e.jsx(Ih,{adjustScale:!1,dropAnimation:null,children:Q?e.jsx("div",{className:"w-[20rem] max-w-[calc(100vw-2rem)]",children:e.jsx(mc,{task:Q,goal:ne,tags:H,isSelected:n===Q.id,isDragging:!0,isOverlay:!0,isMobile:w,onSelect:()=>{},onStartTask:l,notesSummaryByEntity:b})}):null}),M?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(se,{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(bt,{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:m("common.executionBoard.deleteConfirmTitle")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/64",children:m("common.executionBoard.deleteConfirmDescription",{title:M.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:F,onChange:ee=>u(ee.target.checked),className:"size-4 rounded border-white/20 bg-transparent text-[var(--primary)]"}),e.jsx("span",{children:m("common.executionBoard.deleteConfirmCheckbox")})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap justify-end gap-3",children:[e.jsx(W,{variant:"secondary",onClick:()=>{P(null),u(!1)},children:m("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:y===M.id,pendingLabel:m("common.executionBoard.deletingTask"),onClick:()=>void R(M,F),children:m("common.executionBoard.deleteConfirmSubmit")})]})]})}):null]})}const Yg=Qo(t=>({selectedUserId:null,selectedGoalId:null,selectedTagIds:[],setUserId:s=>t({selectedUserId:s}),setGoal:s=>t({selectedGoalId:s}),toggleTag:s=>t(i=>({selectedTagIds:i.selectedTagIds.includes(s)?i.selectedTagIds.filter(n=>n!==s):[...i.selectedTagIds,s]})),reset:()=>t({selectedUserId:null,selectedGoalId:null,selectedTagIds:[]})}));function Vg(){var F;const{t}=at(),s=Ye(),i=ht(),n=We(),[a,r]=c.useState(((F=s.snapshot.tasks[0])==null?void 0:F.id)??null),[l,d]=c.useState(null),{selectedGoalId:o,selectedUserId:x,selectedTagIds:f,setGoal:b,setUserId:m,toggleTag:h,reset:p}=Yg(),w=s.snapshot.tasks.filter(u=>!(o&&u.goalId!==o||x&&u.userId!==x||f.length>0&&!f.every(j=>u.tagIds.includes(j)))),v=w.find(u=>u.id===a)??s.snapshot.tasks.find(u=>u.id===a)??null,I=l?s.snapshot.tasks.find(u=>u.id===l)??null:null,k=w.filter(u=>u.status==="blocked").length,S=w.filter(u=>u.status==="done").length,M=w.filter(u=>u.status==="focus"||u.status==="in_progress").length,P=s.snapshot.activeTaskRuns.length,y=Nt(s.selectedUserIds),N=async()=>{await Promise.all([n.invalidateQueries({queryKey:["forge-snapshot"]}),n.invalidateQueries({queryKey:["project-board"]}),n.invalidateQueries({queryKey:["task-context"]})])},A=ge({mutationFn:({taskId:u,patch:j})=>Yi(u,j),onSuccess:N}),T=ge({mutationFn:u=>hr(u),onSuccess:N});return s.snapshot.tasks.length===0?e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-5",children:[e.jsx(Ke,{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(gt,{eyebrow:t("common.kanban.heroEyebrow"),title:t("common.kanban.emptyTitle"),description:t("common.kanban.emptyDescription"),action:e.jsx(Le,{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(Ke,{title:"Kanban",description:"Move tasks between states, start work directly from the board, or open a task when you need to edit it.",badge:`${w.length} visible tasks`,actions:e.jsx(W,{size:"lg",onClick:()=>s.openStartWork(v?{taskId:v.id}:void 0),children:"Start work"})}),e.jsx(se,{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 what is not started, ready, active, blocked, or done, then move tasks where they belong."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(O,{className:"bg-white/[0.08] text-white/72",children:[M," ready or active"]}),e.jsxs(O,{className:"bg-white/[0.08] text-white/72",children:[k," blocked"]}),e.jsxs(O,{className:"bg-white/[0.08] text-white/72",children:[S," done"]}),e.jsxs(O,{className:"bg-white/[0.08] text-white/72",children:[P," live timer",P===1?"":"s"]})]})]})}),e.jsxs(se,{className:"min-w-0 overflow-hidden",children:[e.jsx("div",{className:"type-label text-white/40",children:"Filters"}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[e.jsx(O,{tone:"meta",className:"bg-white/[0.08] text-white/60",children:"Goal"}),e.jsx("button",{className:`interactive-tap max-w-full rounded-full px-4 py-2 text-sm ${o===null?"bg-white/[0.12] text-white":"bg-white/[0.04] text-white/58"}`,onClick:()=>b(null),children:"All goals"}),s.snapshot.goals.map(u=>e.jsx("button",{className:`interactive-tap min-w-0 max-w-full rounded-full px-4 py-2 text-sm ${o===u.id?"bg-white/[0.12] text-white":"bg-white/[0.04] text-white/58"}`,onClick:()=>b(o===u.id?null:u.id),children:e.jsx(_e,{kind:"goal",label:u.title,className:"max-w-full min-w-0",lines:2,labelClassName:"whitespace-normal text-left"})},u.id))]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(O,{tone:"meta",className:"bg-white/[0.08] text-white/60",children:"Owner"}),e.jsx("button",{className:`interactive-tap max-w-full rounded-full px-4 py-2 text-sm ${x===null?"bg-white/[0.12] text-white":"bg-white/[0.04] text-white/58"}`,onClick:()=>m(null),children:"Everyone"}),s.snapshot.users.map(u=>e.jsx("button",{className:`interactive-tap max-w-full rounded-full px-4 py-2 text-sm ${x===u.id?"bg-white/[0.12] text-white":"bg-white/[0.04] text-white/58"}`,onClick:()=>m(x===u.id?null:u.id),children:u.displayName},u.id))]}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[s.snapshot.tags.map(u=>e.jsx("button",{className:`interactive-tap max-w-full rounded-full px-4 py-2 text-sm ${f.includes(u.id)?"bg-white/[0.12] text-white":"bg-white/[0.04] text-white/58"}`,onClick:()=>h(u.id),children:u.name},u.id)),e.jsx("button",{className:"interactive-tap max-w-full rounded-full bg-white/[0.04] px-4 py-2 text-sm text-[var(--primary)]",onClick:p,children:"Reset"})]})]}),w.length===0?e.jsx(gt,{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:p,children:"Reset"})}):e.jsx(hc,{tasks:w,goals:s.snapshot.goals,tags:s.snapshot.tags,notesSummaryByEntity:s.snapshot.dashboard.notesSummaryByEntity,selectedTaskId:a,onMove:async(u,j)=>{await s.patchTaskStatus(u,j)},onQuickReopenTask:async u=>{await ur(u),await N()},onDeleteTask:async u=>{await T.mutateAsync(u),r(j=>{var L;return j!==u?j:((L=w.find(q=>q.id!==u))==null?void 0:L.id)??null}),d(j=>j===u?null:j)},onStartTask:async u=>{await s.startTaskNow(u),r(u),await n.invalidateQueries({queryKey:["task-context",u]})},onSelectTask:u=>{r(u)},onOpenTask:u=>{i(`/tasks/${u}`)},onEditTask:u=>{d(u)}}),e.jsx(za,{open:I!==null,goals:s.snapshot.goals,projects:s.snapshot.dashboard.projects,tags:s.snapshot.tags,users:s.snapshot.users,editingTask:I,defaultUserId:(I==null?void 0:I.userId)??y,onOpenChange:u=>{u||d(null)},onSubmit:async(u,j)=>{j&&(await A.mutateAsync({taskId:j,patch:u}),d(null))}})]})}function Zg(t){return t.trim().toLowerCase()}function eb(t,s){return t.includes(s)?t:[...t,s]}function tb({entityOptions:t,selectedEntityValues:s,onSelectedEntityValuesChange:i,selectedTextTerms:n,onSelectedTextTermsChange:a,placeholder:r="Filter by linked entity or add free text"}){const[l,d]=c.useState(""),[o,x]=c.useState(!1),[f,b]=c.useState(0),m=Zg(l),h=c.useMemo(()=>s.map(M=>t.find(P=>P.value===M)).filter(Boolean),[t,s]),p=c.useMemo(()=>{const M=t.filter(P=>!s.includes(P.value));return m?M.filter(P=>`${P.label} ${P.description??""} ${P.searchText??""}`.toLowerCase().includes(m)).slice(0,8):M.slice(0,8)},[t,m,s]),w=l.trim().length>0&&!n.includes(l.trim()),v=M=>{i(eb(s,M)),d(""),b(0),x(!1)},I=(M=l)=>{const P=M.trim();!P||n.includes(P)||(a([...n,P]),d(""),b(0),x(!1))},k=M=>{i(s.filter(P=>P!==M))},S=M=>{a(n.filter(P=>P!==M))};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:()=>I(),disabled:!w,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:[h.length>0||n.length>0?e.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[h.map(M=>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:[M.kind?e.jsx(ke,{kind:M.kind,label:M.label,compact:!0,gradient:!1,className:"max-w-[16rem]"}):e.jsx(O,{className:"bg-white/[0.08] text-white/78",children:M.label}),e.jsx("button",{type:"button",className:"rounded-full text-white/50 transition hover:text-white",onClick:()=>k(M.value),"aria-label":`Remove ${M.label}`,children:e.jsx(mt,{className:"size-3.5"})})]},M.value)),n.map(M=>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(Hr,{className:"size-3.5"}),e.jsx("span",{className:"max-w-[16rem] truncate",children:M})]}),e.jsx("button",{type:"button",className:"rounded-full text-cyan-100/70 transition hover:text-white",onClick:()=>S(M),"aria-label":`Remove free-text filter ${M}`,children:e.jsx(mt,{className:"size-3.5"})})]},M))]}):null,n.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(dt,{className:"size-4 text-white/34"}),e.jsx("input",{value:l,onChange:M=>{d(M.target.value),x(!0),b(0)},onFocus:()=>x(!0),onBlur:()=>{window.setTimeout(()=>x(!1),120)},onKeyDown:M=>{if(M.key==="Backspace"&&!l){if(n.length>0){S(n[n.length-1]);return}s.length>0&&k(s[s.length-1]);return}if(M.key==="ArrowDown"){M.preventDefault(),x(!0),b(y=>p.length===0?0:Math.min(p.length-1,y+1));return}if(M.key==="ArrowUp"){M.preventDefault(),b(y=>Math.max(0,y-1));return}if(M.key==="Escape"){x(!1);return}if(M.key!=="Enter")return;M.preventDefault();const P=p[f];if(P){v(P.value);return}I()},placeholder:r,className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]}),o?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((M,P)=>e.jsx("button",{type:"button",className:re("flex w-full items-start justify-between gap-3 rounded-[18px] px-3 py-2.5 text-left transition",P===f?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>b(P),onMouseDown:y=>y.preventDefault(),onClick:()=>v(M.value),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:M.kind?e.jsx(ke,{kind:M.kind,label:M.label,compact:!0,gradient:!1}):M.label}),M.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/46",children:M.description}):null]})},M.value)),w?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:M=>M.preventDefault(),onClick:()=>I(),children:[e.jsx(Hr,{className:"size-4"}),e.jsxs("span",{className:"truncate",children:['Add free text "',l.trim(),'"']})]}):null,p.length===0&&!w?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 sb=new Set(["goal","project","task","strategy","habit","tag","psyche_value","behavior_pattern","behavior","belief_entry","mode_profile","trigger_report"]),Vt={goal:"goal",project:"project",task:"task",strategy:"strategy",habit:"habit",psyche_value:"value",behavior_pattern:"pattern",behavior:"behavior",belief_entry:"belief",mode_profile:"mode",trigger_report:"report"};function uc(t){return sb.has(t)}function At(t,s){return`${t}:${s}`}function oa(t){const s=t.indexOf(":");if(s<=0||s>=t.length-1)return null;const i=t.slice(0,s);return uc(i)?{entityType:i,entityId:t.slice(s+1)}:null}function Kl(t){return t!==null}function Ul(t){const s=t.getAll("linkedTo"),i=t.get("entityType"),n=t.get("entityId");return i&&n&&uc(i)&&s.unshift(At(i,n)),Array.from(new Set(s.map(a=>a.trim()).filter(Boolean)))}function ib(t){return Array.from(new Set(t.getAll("textTerms").map(s=>s.trim()).filter(Boolean)))}function ab(t){return ns(t.getAll("tags"))}function Di(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(i=>At(i.entityType,i.entityId)))??s,tags:ns((t==null?void 0:t.tags)??[]),destroyAtInput:tc((t==null?void 0:t.destroyAt)??null),destroyDelayValue:"",destroyDelayUnit:"days"}}function nb(t){return[...t].sort((s,i)=>s.label.localeCompare(i.label))}function Ql(t){return ec(t.destroyAtInput)??sc(t.destroyDelayValue,t.destroyDelayUnit)}function rb(){var ce,E,z,K,je,V,D;const t=ht(),s=We(),i=Ye(),[n,a]=ft(),[r,l]=c.useState(()=>Ul(n)),[d,o]=c.useState(()=>ab(n)),[x,f]=c.useState(()=>ib(n)),[b,m]=c.useState(n.get("author")??""),[h,p]=c.useState(n.get("updatedFrom")??""),[w,v]=c.useState(n.get("updatedTo")??""),[I,k]=c.useState(!1),[S,M]=c.useState(()=>Di(null,Ul(n))),[P,y]=c.useState(null),[N,A]=c.useState(null),[T,F]=c.useState(null),u=pe({queryKey:["forge-psyche-values"],queryFn:ls}),j=pe({queryKey:["forge-psyche-patterns"],queryFn:Xs}),L=pe({queryKey:["forge-psyche-behaviors"],queryFn:os}),q=pe({queryKey:["forge-psyche-beliefs"],queryFn:As}),G=pe({queryKey:["forge-psyche-modes"],queryFn:Ls}),Q=pe({queryKey:["forge-psyche-reports"],queryFn:Ti});c.useEffect(()=>{const X=new URLSearchParams;for(const he of r)X.append("linkedTo",he);for(const he of d)X.append("tags",he);for(const he of x)X.append("textTerms",he);b.trim()&&X.set("author",b.trim()),h&&X.set("updatedFrom",h),w&&X.set("updatedTo",w),a(X,{replace:!0})},[b,r,d,x,a,h,w]);const ne=c.useMemo(()=>{var he,ye,ze,fe,Pe,Ge;const X=[...i.snapshot.goals.map(Z=>({value:At("goal",Z.id),label:Z.title,description:Be(Z.description,Z.user,"Goal"),searchText:qe([Z.title,Z.description],Z),kind:Vt.goal})),...i.snapshot.dashboard.projects.map(Z=>({value:At("project",Z.id),label:Z.title,description:Be(`${Z.description}${Z.description?" · ":""}${Z.goalTitle}`,Z.user,Z.goalTitle),searchText:qe([Z.title,Z.description,Z.goalTitle],Z),kind:Vt.project})),...i.snapshot.tasks.map(Z=>({value:At("task",Z.id),label:Z.title,description:Be(`${Z.description}${Z.description?" · ":""}${Z.owner}`,Z.user,Z.owner),searchText:qe([Z.title,Z.description,Z.owner],Z),kind:Vt.task})),...i.snapshot.strategies.map(Z=>({value:At("strategy",Z.id),label:Z.title,description:Be(Z.overview,Z.user,"Strategy"),searchText:qe([Z.title,Z.overview,Z.endStateDescription],Z),kind:Vt.strategy})),...i.snapshot.habits.map(Z=>({value:At("habit",Z.id),label:Z.title,description:Be(Z.description,Z.user,"Habit"),searchText:qe([Z.title,Z.description],Z),kind:Vt.habit})),...i.snapshot.tags.map(Z=>({value:At("tag",Z.id),label:Z.name,description:Be(Z.description,Z.user,Z.kind),searchText:qe([Z.name,Z.kind,Z.description],Z)})),...(((he=u.data)==null?void 0:he.values)??[]).map(Z=>({value:At("psyche_value",Z.id),label:Z.title,description:Be(Z.description,Z.user,"Psyche value"),searchText:qe([Z.title,Z.description,Z.valuedDirection],Z),kind:Vt.psyche_value})),...(((ye=j.data)==null?void 0:ye.patterns)??[]).map(Z=>({value:At("behavior_pattern",Z.id),label:Z.title,description:Be(Z.description,Z.user,"Behavior pattern"),searchText:qe([Z.title,Z.description,Z.targetBehavior],Z),kind:Vt.behavior_pattern})),...(((ze=L.data)==null?void 0:ze.behaviors)??[]).map(Z=>({value:At("behavior",Z.id),label:Z.title,description:Be(Z.description,Z.user,"Behavior"),searchText:qe([Z.title,Z.description,Z.kind],Z),kind:Vt.behavior})),...(((fe=q.data)==null?void 0:fe.beliefs)??[]).map(Z=>({value:At("belief_entry",Z.id),label:Z.statement,description:Be(Z.flexibleAlternative||Z.originNote,Z.user,"Belief"),searchText:qe([Z.statement,Z.flexibleAlternative,Z.originNote],Z),kind:Vt.belief_entry})),...(((Pe=G.data)==null?void 0:Pe.modes)??[]).map(Z=>({value:At("mode_profile",Z.id),label:Z.title,description:Be(Z.archetype||Z.family,Z.user,"Mode"),searchText:qe([Z.title,Z.archetype,Z.family,Z.persona],Z),kind:Vt.mode_profile})),...(((Ge=Q.data)==null?void 0:Ge.reports)??[]).map(Z=>({value:At("trigger_report",Z.id),label:Z.title,description:Be(Z.eventSituation,Z.user,"Trigger report"),searchText:qe([Z.title,Z.eventSituation,Z.customEventType??""],Z),kind:Vt.trigger_report}))];return nb(X)},[(ce=L.data)==null?void 0:ce.behaviors,(E=q.data)==null?void 0:E.beliefs,(z=G.data)==null?void 0:z.modes,(K=j.data)==null?void 0:K.patterns,(je=Q.data)==null?void 0:je.reports,i.snapshot.dashboard.projects,i.snapshot.goals,i.snapshot.habits,i.snapshot.strategies,i.snapshot.tags,i.snapshot.tasks,(V=u.data)==null?void 0:V.values]),H=c.useMemo(()=>ne.map(X=>{const he=oa(X.value);return{value:X.value,label:X.label,description:X.description,searchText:X.searchText,kind:X.kind,entityType:(he==null?void 0:he.entityType)??"goal",entityId:(he==null?void 0:he.entityId)??""}}),[ne]),_=c.useMemo(()=>r.map(X=>oa(X)).filter(Boolean),[r]),U=pe({queryKey:["notes-index",r.join("|"),d.join("|"),x.join("|"),b.trim(),h,w],queryFn:()=>Sd({linkedTo:_,tags:d,textTerms:x,author:b.trim()||void 0,updatedFrom:h||void 0,updatedTo:w||void 0,limit:200})}),R=async()=>{await Promise.all([s.invalidateQueries({queryKey:["notes-index"]}),s.invalidateQueries({queryKey:["forge-snapshot"]})])},C=ge({mutationFn:async X=>mr({contentMarkdown:X.contentMarkdown.trim(),author:X.author.trim()||null,tags:ns(X.tags),destroyAt:Ql(X),links:X.linkedValues.map(he=>oa(he)).filter(Kl).map(he=>({entityType:he.entityType,entityId:he.entityId}))}),onSuccess:async()=>{M(Di(null,r)),k(!1),await R()}}),J=ge({mutationFn:async({noteId:X,draft:he})=>Cd(X,{contentMarkdown:he.contentMarkdown.trim(),author:he.author.trim()||null,tags:ns(he.tags),destroyAt:Ql(he),links:he.linkedValues.map(ye=>oa(ye)).filter(Kl).map(ye=>({entityType:ye.entityType,entityId:ye.entityId}))}),onSuccess:async()=>{y(null),A(null),await R()}}),ee=ge({mutationFn:X=>Id(X),onSuccess:R}),le=((D=U.data)==null?void 0:D.notes)??[],oe=T?le.find(X=>X.id===T.noteId)??null:null,ue=oe?Dl(oe):null,me=ue?Es(ue.entityType,ue.entityId):null,$=c.useMemo(()=>oe?[{id:"open-linked",label:"Open linked record",description:me?"Jump back into the main entity this note is attached to.":"This note has no navigable linked record yet.",icon:Ni,disabled:!me,onSelect:()=>{me&&t(me.includes("#")?me:`${me}#notes`)}},{id:"edit-note",label:"Edit note",description:"Update the Markdown body, note tags, expiry, or connected entity links.",icon:Us,onSelect:()=>{y(oe.id),A(Di(oe))}},{id:"delete-note",label:"Delete note",description:"Soft-delete this note from the main workspace.",icon:bt,tone:"danger",disabled:ee.isPending,onSelect:()=>{ee.mutateAsync(oe.id)}}]:[],[me,oe,ee,t]);return U.isError?e.jsx(Oe,{eyebrow:"Notes",error:U.error,onRetry:()=>void U.refetch()}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{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:`${le.length} visible`,actions:e.jsxs(W,{onClick:()=>{M(Di(null,r)),k(!0)},children:[e.jsx(Wt,{className:"size-4"}),"New note"]})}),e.jsxs(se,{className:"grid gap-4",children:[e.jsx(tb,{entityOptions:H,selectedEntityValues:r,onSelectedEntityValuesChange:l,selectedTextTerms:x,onSelectedTextTermsChange:f}),e.jsx(Qi,{value:d,onChange:o,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(ie,{value:b,onChange:X=>m(X.target.value),placeholder:"Filter by author"}),e.jsx(ie,{type:"date",value:h,onChange:X=>p(X.target.value)}),e.jsx(ie,{type:"date",value:w,onChange:X=>v(X.target.value)})]})]}),I?e.jsxs(se,{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.jsx("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."})]}),e.jsx(W,{variant:"ghost",onClick:()=>{k(!1),M(Di(null,r))},children:"Cancel"})]}),e.jsx(Ce,{value:S.contentMarkdown,onChange:X=>M(he=>({...he,contentMarkdown:X.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(ie,{value:S.author,onChange:X=>M(he=>({...he,author:X.target.value})),placeholder:"Optional author"}),e.jsx(st,{options:ne,selectedValues:S.linkedValues,onChange:X=>M(he=>({...he,linkedValues:X})),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(Qi,{value:S.tags,onChange:X=>M(he=>({...he,tags:X}))}),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(ie,{type:"datetime-local",value:S.destroyAtInput,onChange:X=>M(he=>({...he,destroyAtInput:X.target.value}))}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_10rem]",children:[e.jsx(ie,{type:"number",min:"1",value:S.destroyDelayValue,onChange:X=>M(he=>({...he,destroyDelayValue:X.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:S.destroyDelayUnit,onChange:X=>M(he=>({...he,destroyDelayUnit:X.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:S.contentMarkdown.trim()?e.jsx(es,{markdown:S.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:C.isPending,pendingLabel:"Saving",disabled:S.contentMarkdown.trim().length===0||S.linkedValues.length===0,onClick:()=>void C.mutateAsync(S),children:"Save note"})})]}):null,U.isLoading?e.jsx(se,{className:"text-sm text-white/58",children:"Loading notes…"}):le.length===0?e.jsx(gt,{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("div",{className:"grid gap-3",children:le.map(X=>{const he=Dl(X),ye=he?Es(he.entityType,he.entityId):null,ze=P===X.id&&N!==null;return e.jsxs(se,{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:[(X.author??"Unknown author").toString()," •"," ",new Date(X.updatedAt).toLocaleString()]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[X.links.map(fe=>e.jsxs(O,{className:"bg-white/[0.08] text-white/68",wrap:!0,children:[qs(fe.entityType),fe.anchorKey?` · ${Ui(fe.anchorKey)}`:""]},`${X.id}-${fe.entityType}-${fe.entityId}-${fe.anchorKey??""}`)),(X.tags??[]).map(fe=>e.jsx(O,{className:"bg-cyan-400/10 text-cyan-50",wrap:!0,children:fe},`${X.id}-tag-${fe}`)),X.destroyAt?e.jsxs(O,{className:"bg-amber-400/10 text-amber-100",wrap:!0,children:["Ephemeral · deletes"," ",new Date(X.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:fe=>{fe.preventDefault(),fe.stopPropagation();const Pe=fe.currentTarget.getBoundingClientRect();F({noteId:X.id,position:{x:Pe.right-8,y:Pe.bottom+8}})},"aria-label":`Open actions for note ${X.id}`,children:e.jsx(ja,{className:"size-4"})})]}),ze?e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsx(Ce,{value:N.contentMarkdown,onChange:fe=>A(Pe=>Pe&&{...Pe,contentMarkdown:fe.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(ie,{value:N.author,onChange:fe=>A(Pe=>Pe&&{...Pe,author:fe.target.value}),placeholder:"Optional author"}),e.jsx(st,{options:ne,selectedValues:N.linkedValues,onChange:fe=>A(Pe=>Pe&&{...Pe,linkedValues:fe}),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(Qi,{value:N.tags,onChange:fe=>A(Pe=>Pe&&{...Pe,tags:fe})}),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(ie,{type:"datetime-local",value:N.destroyAtInput,onChange:fe=>A(Pe=>Pe&&{...Pe,destroyAtInput:fe.target.value})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_10rem]",children:[e.jsx(ie,{type:"number",min:"1",value:N.destroyDelayValue,onChange:fe=>A(Pe=>Pe&&{...Pe,destroyDelayValue:fe.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:fe=>A(Pe=>Pe&&{...Pe,destroyDelayUnit:fe.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(es,{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),A(null)},children:"Cancel"}),e.jsx(W,{pending:J.isPending,pendingLabel:"Saving",disabled:N.contentMarkdown.trim().length===0||N.linkedValues.length===0,onClick:()=>void J.mutateAsync({noteId:X.id,draft:N}),children:"Save changes"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"mt-4 w-full text-left",onClick:()=>{ye&&t(ye.includes("#")?ye:`${ye}#notes`)},disabled:!ye,children:e.jsx(es,{markdown:X.contentMarkdown,className:"line-clamp-none"})}),ye?e.jsx("div",{className:"mt-4 inline-flex text-xs uppercase tracking-[0.16em] text-[var(--secondary)]",children:"Open linked record"}):null]})]},X.id)})}),e.jsx(Wd,{open:!!T,title:"Note actions",subtitle:oe?oe.contentPlain.slice(0,80)||"Markdown note":void 0,items:$,position:(T==null?void 0:T.position)??null,onClose:()=>F(null)})]})}function pc({eyebrow:t,title:s,description:i,items:n,tone:a="core",className:r}){return e.jsxs("section",{className:re("min-w-0 overflow-hidden rounded-[28px] border border-white/6 shadow-[0_20px_54px_rgba(4,8,18,0.24)]",a==="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))]",r),children:[e.jsxs("div",{className:re("grid min-w-0 gap-3 px-4 py-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,26rem)] lg:px-5",a==="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:re("font-label text-[11px] uppercase tracking-[0.2em]",a==="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:i})]}),e.jsx("div",{className:"grid min-w-0 gap-2 sm:grid-cols-3",children:n.slice(0,3).map(l=>l.href?e.jsxs(Le,{to:l.href,className:re("min-w-0 rounded-[20px] border border-white/6 px-3 py-3 backdrop-blur-sm transition hover:bg-white/[0.08]",a==="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:re("min-w-0 rounded-[20px] border border-white/6 px-3 py-3 backdrop-blur-sm",a==="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:n.map((l,d)=>{const o=re("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]",a==="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))]"),x=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:re("flex min-w-0 flex-1 flex-col p-4",a==="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(O,{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(Gs,{className:"size-3.5"})]})}):null]});return e.jsx(wt.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.22,delay:.04*d,ease:"easeOut"},children:l.href?e.jsx(Le,{to:l.href,className:o,children:x}):e.jsx("div",{className:o,children:x})},l.id)})})]})}function lb(t){switch(t){case"platinum":return"text-cyan-200";case"gold":return"text-amber-200";case"silver":return"text-slate-200";default:return"text-orange-200"}}function ob(t){switch(t){case"surging":return"from-[rgba(192,193,255,0.3)] via-[rgba(78,222,163,0.22)] to-[rgba(255,185,95,0.22)]";case"steady":return"from-[rgba(192,193,255,0.24)] via-[rgba(192,193,255,0.14)] to-[rgba(78,222,163,0.18)]";default:return"from-[rgba(255,185,95,0.2)] via-[rgba(255,185,95,0.12)] to-[rgba(192,193,255,0.16)]"}}function xc({profile:t,achievements:s,milestoneRewards:i,momentumPulse:n,recentLedger:a=[],className:r,tone:l="core"}){const d=s.filter(m=>m.unlocked),o=(d.length>0?d:s).slice(0,3),x=i.slice(0,3),f=a.slice(0,3),b=Math.min(100,Math.round(t.currentLevelXp/t.nextLevelXp*100));return e.jsxs("section",{className:re("min-w-0 overflow-hidden rounded-[30px] border border-white/6 bg-[linear-gradient(180deg,rgba(18,24,40,0.96),rgba(11,16,28,0.94))] shadow-[0_24px_70px_rgba(4,8,18,0.3)]",l==="psyche"&&"bg-[linear-gradient(180deg,rgba(18,27,35,0.96),rgba(12,20,26,0.94))]",r),children:[e.jsx("div",{className:re("bg-gradient-to-r px-5 py-5",ob(n.status)),children:e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/55",children:"Weekly progress"}),e.jsx("h2",{className:"mt-3 font-display text-3xl leading-none text-white lg:text-4xl",children:n.headline}),e.jsx("p",{className:"mt-3 max-w-3xl text-sm leading-7 text-white/68",children:n.detail})]}),e.jsxs("div",{className:"flex min-w-0 flex-wrap gap-2",children:[e.jsxs(O,{wrap:!0,className:"bg-black/20 text-white/84",children:["Level ",t.level]}),e.jsxs(O,{wrap:!0,className:"bg-black/20 text-white/84",children:[t.streakDays," day streak"]}),e.jsxs(O,{wrap:!0,className:"bg-black/20 text-white/84",children:[t.weeklyXp," weekly XP"]})]})]})}),e.jsxs("div",{className:"grid gap-5 px-5 py-5 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(wt.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.24,ease:"easeOut"},className:"overflow-hidden rounded-[24px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium text-white",children:"Next reward"}),e.jsx("div",{className:"mt-2 text-sm text-white/60",children:n.nextMilestoneLabel})]}),e.jsx(O,{wrap:!0,className:"max-w-[12rem] shrink-0 self-start text-[var(--tertiary)]",children:n.celebrationLabel})]}),e.jsx("div",{className:"mt-5",children:e.jsx(ts,{value:b})}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-xs uppercase tracking-[0.16em] text-white/38",children:[e.jsxs("span",{children:[t.currentLevelXp,"/",t.nextLevelXp," XP"]}),e.jsxs("span",{children:[t.comboMultiplier.toFixed(2),"x combo"]})]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:o.map((m,h)=>e.jsxs(wt.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.24,delay:.04*h,ease:"easeOut"},className:"overflow-hidden rounded-[22px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0 flex-1 font-medium text-white",children:m.title}),e.jsx(O,{wrap:!0,className:re("max-w-[8rem] shrink-0 self-start",lb(m.tier)),children:m.tier})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:m.summary}),e.jsx("div",{className:"mt-4 text-xs uppercase tracking-[0.16em] text-white/40",children:m.progressLabel})]},m.id))})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"overflow-hidden rounded-[24px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Rewards in progress"}),e.jsx("div",{className:"mt-4 grid gap-3",children:x.map(m=>{const h=Math.min(100,Math.round(m.current/m.target*100));return e.jsxs("div",{className:"overflow-hidden rounded-[18px] bg-[rgba(8,13,28,0.68)] p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0 flex-1 font-medium text-white",children:m.title}),e.jsx(O,{wrap:!0,className:re("max-w-[10.5rem] shrink-0 self-start",m.completed?"text-emerald-300":"text-white/68"),children:m.rewardLabel})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:m.summary}),e.jsx("div",{className:"mt-4",children:e.jsx(ts,{value:h})}),e.jsx("div",{className:"mt-3 text-xs uppercase tracking-[0.16em] text-white/38",children:m.progressLabel})]},m.id)})})]}),f.length>0?e.jsxs("div",{className:"overflow-hidden rounded-[24px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Recent XP changes"}),e.jsx("div",{className:"mt-4 grid gap-3",children:f.map(m=>e.jsxs("div",{className:"overflow-hidden rounded-[18px] bg-[rgba(8,13,28,0.68)] p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0 flex-1 font-medium text-white",children:m.reasonTitle}),e.jsxs(O,{wrap:!0,className:re("max-w-[8rem] shrink-0 self-start",m.deltaXp>=0?"text-emerald-300":"text-amber-300"),children:[m.deltaXp>0?"+":"",m.deltaXp," XP"]})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:m.reasonSummary}),e.jsx("div",{className:"mt-3 text-xs uppercase tracking-[0.16em] text-white/38",children:er(m.createdAt)})]},m.id))})]}):null]})]})]})}function js({to:t,children:s,className:i}){return e.jsx(Le,{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(se,{className:re("transition-[transform,box-shadow,background] duration-[var(--motion-medium)] ease-[var(--ease-standard)] group-hover:bg-white/[0.06] group-hover:shadow-[var(--card-shadow-hover)] group-focus-visible:shadow-[var(--card-shadow-hover)]",i),children:s})})}function ks({label:t,value:s,tone:i="default",detail:n,className:a}){return e.jsxs(se,{className:re("rounded-[22px] p-4",i==="core"&&"bg-[linear-gradient(180deg,rgba(29,24,48,0.95),rgba(17,17,31,0.92))]",i==="psyche"&&"bg-[linear-gradient(180deg,rgba(18,31,34,0.96),rgba(13,24,27,0.94))]",a),children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:t}),e.jsx("div",{className:"mt-3 font-display text-3xl text-white",children:s}),n?e.jsx("div",{className:"mt-2 text-sm text-white/56",children:n}):null]})}function db(){const{t,formatDateTime:s}=at(),{snapshot:i}=Ye(),n=i.metrics.momentumScore>=80?"Strong":i.metrics.momentumScore>=60?"Steady":"Needs attention",a=new Map(i.projects.map(v=>[v.id,v])),r=i.dashboard.milestoneRewards.find(v=>!v.completed)??i.dashboard.milestoneRewards[0]??null,l=i.dashboard.achievements.filter(v=>v.unlocked).length,d=i.overview.topTasks[0]??null,o=i.overview.dueHabits[0]??null,x=i.overview.activeGoals[0]??null,f=i.overview.neglectedGoals[0]??null,b=i.overview.recentEvidence[0]??null,m={status:i.metrics.momentumScore>=80?"surging":i.metrics.momentumScore>=60?"steady":"recovering",headline:i.metrics.momentumScore>=80?`${i.metrics.streakDays}-day streak active. Your recent work is building on itself.`:i.metrics.momentumScore>=60?"Momentum is stable. One useful push will keep things moving.":"Momentum is soft right now. One real win will help restart it.",detail:r!==null?`${r.title} is the clean next unlock. ${r.progressLabel}.`:`Level ${i.metrics.level} is active with ${i.metrics.weeklyXp} weekly XP recorded.`,celebrationLabel:l>0?`${l} achievement${l===1?"":"s"} unlocked`:i.metrics.weeklyXp>=120?"A strong week is taking shape":"The next reward comes from a real completion or repair",nextMilestoneId:(r==null?void 0:r.id)??null,nextMilestoneLabel:(r==null?void 0:r.rewardLabel)??"Keep building visible momentum"},h=i.overview.activeGoals.length>0||i.overview.projects.length>0||i.overview.topTasks.length>0||i.overview.recentEvidence.length>0||i.overview.dueHabits.length>0||i.overview.neglectedGoals.length>0,p=[{id:"top-task",label:d?"Top task":o?"Due habit":"Top goal",title:d?e.jsx(_e,{kind:"task",label:d.title,lines:3,labelClassName:"[overflow-wrap:anywhere]"}):o?e.jsx(_e,{kind:"habit",label:o.title,lines:3,labelClassName:"[overflow-wrap:anywhere]"}):x?e.jsx(_e,{kind:"goal",label:x.title,lines:3,labelClassName:"[overflow-wrap:anywhere]"}):"Choose the next task",detail:(d==null?void 0:d.description)||(o==null?void 0:o.description)||(x==null?void 0:x.description)||t("common.todayPage.noDirectiveDetail"),badge:d?`${d.points} xp`:o?`${o.rewardXp} xp`:`${i.overview.strategicHeader.focusTasks} focus tasks`,href:d?`/tasks/${d.id}`:o?"/habits":x?`/goals/${x.id}`:"/goals",actionLabel:d?"Open task":o?"Open habits":"Open goal"},{id:"reward",label:"Next reward",title:(r==null?void 0:r.title)??"Keep the streak going",detail:(r==null?void 0:r.progressLabel)??`Level ${i.metrics.level} is live. ${i.metrics.currentLevelXp} XP is already banked toward the next unlock.`,badge:(r==null?void 0:r.rewardLabel)??`${i.metrics.comboMultiplier.toFixed(2)}x combo`,href:"/today",actionLabel:"Open today"},{id:"goal-needing-attention",label:"Goal needing attention",title:f?e.jsx(_e,{kind:"goal",label:f.title,lines:3,labelClassName:"[overflow-wrap:anywhere]"}):"No goal needs urgent attention",detail:(f==null?void 0:f.summary)??`Only ${i.overview.strategicHeader.overdueTasks} overdue task${i.overview.strategicHeader.overdueTasks===1?"":"s"} are currently slowing the engine.`,badge:(f==null?void 0:f.risk)??"stable",href:f?`/goals/${f.goalId}`:"/today",actionLabel:f?"Open goal":"Open today"},{id:"recent-activity",label:"Recent activity",title:b?Xa(b):`${l} achievement${l===1?"":"s"} unlocked`,detail:(b?Ja(b):null)??t("common.overview.noEvidence"),badge:(b==null?void 0:b.source)??`${i.metrics.weeklyXp} weekly XP`,href:b?w(b):"/activity",actionLabel:b?"Open item":"Open activity"}];function w(v){return v.entityType==="goal"?`/goals/${v.entityId}`:v.entityType==="project"?`/projects/${v.entityId}`:v.entityType==="task"?`/tasks/${v.entityId}`:v.entityType==="habit"?"/habits":v.entityType==="task_run"&&typeof v.metadata.taskId=="string"?`/tasks/${v.metadata.taskId}`:`/activity?eventId=${v.id}`}return h?e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-5",children:[e.jsx(Ke,{title:"Overview",titleText:"Overview",description:`${n}. See your main goals, active projects, top tasks, and recent activity in one place.`,badge:`${i.metrics.streakDays} day streak`}),e.jsx(xc,{profile:i.metrics,achievements:i.dashboard.achievements,milestoneRewards:i.dashboard.milestoneRewards,momentumPulse:m}),e.jsx(pc,{eyebrow:"Actions",title:"What you can open or act on right now",description:"Each card below leads to a real task, goal, reward, or recent activity item.",items:p}),e.jsxs("section",{className:"grid min-w-0 grid-cols-1 gap-5",children:[e.jsxs(se,{className:"bg-[linear-gradient(180deg,rgba(19,24,40,0.96),rgba(11,15,27,0.96))]",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",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:"Overview summary"}),e.jsx(Xe,{content:"This summarizes your current level, weekly XP, and the goal that most needs attention."})]}),e.jsx("h2",{className:"mt-2 font-display text-[clamp(1.35rem,2vw,1.9rem)] text-white",children:"Level, weekly XP, and what needs attention"})]}),e.jsx("div",{className:"max-w-full min-w-0 rounded-full border border-white/8 bg-white/[0.04] px-4 py-2 text-sm text-white/62",children:m.status})]}),e.jsxs("div",{className:"mt-4 grid gap-3 lg:grid-cols-3",children:[e.jsx(ks,{label:t("common.overview.metricsLevel"),value:i.metrics.level,tone:"core"}),e.jsx(ks,{label:t("common.overview.metricsWeeklyXp"),value:i.metrics.weeklyXp,tone:"core",detail:"XP earned so far this week."}),e.jsxs(js,{to:f?`/goals/${f.goalId}`:"/today",className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/45",children:"Goal needing attention"}),e.jsx("div",{className:"mt-2 font-medium text-white",children:(f==null?void 0:f.title)??"No goal needs urgent attention"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(f==null?void 0:f.summary)??`Only ${i.overview.strategicHeader.overdueTasks} overdue task${i.overview.strategicHeader.overdueTasks===1?"":"s"} are currently slowing the engine.`})]})]})]}),e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-5",children:[e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Goals"}),i.overview.activeGoals.length===0?e.jsx("div",{className:"mt-4 rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/58",children:t("common.overview.noGoals")}):e.jsx("div",{className:"mt-4 grid gap-3 lg:grid-cols-3",children:i.overview.activeGoals.slice(0,3).map(v=>{var I;return e.jsxs(js,{to:`/goals/${v.id}`,className:"rounded-[22px] p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[e.jsx(ke,{kind:"goal",label:((I=v.tags[0])==null?void 0:I.name)??v.horizon,compact:!0,gradient:!1}),e.jsxs("div",{className:"shrink-0 text-[11px] uppercase tracking-[0.16em] text-white/42",children:[v.progress,"%"]})]}),e.jsx("div",{className:"mt-4",children:e.jsx(_e,{kind:"goal",label:v.title,variant:"heading",size:"lg",lines:3,className:"max-w-full",labelClassName:"[overflow-wrap:anywhere]"})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/60",children:v.description}),e.jsx("div",{className:"mt-4",children:e.jsx(ts,{value:v.progress})}),e.jsx("div",{className:"mt-4",children:e.jsx(yt,{entityType:"goal",entityId:v.id,count:Tt(i.dashboard.notesSummaryByEntity,"goal",v.id).count})})]},v.id)})})]}),e.jsxs("div",{className:"grid min-w-0 gap-5 lg:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]",children:[e.jsxs(se,{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:"Projects"}),e.jsx(Xe,{content:"These are the projects currently carrying active work."})]}),i.overview.projects.length===0?e.jsx("div",{className:"mt-4 rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/58",children:t("common.overview.noProjects")}):e.jsx("div",{className:"mt-4 grid gap-3",children:i.overview.projects.slice(0,4).map(v=>e.jsxs(js,{to:`/projects/${v.id}`,className:"rounded-[20px] px-4 py-4",children:[e.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(ke,{kind:"project",compact:!0,gradient:!1}),e.jsx(_e,{kind:"project",label:v.title,className:"min-w-0",showIcon:!1,lines:2,labelClassName:"[overflow-wrap:anywhere]"})]}),e.jsxs(O,{wrap:!0,className:"max-w-[8rem] shrink-0",children:[v.earnedPoints," xp"]})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:v.description}),e.jsx("div",{className:"mt-3",children:e.jsx(ke,{kind:"goal",label:v.goalTitle,compact:!0})}),e.jsx("div",{className:"mt-4",children:e.jsx(yt,{entityType:"project",entityId:v.id,count:Tt(i.dashboard.notesSummaryByEntity,"project",v.id).count})})]},v.id))})]}),e.jsxs(se,{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:"Due habits"}),e.jsx(Xe,{content:"Recurring commitments or slips that still need a truthful check-in today."})]}),i.overview.dueHabits.length===0?e.jsx("div",{className:"mt-4 rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/58",children:"No habits are due right now."}):e.jsx("div",{className:"mt-4 grid gap-3",children:i.overview.dueHabits.slice(0,4).map(v=>e.jsxs(js,{to:"/habits",className:"rounded-[20px] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(ke,{kind:"habit",compact:!0,gradient:!1}),e.jsx(_e,{kind:"habit",label:v.title,className:"min-w-0",showIcon:!1,lines:2,labelClassName:"[overflow-wrap:anywhere]"})]}),e.jsxs(O,{wrap:!0,children:[v.rewardXp," xp"]})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:v.description||"Recurring operating commitment."}),e.jsx("div",{className:"mt-4",children:e.jsx(yt,{entityType:"habit",entityId:v.id,count:Tt(i.dashboard.notesSummaryByEntity,"habit",v.id).count})})]},v.id))})]}),e.jsxs(se,{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:"Tasks ready to start"}),e.jsx(Xe,{content:"These are the strongest task candidates to pick up next."})]}),i.overview.topTasks.length===0?e.jsx("div",{className:"mt-4 rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/58",children:t("common.overview.noFocus")}):e.jsx("div",{className:"mt-4 grid gap-3",children:i.overview.topTasks.slice(0,4).map(v=>{var I,k;return e.jsxs(js,{to:`/tasks/${v.id}`,className:"rounded-[20px] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(ke,{kind:"task",compact:!0,gradient:!1}),e.jsx(_e,{kind:"task",label:v.title,className:"min-w-0",showIcon:!1,lines:2,labelClassName:"[overflow-wrap:anywhere]"})]}),e.jsxs(O,{wrap:!0,children:[v.points," xp"]})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:v.description}),e.jsx("div",{className:"mt-3",children:(I=a.get(v.projectId??""))!=null&&I.title?e.jsx(ke,{kind:"project",label:((k=a.get(v.projectId??""))==null?void 0:k.title)??"",compact:!0}):e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:t("common.overview.noProjectYet")})}),e.jsx("div",{className:"mt-4",children:e.jsx(yt,{entityType:"task",entityId:v.id,count:Tt(i.dashboard.notesSummaryByEntity,"task",v.id).count})})]},v.id)})})]})]}),e.jsxs(se,{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:"Recent activity"}),e.jsx(Xe,{content:"This shows the latest visible work, completions, and corrections linked to your goals, projects, and tasks."})]}),i.overview.recentEvidence.length===0?e.jsx("div",{className:"mt-4 rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/58",children:t("common.overview.noEvidence")}):e.jsx("div",{className:"mt-4 grid gap-3 lg:grid-cols-2",children:i.overview.recentEvidence.slice(0,6).map(v=>e.jsxs(js,{to:w(v),className:"rounded-[20px] 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:v.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:v.description})]}),e.jsx(O,{wrap:!0,children:v.source})]}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.16em] text-white/35",children:s(v.createdAt)})]},v.id))})]})]})]})]}):e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-5",children:[e.jsx(Ke,{title:"Overview",titleText:"Overview",description:"See your main goals, active projects, top tasks, recent activity, and current progress in one place.",badge:"0 live signals"}),e.jsx(gt,{eyebrow:t("common.overview.heroEyebrow"),title:t("common.overview.emptyTitle"),description:t("common.overview.emptyDescription"),action:e.jsx(Le,{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 cb=[10,15,30,45,60];function Wl(){return{mode:"add",minutes:15,note:""}}function gc({open:t,onOpenChange:s,entityType:i,entityId:n,targetLabel:a,currentCreditedSeconds:r,pending:l=!1,onSubmit:d}){const[o,x]=c.useState(Wl),[f,b]=c.useState(null);c.useEffect(()=>{t&&(x(Wl()),b(null))},[t]);const m=pe({queryKey:["forge-xp-metrics"],queryFn:Ad,enabled:t}),h=c.useMemo(()=>{var S;const v=(S=m.data)==null?void 0:S.metrics.rules.find(M=>M.code==="task_run_progress"),I=Math.max(1,Number((v==null?void 0:v.config.intervalMinutes)??10)),k=Number((v==null?void 0:v.config.fixedXp)??4);return{intervalMinutes:I,fixedXp:k,intervalSeconds:I*60}},[m.data]),p=c.useMemo(()=>{const v=Math.max(0,Math.trunc(o.minutes||0)),I=o.mode==="add"?v:-v,k=Math.max(0,Math.floor(r/60)),S=I>=0?I:-Math.min(Math.abs(I),k),M=Math.max(0,r+S*60),P=Math.floor(Math.max(0,r)/h.intervalSeconds),N=Math.floor(M/h.intervalSeconds)-P;return{requestedDeltaMinutes:I,appliedDeltaMinutes:S,nextCreditedSeconds:M,bucketDelta:N,xpDelta:N*h.fixedXp,maxRemovableMinutes:k}},[h.fixedXp,h.intervalSeconds,r,o.minutes,o.mode]),w=[{id:"adjustment",eyebrow:i==="task"?"Task work":"Project work",title:`Adjust tracked work for ${a}`,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:(v,I)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Mode",labelHelp:"Add minutes when work happened off-timer. Remove minutes when the tracked total needs a correction.",children:e.jsx(tt,{value:v.mode,onChange:k=>I({mode:k}),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(Y,{label:"Minutes",description:`Currently tracked: ${Math.floor(r/60)} minutes.`,hint:v.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(ie,{type:"number",min:1,className:"w-36",value:v.minutes,onChange:k=>I({minutes:Number(k.target.value)||0})}),e.jsx("div",{className:"flex flex-wrap gap-2",children:cb.map(k=>e.jsxs(W,{type:"button",variant:v.minutes===k?"primary":"secondary",onClick:()=>I({minutes:k}),children:[k," min"]},k))})]})}),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: ",h.fixedXp," XP every ",h.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(Y,{label:"Note",description:"Optional context for why this correction is being added. The note stays attached to the adjustment metadata.",children:e.jsx(Ce,{className:"min-h-28",value:v.note,onChange:k=>I({note:k.target.value}),placeholder:"Captured the review session that happened away from the live timer."})})]})}];return e.jsx(it,{open:t,onOpenChange:s,eyebrow:i==="task"?"Adjust task work":"Adjust project work",title:`Adjust work for ${a}`,description:"Add or remove tracked minutes without creating a live task run.",value:o,onChange:x,steps:w,submitLabel:"Save adjustment",pending:l,pendingLabel:"Saving adjustment...",error:f,onSubmit:async()=>{var S;b(null);const v=Math.max(0,Math.trunc(o.minutes||0)),I=o.mode==="add"?v:-v,k=Vh.safeParse({entityType:i,entityId:n,deltaMinutes:I,note:o.note});if(!k.success){b(((S=k.error.issues[0])==null?void 0:S.message)??"Enter a valid minute adjustment.");return}try{await d({entityType:i,entityId:n,deltaMinutes:k.data.deltaMinutes,note:k.data.note||void 0}),s(!1)}catch(M){b(M instanceof Error?M.message:"Could not save the work adjustment right now.")}}})}const bc={allowWorkBlockKinds:[],blockWorkBlockKinds:[],allowCalendarIds:[],blockCalendarIds:[],allowEventTypes:[],blockEventTypes:[],allowEventKeywords:[],blockEventKeywords:[],allowAvailability:[],blockAvailability:[]};function mb(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean)}function xn(t,s){const i=mb(t);if(i.length===0)return!1;const n=s.join(" ").toLowerCase();return i.some(a=>n.includes(a))}function hb(t){return t.allowWorkBlockKinds.length>0||t.allowCalendarIds.length>0||t.allowEventTypes.length>0||t.allowEventKeywords.length>0||t.allowAvailability.length>0}function ub(t,s){return t??s??bc}function fc(t){const s=t.rules??bc,n=(t.at??new Date).getTime(),a=t.overview,r=(a==null?void 0:a.workBlockInstances.filter(m=>{const h=new Date(m.startAt).getTime(),p=new Date(m.endAt).getTime();return h<=n&&n<p}))??[],l=(a==null?void 0:a.events.filter(m=>{if(m.deletedAt)return!1;const h=new Date(m.startAt).getTime(),p=new Date(m.endAt).getTime();return h<=n&&n<p}))??[],d=[],o=r.some(m=>s.blockWorkBlockKinds.includes(m.kind))||l.some(m=>(m.calendarId?s.blockCalendarIds.includes(m.calendarId):!1)||s.blockEventTypes.includes(m.eventType)||s.blockAvailability.includes(m.availability)||xn(s.blockEventKeywords,[m.title,m.description,m.location,...m.categories]));o&&(r.some(m=>s.blockWorkBlockKinds.includes(m.kind))&&d.push("The current work block is marked as blocked."),l.some(m=>m.calendarId?s.blockCalendarIds.includes(m.calendarId):!1)&&d.push("The active calendar belongs to a blocked calendar source."),l.some(m=>s.blockEventTypes.includes(m.eventType))&&d.push("The active calendar event type is blocked."),l.some(m=>s.blockAvailability.includes(m.availability))&&d.push("The active calendar availability is blocked."),l.some(m=>xn(s.blockEventKeywords,[m.title,m.description,m.location,...m.categories]))&&d.push("The active calendar event matches a blocked keyword."));const x=hb(s),f=r.some(m=>s.allowWorkBlockKinds.includes(m.kind))||l.some(m=>(m.calendarId?s.allowCalendarIds.includes(m.calendarId):!1)||s.allowEventTypes.includes(m.eventType)||s.allowAvailability.includes(m.availability)||xn(s.allowEventKeywords,[m.title,m.description,m.location,...m.categories]));!o&&x&&!f&&d.push("The current calendar context does not match the allowed rules yet.");const b=[...r.map(m=>`${m.title} (${m.kind.replaceAll("_"," ")})`),...l.map(m=>m.title)];return d.length>0?{blocked:!0,label:"Blocked right now",tone:"blocked",conflicts:d,context:b}:b.length>0?{blocked:!1,label:"Allowed right now",tone:"allowed",conflicts:[],context:b}:{blocked:!1,label:x?"Waiting for an allowed calendar context":"No live calendar conflict right now",tone:x?"waiting":"allowed",conflicts:[],context:[]}}function pb(t,s){return ub(t.schedulingRules,s)}function xb(t){return!!(t&&t.startsWith("campaign:"))}function gb(){var U;const{t}=at(),s=Ye(),i=Array.isArray(s.selectedUserIds)?s.selectedUserIds:[],n=Hs(),a=ht(),r=We(),[l,d]=c.useState(!1),[o,x]=c.useState(!1),[f,b]=c.useState(!1),[m]=c.useState(()=>{const R=new Date,C=new Date(R);C.setHours(0,0,0,0);const J=new Date(R);return J.setHours(23,59,59,999),{from:C.toISOString(),to:J.toISOString()}}),h=Nt(i),p=s.snapshot.dashboard.projects.find(R=>R.id===n.projectId)??null,w=p?s.snapshot.goals.find(R=>R.id===p.goalId)??null:null,v=p?s.snapshot.tasks.filter(R=>R.projectId===p.id||!R.projectId&&R.goalId===p.goalId):[],I=new Set(v.map(R=>R.id)),k=p?s.snapshot.activity.filter(R=>R.entityId===p.goalId||R.entityId===p.id||I.has(R.entityId)||R.entityType==="task_run"&&typeof R.metadata.taskId=="string"&&I.has(R.metadata.taskId)):[],S=xb(n.projectId),M=pe({queryKey:["project-board",n.projectId],queryFn:()=>Bp(n.projectId),enabled:!!n.projectId&&!S}),P=pe({queryKey:["project-calendar-overview",n.projectId,m.from,m.to,...i],queryFn:()=>Qa({...m,userIds:i}),enabled:!!n.projectId&&!S}),y=ge({mutationFn:R=>ur(R),onSuccess:async()=>{await Promise.all([r.invalidateQueries({queryKey:["forge-snapshot"]}),r.invalidateQueries({queryKey:["project-board",n.projectId]})])}}),N=ge({mutationFn:Fd,onSuccess:async()=>{await Promise.all([r.invalidateQueries({queryKey:["forge-snapshot"]}),r.invalidateQueries({queryKey:["project-board",n.projectId]}),r.invalidateQueries({queryKey:["forge-xp-metrics"]}),r.invalidateQueries({queryKey:["forge-reward-ledger"]}),r.invalidateQueries({queryKey:["forge-operator-context"]})])}}),A=ge({mutationFn:R=>Od(n.projectId,{status:R}),onSuccess:async()=>{await Promise.all([r.invalidateQueries({queryKey:["forge-snapshot"]}),r.invalidateQueries({queryKey:["project-board",n.projectId]}),r.invalidateQueries({queryKey:["forge-xp-metrics"]}),r.invalidateQueries({queryKey:["forge-reward-ledger"]}),r.invalidateQueries({queryKey:["forge-operator-context"]})])}}),T=ge({mutationFn:()=>wx(n.projectId),onSuccess:async()=>{await Promise.all([r.invalidateQueries({queryKey:["forge-snapshot"]}),r.invalidateQueries({queryKey:["project-board",n.projectId]})]),a("/projects")}}),F=ge({mutationFn:R=>hr(R),onSuccess:async()=>{await Promise.all([r.invalidateQueries({queryKey:["forge-snapshot"]}),r.invalidateQueries({queryKey:["project-board",n.projectId]}),r.invalidateQueries({queryKey:["task-context"]})])}}),u=M.data??(p&&w?{project:p,goal:w,tasks:v,activity:k}:void 0),j=s.snapshot.dashboard.projects.find(R=>R.id===n.projectId)??null;if(M.isError&&!S)return e.jsx(Oe,{eyebrow:t("common.projectDetail.errorEyebrow"),error:M.error,onRetry:()=>void M.refetch()});if(!u)return e.jsx(It,{});const L=u.tasks.find(R=>R.status==="focus"||R.status==="in_progress")??u.tasks[0]??null,q=u.tasks.find(R=>R.status==="blocked")??u.tasks.find(R=>R.status==="backlog")??null;u.activity[0];const G="notesSummaryByEntity"in u?u.notesSummaryByEntity:s.snapshot.dashboard.notesSummaryByEntity,Q=A.isPending||T.isPending,ne=fc({rules:u.project.schedulingRules,overview:(U=P.data)==null?void 0:U.calendar}),H=async R=>{await A.mutateAsync(R)},_=async()=>{window.confirm(t("common.projectDetail.deleteProjectConfirm",{title:u.project.title}))&&await T.mutateAsync()};return e.jsxs("div",{className:"grid min-w-0 gap-5",children:[e.jsx(Ke,{entityKind:"project",title:e.jsx(_e,{kind:"project",label:u.project.title,variant:"heading",size:"lg"}),titleText:u.project.title,description:u.project.description?e.jsx(es,{markdown:u.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(ke,{kind:"goal",label:u.goal.title,compact:!0,gradient:!1}),actions:e.jsx(Ha,{userId:h,domain:"projects",entityType:"project",entityId:u.project.id,label:u.project.title,description:u.project.description})}),u.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($e,{user:u.project.user})]}):null,S?e.jsxs(se,{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:()=>x(!0),children:t("common.projectDetail.addTask")}),S?null:e.jsx(W,{variant:"secondary",onClick:()=>b(!0),children:"Adjust work"}),S?null:e.jsx(W,{variant:"secondary",onClick:()=>d(!0),children:t("common.projectDetail.editProject")}),!S&&u.project.status==="active"?e.jsx(W,{variant:"secondary",pending:Q&&A.variables==="paused",pendingLabel:t("common.projectDetail.suspending"),onClick:()=>void H("paused"),children:t("common.projectDetail.suspendProject")}):null,!S&&u.project.status!=="completed"?e.jsx(W,{pending:Q&&A.variables==="completed",pendingLabel:t("common.projectDetail.finishing"),onClick:()=>void H("completed"),children:t("common.projectDetail.finishProject")}):null,!S&&u.project.status!=="active"?e.jsx(W,{variant:"secondary",pending:Q&&A.variables==="active",pendingLabel:t("common.projectDetail.restarting"),onClick:()=>void H("active"),children:t("common.projectDetail.restartProject")}):null,S?null:e.jsx(W,{variant:"ghost",pending:T.isPending,pendingLabel:t("common.projectDetail.deleting"),onClick:()=>void _(),children:t("common.projectDetail.deleteProject")}),e.jsx(Le,{to:`/goals/${u.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(se,{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(ke,{kind:"project",compact:!0,gradient:!1}),e.jsx(ke,{kind:"goal",label:u.goal.title,compact:!0,gradient:!1})]})]}),e.jsxs("div",{className:"mt-4 grid gap-3 lg:grid-cols-2",children:[e.jsxs(Le,{to:L?`/tasks/${L.id}`:`/projects/${u.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")}),L?e.jsx(ke,{kind:"task",compact:!0,gradient:!1}):null]}),e.jsx("div",{className:"mt-2 font-medium text-white",children:(L==null?void 0:L.title)??t("common.projectDetail.noNextTask")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(L==null?void 0:L.description)||t("common.projectDetail.noNextTaskDetail")})]}),e.jsxs(Le,{to:q?`/tasks/${q.id}`:`/projects/${u.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")}),q?e.jsx(ke,{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.noRisk")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(q==null?void 0:q.description)||t("common.projectDetail.noRiskDetail")})]})]})]}),e.jsxs(se,{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(O,{className:"bg-white/[0.08] text-white/72",children:t(`common.enums.projectStatus.${u.project.status}`)}),e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:u.project.momentumLabel}),e.jsxs(O,{className:"bg-white/[0.08] text-white/72",children:[Math.floor(u.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:[u.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:u.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.${u.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:u.tasks.filter(R=>R.status==="focus"||R.status==="in_progress").length})]})]})]})]}),S?null:e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,1fr)_22rem]",children:[e.jsx(pr,{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:u.project.schedulingRules,saveLabel:"Save project scheduling",onSave:async({schedulingRules:R})=>{await s.patchProject(u.project.id,{schedulingRules:R}),await r.invalidateQueries({queryKey:["project-board",n.projectId]}),await r.invalidateQueries({queryKey:["project-calendar-overview",n.projectId]})}}),e.jsxs(se,{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(O,{className:ne.tone==="blocked"?"bg-rose-500/14 text-rose-100":ne.tone==="waiting"?"bg-amber-500/14 text-amber-100":"bg-emerald-500/14 text-emerald-100",children:ne.label}),e.jsx(O,{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."}),ne.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:ne.context.map(R=>e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:R},R))})]}):null,ne.conflicts.length>0?e.jsx("div",{className:"mt-4 grid gap-2",children:ne.conflicts.map(R=>e.jsx("div",{className:"rounded-[16px] bg-rose-500/10 px-3 py-2 text-sm text-rose-100",children:R},R))}):null,e.jsx("div",{className:"mt-4",children:e.jsx(Le,{to:"/calendar",children:e.jsx(W,{variant:"secondary",children:"Open calendar workspace"})})})]})]}),e.jsx(hc,{tasks:u.tasks,goals:s.snapshot.goals,tags:s.snapshot.tags,notesSummaryByEntity:G,selectedTaskId:null,onMove:async(R,C)=>{await s.patchTaskStatus(R,C),await r.invalidateQueries({queryKey:["project-board",n.projectId]})},onSelectTask:R=>a(`/tasks/${R}`),onQuickReopenTask:async R=>{await y.mutateAsync(R)},onDeleteTask:async R=>{await F.mutateAsync(R)}}),S?null:e.jsx(Ga,{entityType:"project",entityId:u.project.id,title:"Project notes",description:"Keep rollout notes, checkpoints, and cross-task context attached to the project itself.",invalidateQueryKeys:[["project-board",n.projectId]]}),e.jsxs(se,{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:u.activity.slice(0,6).map(R=>e.jsxs(Le,{to:Ms(R)??`/activity?eventId=${R.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:Xa(R)}),e.jsx(O,{children:R.source})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:Ja(R)})]},R.id))})]}),e.jsx(nr,{open:l,goals:s.snapshot.goals,users:s.snapshot.users,editingProject:j,defaultUserId:(j==null?void 0:j.userId)??h,onOpenChange:d,onSubmit:async(R,C)=>{C&&(await s.patchProject(C,R),await r.invalidateQueries({queryKey:["project-board",n.projectId]}))}}),e.jsx(za,{open:o,goals:s.snapshot.goals,projects:s.snapshot.dashboard.projects,tags:s.snapshot.tags,users:s.snapshot.users,editingTask:null,initialProjectId:S?null:u.project.id,defaultUserId:u.project.userId??h,onOpenChange:x,onSubmit:async(R,C)=>{C?await Yi(C,R):await s.createTask(R),await r.invalidateQueries({queryKey:["project-board",n.projectId]})}}),S?null:e.jsx(gc,{open:f,onOpenChange:b,entityType:"project",entityId:u.project.id,targetLabel:u.project.title,currentCreditedSeconds:u.project.time.totalCreditedSeconds,pending:N.isPending,onSubmit:async R=>{await N.mutateAsync(R)}})]})}function bb(t){return t.trim().toLowerCase()}function Gl(t,s=!1){switch(t.kind){case"goal":return e.jsx(ke,{kind:"goal",label:t.label,compact:!0,gradient:!1});case"task":return e.jsx(ke,{kind:"task",label:t.label,compact:!0,gradient:!1});case"tag":return e.jsx(O,{className:"bg-white/[0.08] text-white/78",children:t.label});case"status":return e.jsx(O,{className:"bg-[rgba(192,193,255,0.12)] text-white/84",children:t.label});case"type":return e.jsx(O,{className:"bg-[rgba(86,170,255,0.12)] text-white/84",children:t.label});case"user":return e.jsx(O,{className:"bg-[rgba(110,231,183,0.12)] text-white/84",children:t.label});default:return t.label}}function fb({query:t,onQueryChange:s,options:i,selectedOptionIds:n,onSelectedOptionIdsChange:a,resultSummary:r}){const[l,d]=c.useState(!1),[o,x]=c.useState(0),f=c.useMemo(()=>n.map(v=>i.find(I=>I.id===v)).filter(Boolean),[i,n]),b=bb(t),m=c.useMemo(()=>{const v=i.filter(I=>!n.includes(I.id));return b?v.filter(I=>`${I.label} ${I.description??""} ${I.searchText??""}`.toLowerCase().includes(b)).slice(0,10):v.slice(0,10)},[b,i,n]),h=v=>{n.includes(v)||(a([...n,v]),s(""),x(0),d(!1))},p=v=>{a(n.filter(I=>I!==v))},w=()=>{s(""),a([]),x(0),d(!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||n.length>0?e.jsx("button",{type:"button",onClick:w,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:[f.length>0?e.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:f.map(v=>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:[Gl(v,!0),e.jsx("button",{type:"button",className:"rounded-full text-white/52 transition hover:text-white",onClick:()=>p(v.id),"aria-label":`Remove ${v.label}`,children:e.jsx(mt,{className:"size-3.5"})})]},v.id))}):null,e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(dt,{className:"size-4 text-white/36"}),e.jsx("input",{value:t,onChange:v=>{s(v.target.value),d(!0),x(0)},onFocus:()=>d(!0),onBlur:()=>{window.setTimeout(()=>d(!1),120)},onKeyDown:v=>{if(v.key==="Backspace"&&!t&&n.length>0){p(n[n.length-1]);return}if(v.key==="ArrowDown"){v.preventDefault(),d(!0),x(I=>m.length===0?0:Math.min(m.length-1,I+1));return}if(v.key==="ArrowUp"){v.preventDefault(),x(I=>Math.max(0,I-1));return}if(v.key==="Escape"){d(!1);return}v.key==="Enter"&&m[o]&&(v.preventDefault(),h(m[o].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:m.length>0?m.map((v,I)=>e.jsx("button",{type:"button",className:re("flex w-full items-start justify-between gap-3 rounded-[18px] px-3 py-2.5 text-left transition",I===o?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>x(I),onMouseDown:k=>k.preventDefault(),onClick:()=>h(v.id),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:Gl(v)}),v.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/46",children:v.description}):null]})},v.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:r})]})})}const wb={execution:"Execution",value:"Value",category:"Category"};function vb(t){return t.trim().toLowerCase()}function yb(){const t=Ye(),[s,i]=c.useState("active"),[n,a]=c.useState(""),[r,l]=c.useState([]),[d,o]=c.useState(null),x=c.useMemo(()=>gr(t.snapshot.dashboard.projects),[t.snapshot.dashboard.projects]),f=c.useMemo(()=>{const k=new Map(t.snapshot.dashboard.goals.map(y=>[y.id,y])),S=new Map(t.snapshot.tags.map(y=>[y.id,y])),M=new Map(t.snapshot.users.map(y=>[y.id,y])),P=new Map;for(const y of t.snapshot.tasks){if(!y.projectId)continue;const N=P.get(y.projectId)??[];N.push(y),P.set(y.projectId,N)}return new Map(t.snapshot.dashboard.projects.map(y=>{const N=k.get(y.goalId)??null,A=P.get(y.id)??[],T=y.userId?M.get(y.userId)??null:null,F=new Map;for(const L of(N==null?void 0:N.tags)??[])F.set(L.id,{id:L.id,name:L.name,kind:L.kind});for(const L of A)for(const q of L.tagIds){const G=S.get(q);G&&F.set(G.id,{id:G.id,name:G.name,kind:G.kind})}const u=Array.from(new Set(Array.from(F.values()).map(L=>L.kind))),j=[y.title,y.description,y.goalTitle,(T==null?void 0:T.displayName)??"",(T==null?void 0:T.handle)??"",(T==null?void 0:T.kind)??"",(N==null?void 0:N.description)??"",y.nextTaskTitle??"",y.momentumLabel,y.status,A.map(L=>L.title).join(" "),Array.from(F.values()).map(L=>`${L.name} ${L.kind}`).join(" ")].join(" ").toLowerCase();return[y.id,{tagIds:Array.from(F.keys()),tags:Array.from(F.values()),taskIds:A.map(L=>L.id),typeKeys:u,userId:y.userId,searchText:j}]}))},[t.snapshot.dashboard.goals,t.snapshot.dashboard.projects,t.snapshot.tags,t.snapshot.tasks,t.snapshot.users]),b=c.useMemo(()=>{var T,F,u,j,L;const k=new Map,S=new Map,M=new Map,P=new Map,y=new Map,N=new Map,A=new Map;for(const q of t.snapshot.dashboard.projects){const G=f.get(q.id);if(G){S.has(q.goalId)||S.set(q.goalId,new Set),S.get(q.goalId).add(q.id),y.has(q.status)||y.set(q.status,new Set),y.get(q.status).add(q.id);for(const Q of G.taskIds)M.has(Q)||M.set(Q,new Set),M.get(Q).add(q.id);for(const Q of G.tags)P.has(Q.id)||P.set(Q.id,new Set),P.get(Q.id).add(q.id);for(const Q of G.typeKeys)N.has(Q)||N.set(Q,new Set),N.get(Q).add(q.id);G.userId&&(A.has(G.userId)||A.set(G.userId,new Set),A.get(G.userId).add(q.id))}}for(const q of t.snapshot.dashboard.goals){const G=((T=S.get(q.id))==null?void 0:T.size)??0;G!==0&&k.set(`goal:${q.id}`,{id:`goal:${q.id}`,kind:"goal",value:q.id,label:q.title,description:Be(`${G} project${G===1?"":"s"} linked to this goal`,q.user,`${G} project${G===1?"":"s"} linked to this goal`),searchText:qe([q.title,q.description],q)})}for(const q of t.snapshot.tasks){const G=((F=M.get(q.id))==null?void 0:F.size)??0;G!==0&&k.set(`task:${q.id}`,{id:`task:${q.id}`,kind:"task",value:q.id,label:q.title,description:Be(`${G} project${G===1?"":"s"} linked to this task`,q.user,`${G} project${G===1?"":"s"} linked to this task`),searchText:qe([q.title,q.description],q)})}for(const q of t.snapshot.tags){const G=((u=P.get(q.id))==null?void 0:u.size)??0;G!==0&&k.set(`tag:${q.id}`,{id:`tag:${q.id}`,kind:"tag",value:q.id,label:q.name,description:Be(`${G} project${G===1?"":"s"} touching this tag`,q.user,`${G} project${G===1?"":"s"} touching this tag`),searchText:qe([q.name,q.kind,q.description],q)})}for(const[q,G]of Object.entries(x))q==="all"||G===0||k.set(`status:${q}`,{id:`status:${q}`,kind:"status",value:q,label:q==="paused"?"Suspended":q==="completed"?"Finished":"Active",description:`${G} project${G===1?"":"s"} currently ${q==="paused"?"suspended":q==="completed"?"finished":"active"}`,searchText:`${q} ${q==="paused"?"suspended":""} ${q==="completed"?"finished":""}`});for(const[q,G]of Object.entries(wb)){const Q=((j=N.get(q))==null?void 0:j.size)??0;Q!==0&&k.set(`type:${q}`,{id:`type:${q}`,kind:"type",value:q,label:G,description:`${Q} project${Q===1?"":"s"} linked to ${G.toLowerCase()} tags`,searchText:`${G} ${q} project type`})}for(const q of t.snapshot.users){const G=((L=A.get(q.id))==null?void 0:L.size)??0;G!==0&&k.set(`user:${q.id}`,{id:`user:${q.id}`,kind:"user",value:q.id,label:q.displayName,description:`${G} project${G===1?"":"s"} owned by this ${q.kind}`,searchText:`${q.displayName} ${q.handle} ${q.kind} ${q.description}`})}return Array.from(k.values()).sort((q,G)=>q.label.localeCompare(G.label))},[x,f,t.snapshot.dashboard.goals,t.snapshot.dashboard.projects,t.snapshot.tags,t.snapshot.tasks,t.snapshot.users]),m=c.useMemo(()=>r.map(k=>b.find(S=>S.id===k)).filter(Boolean),[b,r]),h=c.useMemo(()=>{const k=vb(n);return br(t.snapshot.dashboard.projects,s).filter(S=>{const M=f.get(S.id);return!M||!m.every(y=>{switch(y.kind){case"goal":return S.goalId===y.value;case"task":return M.taskIds.includes(y.value);case"tag":return M.tagIds.includes(y.value);case"status":return S.status===y.value;case"type":return M.typeKeys.includes(y.value);case"user":return M.userId===y.value;default:return!0}})?!1:k?M.searchText.includes(k):!0})},[s,f,n,m,t.snapshot.dashboard.projects]),p=s==="all"?x.all:x[s],v=n.trim().length>0||r.length>0?`${h.length} matching project${h.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"}`,I=async k=>{o(k);try{await t.patchProject(k,{status:"active"})}finally{o(null)}};return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{entityKind:"project",title:e.jsx(_e,{kind:"project",label:"Projects",variant:"heading",size:"lg"}),titleText:"Projects",description:"Projects are the concrete paths that move a life goal forward. Filter the active stack by default, then pull suspended or finished work back into view whenever you need to revive or inspect it.",badge:`${t.snapshot.dashboard.projects.length} total projects`}),t.snapshot.dashboard.projects.length===0?e.jsx(gt,{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(Le,{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.jsxs(e.Fragment,{children:[e.jsx(fb,{query:n,onQueryChange:a,options:b,selectedOptionIds:r,onSelectedOptionIdsChange:l,resultSummary:v}),e.jsx(xr,{value:s,counts:x,onChange:i}),h.length===0?e.jsxs(se,{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. Clear the search, or switch the collection filter to pull suspended or finished projects back in."})]}):e.jsx("div",{className:"grid gap-4 lg:grid-cols-2 2xl:grid-cols-3",children:h.map(k=>{const S=Tt(t.snapshot.dashboard.notesSummaryByEntity,"project",k.id),M=f.get(k.id),P=(M==null?void 0:M.tags.slice(0,3))??[];return e.jsxs(se,{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 flex-wrap items-center gap-2",children:[e.jsx(ke,{kind:"goal",label:k.goalTitle,compact:!0}),e.jsx($e,{user:k.user,compact:!0})]}),e.jsx(O,{className:k.status==="completed"?"text-emerald-300":k.status==="paused"?"text-amber-300":"text-[var(--primary)]",children:k.status==="paused"?"Suspended":k.status==="completed"?"Finished":"Active"})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Le,{to:`/projects/${k.id}`,className:"transition hover:opacity-90",children:e.jsx(_e,{kind:"project",label:k.title,variant:"heading",size:"xl"})})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:k.description}),P.length>0?e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:P.map(y=>e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:y.name},y.id))}):null,e.jsx("div",{className:"mt-4",children:e.jsx(ts,{value:k.progress,tone:k.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:k.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:k.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:k.earnedPoints})]})]}),e.jsx("div",{className:"mt-5 text-[11px] uppercase tracking-[0.16em] text-white/40",children:k.nextTaskTitle?`Next move: ${k.nextTaskTitle}`:"Ready for the next task"}),e.jsx("div",{className:"mt-4",children:e.jsx(yt,{entityType:"project",entityId:k.id,count:S.count})}),e.jsxs("div",{className:"mt-5 flex flex-wrap items-center justify-between gap-3 pt-1",children:[e.jsx(Le,{to:`/projects/${k.id}`,children:e.jsx(W,{variant:"ghost",children:"Open project"})}),s!=="active"&&k.status!=="active"?e.jsx(W,{variant:"secondary",pending:d===k.id,pendingLabel:"Restarting…",onClick:()=>void I(k.id),children:"Restart"}):null]})]},k.id)})})]})]})}const vr=[{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."}],jb=vr[1].value,Nb="medium",kb="medium",Sb="Prepare reviewable Forge wiki drafts from the source. Do not dump raw chats or transcripts. Extract durable people, projects, goals, tasks, habits, strategies, values, notes, evidence, self-observations, and recurring patterns. Keep the main page concise, split strong subtopics into article candidates with meaningful [[wiki links]], and organize knowledge around durable Forge themes such as people, projects, concepts, sources, chronicle, values, practices, health, places, decisions, and enduring life areas like relationships, work, learning, finances, and home.";function wc(t){const s=t==null?void 0:t.reasoningEffort;return s==="none"||s==="low"||s==="medium"||s==="high"||s==="xhigh"?s:Nb}function vc(t){const s=t==null?void 0:t.verbosity;return s==="low"||s==="medium"||s==="high"?s:kb}function Cb(t){return{reasoningEffort:t.reasoningEffort,verbosity:t.verbosity}}function Hl(t){var i;return{model:((i=vr.find(n=>n.value===t.model))==null?void 0:i.label)??t.model,reasoning:wc(t.metadata),verbosity:vc(t.metadata),hasKey:!!t.secretId}}function Xl(t){return{label:(t==null?void 0:t.label)??"Forge wiki ingest",model:(t==null?void 0:t.model)??jb,apiKey:"",baseUrl:(t==null?void 0:t.baseUrl)??"https://api.openai.com/v1",systemPrompt:(t==null?void 0:t.systemPrompt)??Sb,reasoningEffort:wc(t==null?void 0:t.metadata),verbosity:vc(t==null?void 0:t.metadata)}}function Jl({label:t,options:s,value:i,onChange:n,tooltip:a}){return e.jsxs("div",{className:"grid gap-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.18em] text-white/48",children:t}),e.jsx(Xe,{content:a})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map(r=>{const l=r.value===i;return e.jsxs("button",{type:"button",className:re("rounded-full border px-3 py-2 text-left transition",l?"border-[rgba(192,193,255,0.35)] bg-[rgba(192,193,255,0.16)] text-white":"border-white/10 bg-white/[0.03] text-white/62 hover:border-white/18 hover:text-white"),onClick:()=>n(r.value),children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-[0.12em]",children:r.label}),e.jsx("div",{className:"mt-1 text-[11px] leading-5 text-inherit/80",children:r.description})]},r.value)})})]})}function Ib({open:t,onOpenChange:s,profile:i,onSaved:n}){const[a,r]=c.useState(()=>Xl(i)),[l,d]=c.useState(null),[o,x]=c.useState(null);c.useEffect(()=>{t&&(r(Xl(i)),d(null),x(null))},[t,i]),c.useEffect(()=>{t&&(d(null),x(null))},[t,a.apiKey,a.baseUrl,a.model,a.reasoningEffort,a.verbosity]);const f=!!(i!=null&&i.secretId&&!a.apiKey.trim()),b=c.useMemo(()=>a.label.trim().length>0&&a.model.trim().length>0&&(a.apiKey.trim().length>0||!!(i!=null&&i.secretId)),[a.apiKey,a.label,a.model,i==null?void 0:i.secretId]),m=ge({mutationFn:async()=>ap({id:i==null?void 0:i.id,label:a.label.trim(),provider:"openai-responses",baseUrl:a.baseUrl.trim(),model:a.model,apiKey:a.apiKey.trim()||void 0,systemPrompt:a.systemPrompt.trim(),reasoningEffort:a.reasoningEffort,verbosity:a.verbosity,enabled:!0,metadata:Cb({reasoningEffort:a.reasoningEffort,verbosity:a.verbosity})}),onSuccess:async w=>{d({tone:"success",message:"OpenAI profile saved."}),await n(w.profile),s(!1)},onError:w=>{d({tone:"error",message:w instanceof Error?w.message:"Unable to save the profile."})}}),h=ge({mutationFn:async()=>np({profileId:i==null?void 0:i.id,provider:"openai-responses",baseUrl:a.baseUrl.trim(),model:a.model,apiKey:a.apiKey.trim()||void 0,reasoningEffort:a.reasoningEffort,verbosity:a.verbosity}),onSuccess:({result:w})=>{x(w),d({tone:"success",message:w.usingStoredKey?"Stored OpenAI key worked.":"OpenAI key accepted."})},onError:w=>{x(null),d({tone:"error",message:w instanceof Error?w.message:"OpenAI rejected the connection test."})}}),p=[{id:"profile",eyebrow:"OpenAI profile",title:i?"Update the wiki drafting profile":"Create the wiki drafting profile",description:"Start with the identity and credentials Forge will use for wiki auto-ingest. The key stays in local encrypted storage.",render:(w,v)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Profile label",description:"This is the name Forge will show in Wiki Settings.",labelHelp:"Use a plain operational label like Forge wiki ingest.",children:e.jsx(ie,{value:w.label,onChange:I=>v({label:I.target.value}),placeholder:"Forge wiki ingest"})}),e.jsx(Y,{label:"OpenAI API key",description:"Paste a key from your OpenAI account to enable auto-ingest.",labelHelp:"Leave this blank when editing if you want to keep the saved key already stored in Forge.",hint:f?"Using the saved key until you replace it.":"Forge will store the key locally and use it for future ingest runs.",children:e.jsx(ie,{value:w.apiKey,onChange:I=>v({apiKey:I.target.value}),type:"password",placeholder:i!=null&&i.secretId?"Saved key already present":"sk-..."})})]})},{id:"model",eyebrow:"Model choice",title:"Pick the GPT-5.4 model tier",description:"Choose the OpenAI model Forge should use when it drafts wiki pages and entity proposals from imported source material.",render:(w,v)=>e.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:vr.map(I=>{const k=w.model===I.value;return e.jsxs("button",{type:"button",className:re("rounded-[24px] border p-4 text-left transition",k?"border-[rgba(192,193,255,0.38)] bg-[rgba(192,193,255,0.13)]":"border-white/10 bg-white/[0.03] hover:border-white/18 hover:bg-white/[0.05]"),onClick:()=>v({model:I.value}),children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[e.jsx(Cm,{className:"size-4 text-[var(--primary)]"}),e.jsx("span",{className:"font-semibold",children:I.label})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:I.description})]},I.value)})})},{id:"controls",eyebrow:"Drafting controls",title:"Tune reasoning and output shape",description:"Set how much thinking budget Forge should spend and how verbose the generated wiki drafts should be. Advanced settings stay optional.",render:(w,v)=>e.jsxs(e.Fragment,{children:[e.jsx(Jl,{label:"Thinking",value:w.reasoningEffort,onChange:I=>v({reasoningEffort:I}),tooltip:"OpenAI exposes this as reasoning.effort on the Responses API. Higher values spend more reasoning tokens before the model drafts the result.",options:[{value:"none",label:"None",description:"Fastest response."},{value:"low",label:"Low",description:"Short reasoning budget."},{value:"medium",label:"Medium",description:"Balanced depth."},{value:"high",label:"High",description:"More drafting effort."},{value:"xhigh",label:"X-High",description:"Deepest reasoning."}]}),e.jsx(Jl,{label:"Verbosity",value:w.verbosity,onChange:I=>v({verbosity:I}),tooltip:"OpenAI exposes this as text.verbosity on the Responses API. Lower values keep drafts tighter; higher values let the model write fuller structured output.",options:[{value:"low",label:"Low",description:"Shorter drafts."},{value:"medium",label:"Medium",description:"Balanced detail."},{value:"high",label:"High",description:"Richer drafting."}]}),e.jsxs("div",{className:"grid gap-4 rounded-[24px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.18em] text-white/48",children:"Advanced"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:"Leave these at the defaults unless you are intentionally routing through another compatible endpoint or customizing the drafting behavior."})]}),e.jsx(Y,{label:"Base URL",description:"Forge defaults to the official OpenAI API endpoint.",children:e.jsx(ie,{value:w.baseUrl,onChange:I=>v({baseUrl:I.target.value}),placeholder:"https://api.openai.com/v1"})}),e.jsx(Y,{label:"System prompt",description:"Optional custom instructions for how wiki drafts should be structured.",children:e.jsx(Ce,{value:w.systemPrompt,onChange:I=>v({systemPrompt:I.target.value}),className:"min-h-36",placeholder:"Optional system prompt for wiki drafting"})})]})]})},{id:"review",eyebrow:"Review and test",title:"Check the configuration before saving",description:"Review the final setup, run a live connection test, and then save the profile once the model accepts the configuration.",render:w=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[e.jsx(vt,{className:"size-4 text-[var(--primary)]"}),e.jsx("div",{className:"text-sm font-semibold",children:"Profile summary"})]}),e.jsxs("div",{className:"mt-4 grid gap-3 text-sm",children:[e.jsxs("div",{className:"rounded-[18px] 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:"Label"}),e.jsx("div",{className:"mt-2 text-white",children:w.label||"Untitled profile"})]}),e.jsxs("div",{className:"rounded-[18px] 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:"OpenAI Responses API"})]}),e.jsxs("div",{className:"rounded-[18px] 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:w.model})]})]})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[e.jsx(Qs,{className:"size-4 text-[var(--primary)]"}),e.jsx("div",{className:"text-sm font-semibold",children:"Runtime controls"})]}),e.jsxs("div",{className:"mt-4 grid gap-3 text-sm",children:[e.jsxs("div",{className:"rounded-[18px] 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:"Key status"}),e.jsx("div",{className:"mt-2 text-white",children:w.apiKey.trim()?"New key ready to test":i!=null&&i.secretId?"Saved key available":"No key saved yet"})]}),e.jsxs("div",{className:"rounded-[18px] 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:"Controls"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-xs",children:[e.jsxs("span",{className:"rounded-full bg-white/[0.06] px-3 py-1.5 text-white/78",children:["thinking ",w.reasoningEffort]}),e.jsxs("span",{className:"rounded-full bg-white/[0.06] px-3 py-1.5 text-white/78",children:["verbosity ",w.verbosity]})]})]}),e.jsxs("div",{className:"rounded-[18px] 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:"Base URL"}),e.jsx("div",{className:"mt-2 break-all text-white/72",children:w.baseUrl})]})]})]})]}),e.jsxs("div",{className:"grid gap-3 rounded-[22px] border border-white/8 bg-white/[0.03] 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-semibold text-white",children:"Connection check"}),e.jsx("div",{className:"mt-1 text-sm leading-6 text-white/58",children:"Test the exact model and control settings before you save them."})]}),e.jsx(W,{variant:"secondary",pending:h.isPending,pendingLabel:"Testing",disabled:!b,onClick:()=>void h.mutateAsync(),children:"Test connection"})]}),l?e.jsx("div",{className:re("rounded-[20px] border px-4 py-3 text-sm leading-6",l.tone==="success"?"border-emerald-400/18 bg-emerald-400/[0.08] text-emerald-100":"border-rose-400/18 bg-rose-400/[0.08] text-rose-100"),children:l.message}):null,o?e.jsxs("div",{className:"rounded-[20px] border border-emerald-400/18 bg-emerald-400/[0.08] px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-emerald-100",children:[e.jsx(Im,{className:"size-4"}),"OpenAI accepted this configuration"]}),e.jsxs("div",{className:"mt-2 text-sm leading-6 text-emerald-100/86",children:["Preview: ",o.outputPreview]})]}):null]})]})}];return e.jsx(it,{open:t,onOpenChange:s,eyebrow:"OpenAI setup",title:i?"Update wiki drafting":"Set up wiki drafting",description:"Forge wiki auto-ingest uses the OpenAI Responses API to turn uploads into draft wiki pages and entity proposals before you review them.",value:a,onChange:r,steps:p,submitLabel:i?"Update profile":"Save profile",pending:m.isPending,pendingLabel:"Saving",error:(l==null?void 0:l.tone)==="error"?l.message:null,contentClassName:"lg:w-[min(60rem,calc(100vw-1.5rem))]",onSubmit:async()=>{if(!b){d({tone:"error",message:a.label.trim().length===0?"Add a profile label before saving.":a.model.trim().length===0?"Pick a model before saving.":"Add an OpenAI API key or keep using the saved one before saving."});return}await m.mutateAsync()}})}const da=[{to:"/settings",label:"General",icon:Xo},{to:"/settings/users",label:"Users",icon:Yn},{to:"/settings/calendar",label:"Calendar",icon:us},{to:"/settings/mobile",label:"Mobile",icon:Tm},{to:"/settings/agents",label:"Agents",icon:ka},{to:"/settings/wiki",label:"Wiki",icon:Gn},{to:"/settings/logs",label:"Logs",icon:Pm},{to:"/settings/rewards",label:"Rewards",icon:Mm},{to:"/settings/bin",label:"Bin",icon:En}];function gn(t,s){return s==="/settings"?t==="/settings":t===s||t.startsWith(`${s}/`)}function gs({className:t}){const s=ki(),[i,n]=c.useState(!1),a=c.useMemo(()=>[...da].sort((r,l)=>l.to.length-r.to.length).find(r=>gn(s.pathname,r.to))??da[0],[s.pathname]);return e.jsxs(e.Fragment,{children:[e.jsxs(se,{className:re("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:da.map(r=>e.jsxs(Ks,{to:r.to,end:r.to==="/settings",className:({isActive:l})=>re("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||gn(s.pathname,r.to)?"bg-[var(--primary)]/[0.18] text-[var(--primary)]":"bg-white/[0.04] text-white/58 hover:bg-white/[0.08] hover:text-white"),children:[e.jsx(r.icon,{className:"size-3.5"}),e.jsx("span",{children:r.label})]},r.to))})}),e.jsx("div",{className:"flex items-center justify-between gap-3 lg:hidden",children:e.jsxs("button",{type:"button",className:"inline-flex min-w-0 flex-1 items-center justify-between rounded-full bg-white/[0.06] px-4 py-3 text-left",onClick:()=>n(!0),children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(a.icon,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"truncate text-sm font-medium text-white",children:a.label})]}),e.jsx("span",{className:"text-[10px] uppercase tracking-[0.16em] text-white/42",children:"Switch"})]})})]}),i?e.jsx("div",{className:"fixed inset-0 z-50 bg-[rgba(5,10,18,0.86)] px-4 py-5 backdrop-blur-xl lg:hidden",children:e.jsxs("div",{className:"mx-auto flex h-full max-w-xl flex-col rounded-[32px] bg-[linear-gradient(180deg,rgba(16,25,33,0.98),rgba(11,18,25,0.98))] p-5 shadow-[0_30px_80px_rgba(0,0,0,0.35)]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/38",children:"Settings"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:"Navigate to section"})]}),e.jsx(W,{variant:"secondary",onClick:()=>n(!1),children:"Close"})]}),e.jsx("div",{className:"mt-6 grid gap-3 overflow-y-auto",children:da.map(r=>e.jsxs(Ks,{to:r.to,end:r.to==="/settings",onClick:()=>n(!1),className:re("flex items-center justify-between rounded-[24px] px-4 py-4 transition",gn(s.pathname,r.to)?"bg-[var(--primary)]/[0.14] text-white":"bg-white/[0.04] text-white/70"),children:[e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(r.icon,{className:"size-4 text-[var(--primary)]"}),e.jsx("span",{className:"text-base font-medium",children:r.label})]}),e.jsx("span",{className:"text-[10px] uppercase tracking-[0.16em] text-white/36",children:"Open"})]},r.to))})]})}):null]})}function Tb(){var R;const t=We(),[s,i]=ft(),[n,a]=c.useState(""),[r,l]=c.useState(""),[d,o]=c.useState("personal"),[x,f]=c.useState("Fast wiki search"),[b,m]=c.useState("text-embedding-3-small"),[h,p]=c.useState("https://api.openai.com/v1"),[w,v]=c.useState(""),[I,k]=c.useState("1200"),[S,M]=c.useState("200"),[P,y]=c.useState(s.get("setupLlm")==="1"),[N,A]=c.useState(null),T=pe({queryKey:["forge-wiki-settings"],queryFn:Ua}),F=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"]})])},u=ge({mutationFn:()=>Gu({label:n.trim(),description:r.trim(),visibility:d}),onSuccess:async()=>{a(""),l(""),o("personal"),await F()}}),j=ge({mutationFn:()=>rp({label:x.trim(),model:b.trim(),baseUrl:h.trim(),apiKey:w.trim()||void 0,chunkSize:Number(I),chunkOverlap:Number(S)}),onSuccess:async()=>{v(""),await F()}}),L=ge({mutationFn:({kind:C,profileId:J})=>lp(C,J),onSuccess:F}),q=ge({mutationFn:()=>sp(),onSuccess:F}),G=ge({mutationFn:()=>ip(),onSuccess:F});if(c.useEffect(()=>{s.get("setupLlm")==="1"&&(A(null),y(!0))},[s]),T.isLoading)return e.jsx(xt,{eyebrow:"Wiki settings",title:"Loading wiki controls",description:"Fetching spaces and profile configuration for the Forge wiki."});if(T.isError)return e.jsx(Oe,{eyebrow:"Wiki settings",error:T.error,onRetry:()=>void T.refetch()});const Q=(R=T.data)==null?void 0:R.settings;if(!Q)return e.jsx(Oe,{eyebrow:"Wiki settings",error:new Error("Forge returned an empty wiki settings payload."),onRetry:()=>void T.refetch()});const ne=Q.llmProfiles.find(C=>C.enabled)??Q.llmProfiles[0]??null,H=ne?Hl(ne):null,_="Canonical knowledge lives as markdown and media files on disk, with Forge keeping a synced metadata, link, and search index on top. 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.",U=C=>{if(y(C),!C){const J=new URLSearchParams(s);J.delete("setupLlm"),i(J,{replace:!0})}};return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1440px] gap-5",children:[e.jsx(Ke,{eyebrow:"File-first memory",title:"Wiki Settings",titleText:"Wiki Settings",description:"Configure file-backed spaces, parse models, and embedding profiles for the Forge wiki memory system.",badge:`${Q.spaces.length} spaces · ${Q.embeddingProfiles.length} embedding profiles`,actions:e.jsxs(e.Fragment,{children:[e.jsx(W,{variant:"secondary",pending:q.isPending,pendingLabel:"Syncing",onClick:()=>void q.mutateAsync(),children:"Sync vault"}),e.jsx(W,{pending:G.isPending,pendingLabel:"Reindexing",onClick:()=>void G.mutateAsync(),disabled:Q.embeddingProfiles.length===0,children:"Reindex embeddings"})]})}),e.jsx(gs,{}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(se,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Qs,{className:"size-4 text-[var(--secondary)]"}),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:"Set the OpenAI model that turns imported source material into draft wiki pages and entity proposals before review."})]})]}),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:(ne==null?void 0:ne.label)??"OpenAI not configured"}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:ne?"This profile is used by the wiki ingest flow when Forge turns uploads into draft pages and entities.":"Forge needs an OpenAI profile before auto-ingest can create structured draft pages instead of importing one raw dump page."})]}),e.jsxs(W,{onClick:()=>{A(ne),y(!0)},children:[e.jsx(vt,{className:"size-4"}),ne?"Edit OpenAI":"Set up OpenAI"]})]}),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:(H==null?void 0:H.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:"Thinking"}),e.jsx("div",{className:"mt-2 text-white",children:(H==null?void 0:H.reasoning)??"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:"Key"}),e.jsx("div",{className:"mt-2 flex items-center gap-2 text-white",children:H!=null&&H.hasKey?e.jsxs(e.Fragment,{children:[e.jsx(Em,{className:"size-4 text-emerald-300"}),"Saved"]}):"Missing"})]})]})]}),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.jsx("div",{className:"text-sm leading-6 text-white/58",children:"Forge exposes the current GPT-5.4 family with model choice, reasoning effort, and verbosity on top of the OpenAI Responses API."}),e.jsx("div",{className:"flex flex-wrap gap-2",children:["GPT-5.4","GPT-5.4 mini","GPT-5.4 nano"].map(C=>e.jsx(O,{className:"bg-white/[0.06] text-white/78",children:C},C))}),e.jsxs(W,{variant:"secondary",onClick:()=>{A(ne),y(!0)},children:["Open setup",e.jsx(Ni,{className:"size-4"})]})]})]}),e.jsxs("div",{className:"grid gap-3",children:[Q.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,Q.llmProfiles.map(C=>{const J=Hl(C);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:C.label}),e.jsxs("div",{className:"mt-1 text-xs text-white/46",children:[J.model," · thinking ",J.reasoning," · verbosity ",J.verbosity]})]}),e.jsxs("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:()=>{A(C),y(!0)},children:e.jsx(ys,{className:"size-4"})}),e.jsx("button",{type:"button",className:"rounded-full p-2 text-white/48 transition hover:bg-white/[0.08] hover:text-white",onClick:()=>void L.mutateAsync({kind:"llm",profileId:C.id}),children:e.jsx(bt,{className:"size-4"})})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs text-white/58",children:[e.jsx(O,{className:"bg-white/[0.06] text-white/76",children:C.baseUrl}),e.jsx(O,{className:"bg-white/[0.06] text-white/76",children:J.hasKey?"key saved":"key missing"})]})]},C.id)})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(se,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Am,{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(Xe,{content:_,label:"Explain the wiki operating model"})]}),e.jsx("div",{className:"text-xs leading-5 text-white/50",children:"Personal and shared wiki vaults map to explicit file-backed roots and metadata namespaces."})]})]}),e.jsx("div",{className:"grid gap-3",children:Q.spaces.map(C=>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:C.label}),e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/42",children:C.visibility})]}),e.jsx("div",{className:"text-xs text-white/46",children:C.slug}),e.jsx("div",{className:"text-sm text-white/60",children:C.description||"No description yet."})]},C.id))}),e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsx(ie,{value:n,onChange:C=>a(C.target.value),placeholder:"New space label"}),e.jsx(ie,{value:r,onChange:C=>l(C.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:d,onChange:C=>o(C.target.value),children:[e.jsx("option",{value:"personal",children:"Personal"}),e.jsx("option",{value:"shared",children:"Shared"})]}),e.jsx(W,{pending:u.isPending,pendingLabel:"Creating",disabled:!n.trim(),onClick:()=>void u.mutateAsync(),children:"Create space"})]})]}),e.jsxs(se,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Lm,{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:Q.embeddingProfiles.map(C=>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:C.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 L.mutateAsync({kind:"embedding",profileId:C.id}),children:e.jsx(bt,{className:"size-4"})})]}),e.jsxs("div",{className:"text-xs text-white/46",children:[C.model," · ",C.baseUrl]}),e.jsxs("div",{className:"text-sm text-white/60",children:["chunkSize ",C.chunkSize," · overlap"," ",C.chunkOverlap]})]},C.id))}),e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsx(ie,{value:x,onChange:C=>f(C.target.value),placeholder:"Profile label"}),e.jsx(ie,{value:b,onChange:C=>m(C.target.value),placeholder:"Model"}),e.jsx(ie,{value:h,onChange:C=>p(C.target.value),placeholder:"Base URL"}),e.jsx(ie,{value:w,onChange:C=>v(C.target.value),placeholder:"API key (optional)",type:"password"}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsx(ie,{value:I,onChange:C=>k(C.target.value),placeholder:"Chunk size",type:"number"}),e.jsx(ie,{value:S,onChange:C=>M(C.target.value),placeholder:"Chunk overlap",type:"number"})]}),e.jsx(W,{pending:j.isPending,pendingLabel:"Saving",disabled:!x.trim()||!b.trim(),onClick:()=>void j.mutateAsync(),children:"Save embedding profile"})]})]})]})]}),e.jsx(Ib,{open:P,onOpenChange:U,profile:N,onSaved:F})]})}function yr(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 yc(t){return yr(t).every(s=>s.satisfied)}function jr(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 Pb(t){return t.trim().toLowerCase()}function pi(t,s){return t.includes(s)?t.filter(i=>i!==s):[...t,s]}function Yl(t,s){return t.some(i=>i.entityType===s.entityType&&i.entityId===s.entityId)?t.filter(i=>!(i.entityType===s.entityType&&i.entityId===s.entityId)):[...t,s]}function Vl(t,s){if(t.length!==s.length)return!1;const i=new Set(s);return t.every(n=>i.has(n))}function La(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 Mb(t){const s=new Map(t.graph.nodes.map(d=>[d.id,d])),i=new Map(t.graph.nodes.map(d=>[d.id,0])),n=new Map,a=new Map(t.graph.nodes.map((d,o)=>[d.id,o]));for(const d of t.graph.nodes)n.set(d.id,[]);for(const d of t.graph.edges)i.set(d.to,(i.get(d.to)??0)+1),n.set(d.from,[...n.get(d.from)??[],d.to]);const r=t.graph.nodes.filter(d=>(i.get(d.id)??0)===0).sort((d,o)=>(a.get(d.id)??0)-(a.get(o.id)??0)).map(d=>d.id),l=[];for(;r.length>0;){r.sort((x,f)=>(a.get(x)??0)-(a.get(f)??0));const d=r.shift();if(!d)continue;const o=s.get(d);if(o){l.push(o);for(const x of n.get(d)??[]){const f=(i.get(x)??0)-1;i.set(x,f),f===0&&r.push(x)}}}return l.length===t.graph.nodes.length?l:t.graph.nodes}function Eb(t){const s=new Map;for(const n of t.graph.nodes)s.set(n.id,[]);for(const n of t.graph.edges)s.set(n.to,[...s.get(n.to)??[],n.from]);const i=Mb(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:i.map((n,a)=>{const r=s.get(n.id)??[],l=i[a-1],d=l?s.get(l.id)??[]:[];let o="custom";return r.length===0?o="start":l&&Vl(r,[l.id])?o="after_previous":l&&r.length>0&&Vl(r,d)&&(o="parallel_with_previous"),La(n.entityType,{id:n.id,entityId:n.entityId,branchLabel:n.branchLabel,notes:n.notes,dependencyMode:o,customPredecessorIds:r})})}}function jc(t){const s=new Map,i=new Set;for(const[n,a]of t.entries()){const r=t[n-1];let l;switch(a.dependencyMode){case"after_previous":l=r?[r.id]:[];break;case"parallel_with_previous":l=r?[...s.get(r.id)??[]]:[];break;case"custom":l=a.customPredecessorIds.filter(d=>i.has(d));break;case"start":default:l=[];break}s.set(a.id,l),i.add(a.id)}return s}function Zl(t){const s=jc(t),i=new Set,n=new Set;function a(r){if(n.has(r))return!0;if(i.has(r))return!1;i.add(r),n.add(r);for(const l of s.get(r)??[])if(a(l))return!0;return n.delete(r),!1}return t.some(r=>a(r.id))}const eo={title:"",overview:"",endStateDescription:"",status:"active",userId:null,targetGoalIds:[],targetProjectIds:[],linkedEntities:[],nodes:[La("project",{dependencyMode:"start"})]};function Zs(t,s){const i=s[0];return{title:"",description:"",goalId:(i==null?void 0:i.goalId)??"",projectId:(i==null?void 0:i.id)??"",userId:(i==null?void 0:i.userId)??t,priority:"medium",effort:"deep",energy:"steady",points:60}}function Ab(t,s,i){const n=jc(t.nodes),a=new Set(t.nodes.filter(r=>r.entityId).map(r=>r.id));return{nodes:t.nodes.filter(r=>r.entityId).map(r=>{var l,d;return{id:r.id,entityType:r.entityType,entityId:r.entityId,title:r.entityType==="project"?((l=s.get(r.entityId))==null?void 0:l.title)??r.entityId:((d=i.get(r.entityId))==null?void 0:d.title)??r.entityId,branchLabel:r.branchLabel.trim(),notes:r.notes.trim()}}),edges:t.nodes.flatMap(r=>a.has(r.id)?(n.get(r.id)??[]).filter(l=>a.has(l)).map(l=>({from:l,to:r.id,label:"",condition:""})):[])}}function to(t){return((t==null?void 0:t.progress)??0)/100}function Lb(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 Db(t){const{draft:s,graph:i,goals:n,projects:a,projectsById:r,tasks:l,tasksById:d}=t,o=new Map(i.nodes.map(_=>[_.id,_.entityType==="project"?to(r.get(_.entityId)):Lb(d.get(_.entityId))])),x=new Map;for(const _ of i.nodes)x.set(_.id,[]);for(const _ of i.edges)x.set(_.to,[...x.get(_.to)??[],_.from]);const f=i.nodes.filter(_=>(o.get(_.id)??0)>=1).map(_=>_.id),b=i.nodes.filter(_=>(o.get(_.id)??0)>0).map(_=>_.id),m=i.nodes.filter(_=>{var U,R;return _.entityType==="project"?((U=r.get(_.entityId))==null?void 0:U.status)==="paused":((R=d.get(_.entityId))==null?void 0:R.status)==="blocked"}).map(_=>_.id),h=i.nodes.filter(_=>(o.get(_.id)??0)<=0?!1:(x.get(_.id)??[]).some(R=>(o.get(R)??0)<1)).map(_=>_.id),p=i.nodes.filter(_=>(o.get(_.id)??0)>=1?!1:(x.get(_.id)??[]).every(R=>(o.get(R)??0)>=1)).map(_=>_.id),w=new Map(n.map(_=>[_.id,_])),v=s.targetGoalIds.map(_=>{var R;const U=l.filter(C=>C.goalId===_);return U.length===0?((R=w.get(_))==null?void 0:R.status)==="completed"?1:0:U.filter(C=>C.status==="done").length/U.length}),I=s.targetProjectIds.map(_=>to(r.get(_))),k=[...v,...I],S=i.nodes.length===0?0:i.nodes.reduce((_,U)=>_+(o.get(U.id)??0),0)/i.nodes.length,M=k.length===0?S:k.reduce((_,U)=>_+U,0)/k.length,P=new Set(i.nodes.filter(_=>_.entityType==="project").map(_=>_.entityId)),y=new Set(i.nodes.filter(_=>_.entityType==="task").map(_=>_.entityId)),N=new Set,A=new Set,T=new Set;for(const _ of s.targetProjectIds){const U=a.find(R=>R.id===_);if(U&&!P.has(U.id)&&U.status!=="completed"){const R=`project:${U.id}`;N.add(R),A.add(R)}for(const R of l.filter(C=>C.projectId===_))if(!y.has(R.id)&&["focus","in_progress","done","blocked"].includes(R.status)){const C=`task:${R.id}`;N.add(C),R.status==="done"?T.add(C):A.add(C)}}for(const _ of s.targetGoalIds)for(const U of l.filter(R=>R.goalId===_))if(!y.has(U.id)&&["focus","in_progress","done","blocked"].includes(U.status)){const R=`task:${U.id}`;N.add(R),U.status==="done"?T.add(R):A.add(R)}const F=Math.max(1,i.nodes.length),u=N.size,j=m.length/F,L=Math.max(0,Math.min(100,Math.round(S*100))),q=Math.max(0,Math.min(100,Math.round(100-h.length/F*100))),G=Math.max(0,Math.min(100,Math.round(100-u/F*100))),Q=Math.max(0,Math.min(100,Math.round(Math.max(0,Math.min(1,M*.8+(1-j)*.2))*100))),ne=Math.max(0,Math.min(100,Math.round(M*100)));return{alignmentScore:Math.max(0,Math.min(100,Math.round(L*.35+q*.3+G*.2+Q*.15))),planCoverageScore:L,sequencingScore:q,scopeDisciplineScore:G,qualityScore:Q,targetProgressScore:ne,completedNodeCount:f.length,startedNodeCount:b.length,readyNodeCount:p.length,totalNodeCount:F,completedTargetCount:k.filter(_=>_>=1).length,totalTargetCount:k.length,offPlanEntityCount:u,offPlanActiveEntityCount:A.size,offPlanCompletedEntityCount:T.size,activeNodeIds:p.slice(0,8),nextNodeIds:p.slice(0,5),blockedNodeIds:m,outOfOrderNodeIds:h}}function $b({node:t,index:s,total:i,projectsById:n,tasksById:a,usersById:r,allNodes:l,onUpdate:d,onRemove:o}){const{attributes:x,listeners:f,setNodeRef:b,transform:m,transition:h,isDragging:p}=md({id:t.id}),w=t.entityType==="project"?n.get(t.entityId):a.get(t.entityId),v=w&&"userId"in w&&w.userId?r.get(w.userId)??w.user??null:null,I=l.slice(0,s);return e.jsxs("div",{ref:b,style:{transform:hd.Transform.toString(m),transition:h},className:re("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",...x,...f,children:e.jsx(Dm,{className:"size-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(O,{className:"bg-white/[0.08] text-white/76",children:["Step ",s+1]}),e.jsx(O,{className:"bg-white/[0.08] text-white/76",children:t.entityType}),w?e.jsx(ke,{kind:t.entityType,label:w.title,compact:!0,gradient:!1}):null]}),e.jsx("div",{className:"mt-3 text-base font-medium text-white",children:(w==null?void 0:w.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||(w&&"description"in w?w.description:"")||"Add an optional note if this phase needs intent or setup context."}),v?e.jsx("div",{className:"mt-3",children:e.jsx($e,{user:v,compact:!0})}):null]})]}),e.jsxs(W,{type:"button",variant:"secondary",size:"sm",className:"w-full sm:w-auto",disabled:i===1,onClick:()=>o(t.id),children:[e.jsx(bt,{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(Y,{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(tt,{value:t.dependencyMode,columns:2,onChange:k=>d(t.id,{dependencyMode:k}),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(Y,{label:"Branch label",children:e.jsx(ie,{value:t.branchLabel,onChange:k=>d(t.id,{branchLabel:k.target.value}),placeholder:"Core path, fallback lane, support branch"})}),e.jsx(Y,{label:"Step note",children:e.jsx(Ce,{value:t.notes,onChange:k=>d(t.id,{notes:k.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:I.length===0?e.jsx("div",{className:"text-sm text-white/52",children:"No earlier steps available yet."}):I.map(k=>{const S=k.entityType==="project"?n.get(k.entityId):a.get(k.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:(S==null?void 0:S.title)||`Step ${l.indexOf(k)+1}`}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/52",children:k.branchLabel||k.entityType})]}),e.jsx("input",{type:"checkbox",checked:t.customPredecessorIds.includes(k.id),onChange:()=>d(t.id,{customPredecessorIds:pi(t.customPredecessorIds,k.id)})})]},k.id)})})]}):null]})}function Nc({open:t,pending:s=!1,editingStrategy:i,goals:n,projects:a,tasks:r,habits:l,strategies:d,users:o,defaultUserId:x=null,initialStepId:f,onOpenChange:b,onSubmit:m}){const[h,p]=c.useState(eo),[w,v]=c.useState(""),[I,k]=c.useState(""),[S,M]=c.useState(""),[P,y]=c.useState(null),[N,A]=c.useState([]),[T,F]=c.useState(Zs(x,a)),[u,j]=c.useState(!1),[L,q]=c.useState(null),[G,Q]=c.useState(!1);c.useEffect(()=>{var B,de,be;if(!t)return;const g=i?Eb(i):{...eo,userId:x,nodes:[La("project",{dependencyMode:"start"})]};p(g),v(""),k(""),M(""),A([]),j(!1),F(Zs(x,a).projectId&&g.targetProjectIds[0]?{...Zs(x,a),goalId:((B=a.find(Ne=>Ne.id===g.targetProjectIds[0]))==null?void 0:B.goalId)??"",projectId:g.targetProjectIds[0]??((de=a[0])==null?void 0:de.id)??"",userId:((be=a.find(Ne=>Ne.id===g.targetProjectIds[0]))==null?void 0:be.userId)??x}:Zs(x,a)),q(null),y(null)},[x,i,t,a]);const ne=c.useDeferredValue(w),H=c.useDeferredValue(I),_=c.useDeferredValue(S),U=c.useMemo(()=>{const g=new Set(N.map(B=>B.id));return[...N,...r.filter(B=>!g.has(B.id))]},[N,r]),R=c.useMemo(()=>new Map(n.map(g=>[g.id,g])),[n]),C=c.useMemo(()=>new Map(a.map(g=>[g.id,g])),[a]),J=c.useMemo(()=>new Map(U.map(g=>[g.id,g])),[U]),ee=c.useMemo(()=>new Map(o.map(g=>[g.id,g])),[o]),le=o.find(g=>g.id===x)??null,oe=o.find(g=>g.id===h.userId)??le,ue=(g,B,de)=>{const be=Pb(g);return be.length===0||qe(B,de).includes(be)},me=c.useMemo(()=>n.filter(g=>ue(H,[g.title,g.description],g.user)),[H,n]),$=c.useMemo(()=>n.filter(g=>ue(ne,[g.title,g.description],g.user)),[n,ne]),ce=c.useMemo(()=>a.filter(g=>ue(ne,[g.title,g.description,g.goalTitle,g.status],g.user)),[ne,a]),E=c.useMemo(()=>a.filter(g=>ue(H,[g.title,g.description,g.goalTitle,g.status],g.user)),[H,a]),z=c.useMemo(()=>U.filter(g=>ue(H,[g.title,g.description,g.owner,g.status],g.user)),[U,H]),K=c.useMemo(()=>l.filter(g=>ue(H,[g.title,g.description,g.frequency,g.status],g.user)),[H,l]),je=c.useMemo(()=>d.filter(g=>g.id!==(i==null?void 0:i.id)&&ue(H,[g.title,g.overview,g.endStateDescription,g.status],g.user)),[H,i==null?void 0:i.id,d]),V=c.useMemo(()=>[...me.map(B=>({key:`goal:${B.id}`,entityType:"goal",entityId:B.id,label:B.title,description:Be(B.description,B.user,"Goal"),user:B.user??null})),...E.map(B=>({key:`project:${B.id}`,entityType:"project",entityId:B.id,label:B.title,description:Be(`${B.goalTitle}${B.goalTitle?" · ":""}${B.status}`,B.user,`Project · ${B.goalTitle}`),user:B.user??null})),...z.map(B=>({key:`task:${B.id}`,entityType:"task",entityId:B.id,label:B.title,description:Be(`${B.status} · ${B.owner}`,B.user,`Task · ${B.owner}`),user:B.user??null})),...K.map(B=>({key:`habit:${B.id}`,entityType:"habit",entityId:B.id,label:B.title,description:Be(B.description,B.user,"Habit"),user:B.user??null})),...je.map(B=>({key:`strategy:${B.id}`,entityType:"strategy",entityId:B.id,label:B.title,description:Be(B.overview,B.user,"Strategy"),user:B.user??null}))].sort((B,de)=>B.label.localeCompare(de.label)),[me,K,E,je,z]),D=c.useMemo(()=>Ab(h,C,J),[h,C,J]),X=c.useMemo(()=>Db({draft:h,graph:D,goals:n,projects:a,projectsById:C,tasks:U,tasksById:J}),[U,h,D,n,a,C,J]),he=c.useMemo(()=>[...yr({title:h.title,overview:h.overview,endStateDescription:h.endStateDescription,targetGoalIds:h.targetGoalIds,targetProjectIds:h.targetProjectIds,graph:D}),{id:"acyclic",label:"Graph stays directed and non-looping",satisfied:!Zl(h.nodes)}],[h.endStateDescription,h.nodes,h.overview,h.targetGoalIds,h.targetProjectIds,h.title,D]),ye=c.useMemo(()=>yc({title:h.title,overview:h.overview,endStateDescription:h.endStateDescription,targetGoalIds:h.targetGoalIds,targetProjectIds:h.targetProjectIds,graph:D}),[h.endStateDescription,h.overview,h.targetGoalIds,h.targetProjectIds,h.title,D]),ze=c.useMemo(()=>jr(X),[X]),fe=c.useMemo(()=>{if(!h.title.trim())return"Strategy title is required.";if(h.nodes.length===0)return"Add at least one project or task step.";const g=new Set;for(const B of h.nodes){if(!B.entityId)return"Every step needs a linked project or task.";const de=`${B.entityType}:${B.entityId}`;if(g.has(de))return"Each project or task should appear only once in the sequence.";g.add(de)}return Zl(h.nodes)?"Strategy graph must stay directed and non-loopy.":null},[h.nodes,h.title]),Pe=g=>g==="sequence"?P??fe??(ye?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(()=>n.filter(g=>ue(_,[g.title,g.description],g.user)),[n,_]),Z=c.useMemo(()=>a.filter(g=>ue(_,[g.title,g.description,g.goalTitle,g.status],g.user)),[a,_]),He=c.useMemo(()=>U.filter(g=>ue(_,[g.title,g.description,g.owner,g.status],g.user)),[U,_]),Ue=c.useMemo(()=>new Set(h.targetGoalIds),[h.targetGoalIds]),Qe=c.useMemo(()=>new Set(h.targetProjectIds),[h.targetProjectIds]),ct=c.useMemo(()=>new Set(h.nodes.map(g=>`${g.entityType}:${g.entityId}`)),[h.nodes]),zt=c.useMemo(()=>h.targetGoalIds.map(g=>R.get(g)).filter(g=>!!g),[h.targetGoalIds,R]),qt=c.useMemo(()=>h.targetProjectIds.map(g=>C.get(g)).filter(g=>!!g),[h.targetProjectIds,C]),Pt=c.useMemo(()=>Z.filter(g=>Qe.has(g.id)||Ue.has(g.goalId)),[Z,Ue,Qe]),Mt=c.useMemo(()=>He.filter(g=>Qe.has(g.projectId??"")||Ue.has(g.goalId??"")),[He,Ue,Qe]),Et=c.useMemo(()=>$.slice(0,8),[$]),te=c.useMemo(()=>ce.slice(0,8),[ce]),we=c.useMemo(()=>V.slice(0,12),[V]),Me=c.useMemo(()=>Ge.slice(0,6),[Ge]),Ve=c.useMemo(()=>Z.slice(0,8),[Z]),Se=c.useMemo(()=>He.slice(0,10),[He]),xe=c.useMemo(()=>Pt.slice(0,4),[Pt]),Ie=c.useMemo(()=>Mt.slice(0,6),[Mt]),Ee=c.useMemo(()=>{if(!T.goalId)return a;const g=a.filter(B=>B.goalId===T.goalId);return g.length>0?g:a},[T.goalId,a]),et=_.length>0,Fe=Me.length>0||Ve.length>0||Se.length>0,ut=(g,B)=>{p(de=>({...de,nodes:de.nodes.map(be=>be.id===g?{...be,...B}:be)}))},Te=(g,B)=>{h.nodes.some(de=>de.entityType===g&&de.entityId===B)||p(de=>({...de,nodes:[...de.nodes,La(g,{entityId:B,dependencyMode:de.nodes.length===0?"start":"after_previous"})]}))},rt=g=>{p(B=>{const de=B.nodes.filter(be=>be.id!==g);return{...B,nodes:de.map((be,Ne)=>({...be,dependencyMode:Ne===0&&be.dependencyMode==="after_previous"?"start":be.dependencyMode,customPredecessorIds:be.customPredecessorIds.filter(lt=>lt!==g)}))}})},kt=rd(ld(dd,{activationConstraint:{distance:6}})),Bt=g=>{!g.over||g.active.id===g.over.id||p(B=>{const de=B.nodes.findIndex(Ne=>Ne.id===g.active.id),be=B.nodes.findIndex(Ne=>{var lt;return Ne.id===((lt=g.over)==null?void 0:lt.id)});return de<0||be<0?B:{...B,nodes:Eh(B.nodes,de,be)}})},ds=()=>{const g=S.trim(),B=h.targetProjectIds.map(Ne=>C.get(Ne)).find(Ne=>!!Ne)??C.get(T.projectId)??a[0]??null,de=(B==null?void 0:B.goalId)??h.targetGoalIds[0]??"",be=a.find(Ne=>Ne.goalId===de&&(B?Ne.id===B.id:!0))??a.find(Ne=>Ne.goalId===de)??B;F(Ne=>({...Zs(x,a),title:g||Ne.title,description:Ne.description,goalId:de,projectId:(be==null?void 0:be.id)??Ne.projectId,userId:(be==null?void 0:be.userId)??Ne.userId??x})),q(null),j(!0)},Ds=async()=>{const g=C.get(T.projectId);if(!T.title.trim()){q("Task title is required.");return}if(!g){q("Pick a project for the new task.");return}Q(!0),q(null);try{const B=ee.get(T.userId??g.userId??"")??g.user??oe??le,de=(await Ea({title:T.title.trim(),description:T.description.trim(),owner:(B==null?void 0:B.displayName)??"Albert",userId:T.userId??g.userId??h.userId,goalId:g.goalId,projectId:g.id,priority:T.priority,status:"focus",effort:T.effort,energy:T.energy,dueDate:"",points:T.points,tagIds:[],notes:[]})).task;A(be=>[de,...be]),Te("task",de.id),F({...Zs(x,a),goalId:g.goalId,projectId:g.id,userId:de.userId??g.userId??h.userId}),M(""),j(!1)}catch(B){q(B instanceof Error?B.message:"Task creation failed.")}finally{Q(!1)}},$s=async()=>{if(fe){y(fe);return}try{await m({title:h.title.trim(),overview:h.overview.trim(),endStateDescription:h.endStateDescription.trim(),status:h.status,userId:h.userId,targetGoalIds:h.targetGoalIds,targetProjectIds:h.targetProjectIds,linkedEntities:h.linkedEntities,graph:D},i==null?void 0:i.id),y(null),b(!1)}catch(g){y(g instanceof Error?g.message:"Strategy save failed.")}},Os=[{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:(g,B)=>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(Y,{label:"Strategy title",children:e.jsx(ie,{value:g.title,onChange:de=>B({title:de.target.value}),placeholder:"Land the multi-user planning system"})}),e.jsx(Y,{label:"Status",children:e.jsx(tt,{value:g.status,onChange:de=>B({status:de}),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(is,{value:g.userId,users:o,onChange:de=>B({userId:de}),label:"Owner user",defaultLabel:ss(le),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(ke,{kind:"strategy",label:g.title.trim()||"Untitled strategy",compact:!0,gradient:!1}),e.jsx(O,{className:"bg-white/[0.12] text-white/86",children:g.status}),oe?e.jsx($e,{user:oe,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:(g,B)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsx(Y,{label:"Overview",children:e.jsx(Ce,{value:g.overview,onChange:de=>B({overview:de.target.value}),placeholder:"Explain what this strategy is coordinating and why it matters right now."})}),e.jsx(Y,{label:"End state",children:e.jsx(Ce,{value:g.endStateDescription,onChange:de=>B({endStateDescription:de.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(Y,{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(dt,{className:"size-4 text-white/42"}),e.jsx(ie,{className:"border-none bg-transparent px-0 py-0",value:w,onChange:de=>v(de.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:zt.length===0?e.jsx(O,{className:"bg-white/[0.08] text-white/62",children:"No target goals yet"}):zt.map(de=>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:()=>B({targetGoalIds:pi(g.targetGoalIds,de.id)}),children:[e.jsx(ke,{kind:"goal",label:de.title,compact:!0,gradient:!1}),e.jsx("span",{children:"Remove"})]},de.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:qt.length===0?e.jsx(O,{className:"bg-white/[0.08] text-white/62",children:"No target projects yet"}):qt.map(de=>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:()=>B({targetProjectIds:pi(g.targetProjectIds,de.id)}),children:[e.jsx(ke,{kind:"project",label:de.title,compact:!0,gradient:!1}),e.jsx("span",{children:"Remove"})]},de.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"}),ne?e.jsxs(O,{className:"bg-white/[0.08] text-white/72",children:[$.length," found"]}):null]}),e.jsx("div",{className:"mt-3 grid gap-3",children:ne?Et.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."}):Et.map(de=>{const be=g.targetGoalIds.includes(de.id);return e.jsxs("button",{type:"button",className:re("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:()=>B({targetGoalIds:pi(g.targetGoalIds,de.id)}),children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-between gap-2",children:[e.jsx(_e,{kind:"goal",label:de.title,className:"max-w-full min-w-0"}),e.jsx($e,{user:de.user,compact:!0})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:de.description||"No strategic note attached yet."})]},de.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"}),ne?e.jsxs(O,{className:"bg-white/[0.08] text-white/72",children:[ce.length," found"]}):null]}),e.jsx("div",{className:"mt-3 grid gap-3",children:ne?te.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."}):te.map(de=>{const be=g.targetProjectIds.includes(de.id);return e.jsxs("button",{type:"button",className:re("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:()=>B({targetProjectIds:pi(g.targetProjectIds,de.id)}),children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-between gap-2",children:[e.jsx(_e,{kind:"project",label:de.title,className:"max-w-full min-w-0",showIcon:!1}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(O,{className:"bg-white/[0.08] text-white/70",children:de.goalTitle}),e.jsx($e,{user:de.user,compact:!0})]})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:de.description||"No project summary attached yet."})]},de.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:(g,B)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{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(dt,{className:"size-4 text-white/42"}),e.jsx(ie,{className:"border-none bg-transparent px-0 py-0",value:I,onChange:de=>k(de.target.value),placeholder:"Search by title, owner, @handle, human, or bot"})]})}),e.jsx("div",{className:"flex flex-wrap gap-2",children:g.linkedEntities.length===0?e.jsx(O,{className:"bg-white/[0.08] text-white/62",children:"No extra linked context yet"}):g.linkedEntities.map(de=>{const be=V.find(Ne=>Ne.entityType===de.entityType&&Ne.entityId===de.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:()=>B({linkedEntities:g.linkedEntities.filter(Ne=>!(Ne.entityType===de.entityType&&Ne.entityId===de.entityId))}),children:[e.jsx(rs,{className:"mr-1 size-3.5"}),(be==null?void 0:be.label)??`${de.entityType}:${de.entityId}`,e.jsx("span",{children:"Remove"})]},`${de.entityType}:${de.entityId}`)})}),e.jsx("div",{className:"grid gap-3",children:H?we.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."}):we.map(de=>{const be=g.linkedEntities.some(Ne=>Ne.entityType===de.entityType&&Ne.entityId===de.entityId);return e.jsxs("label",{className:re("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(ke,{kind:de.entityType,label:de.label,compact:!0,gradient:!1}),de.user?e.jsx($e,{user:de.user,compact:!0}):null]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:de.description})]}),e.jsx("input",{type:"checkbox",checked:be,onChange:()=>B({linkedEntities:Yl(g.linkedEntities,{entityType:de.entityType,entityId:de.entityId})})})]},de.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(O,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[h.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(dt,{className:"size-4 text-white/42"}),e.jsx(ie,{className:"border-none bg-transparent px-0 py-0",value:S,onChange:g=>M(g.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:ds,children:[e.jsx(Wt,{className:"size-4"}),"Create new task"]}),u?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:()=>{j(!1),q(null)},children:"Close"})]}),e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsx(Y,{label:"Task title",children:e.jsx(ie,{value:T.title,onChange:g=>F(B=>({...B,title:g.target.value})),placeholder:"Draft the shared strategy hierarchy view"})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Y,{label:"Goal",children:e.jsxs("select",{value:T.goalId,onChange:g=>{const B=g.target.value,de=a.find(be=>be.goalId===B)??null;F(be=>({...be,goalId:B,projectId:(de==null?void 0:de.id)??"",userId:(de==null?void 0:de.userId)??be.userId??x}))},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"}),n.map(g=>e.jsx("option",{value:g.id,children:g.title},g.id))]})}),e.jsx(Y,{label:"Project",children:e.jsxs("select",{value:T.projectId,onChange:g=>F(B=>{var de,be;return{...B,projectId:g.target.value,goalId:((de=C.get(g.target.value))==null?void 0:de.goalId)??B.goalId,userId:((be=C.get(g.target.value))==null?void 0:be.userId)??B.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"}),Ee.map(g=>e.jsx("option",{value:g.id,children:g.title},g.id))]})})]}),e.jsx(Y,{label:"Notes",children:e.jsx(Ce,{value:T.description,onChange:g=>F(B=>({...B,description:g.target.value})),placeholder:"Optional detail or acceptance note."})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Y,{label:"Priority",children:e.jsxs("select",{value:T.priority,onChange:g=>F(B=>({...B,priority:g.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(Y,{label:"Points",children:e.jsx(ie,{type:"number",value:T.points,onChange:g=>F(B=>({...B,points:Number(g.target.value)||0}))})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Y,{label:"Effort",children:e.jsxs("select",{value:T.effort,onChange:g=>F(B=>({...B,effort:g.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(Y,{label:"Energy",children:e.jsxs("select",{value:T.energy,onChange:g=>F(B=>({...B,energy:g.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"})]})})]}),L?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:L}):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:()=>{j(!1),q(null)},children:"Cancel"}),e.jsxs(W,{type:"button",className:"w-full sm:w-auto",pending:G,pendingLabel:"Creating task",onClick:()=>void Ds(),children:[e.jsx(Wt,{className:"size-4"}),"Create task"]})]})]})]}):null,et?Fe?e.jsxs("div",{className:"grid gap-3",children:[Me.length>0?e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Goals"}):null,Me.map(g=>{const B=h.targetGoalIds.includes(g.id),de=h.linkedEntities.some(be=>be.entityType==="goal"&&be.entityId===g.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(ke,{kind:"goal",label:g.title,compact:!0,gradient:!1}),e.jsx($e,{user:g.user,compact:!0})]}),g.description?e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:g.description}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{type:"button",className:"w-full sm:w-auto",variant:B?"secondary":"primary",onClick:()=>p(be=>({...be,targetGoalIds:pi(be.targetGoalIds,g.id)})),children:B?"Targeted":"Add target"}),e.jsx(W,{type:"button",className:"w-full sm:w-auto",variant:"secondary",onClick:()=>p(be=>({...be,linkedEntities:Yl(be.linkedEntities,{entityType:"goal",entityId:g.id})})),children:de?"Unlink":"Link"})]})]})},g.id)}),Ve.length>0?e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Projects"}):null,Ve.map(g=>{const B=ct.has(`project:${g.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(ke,{kind:"project",label:g.title,compact:!0,gradient:!1}),e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:g.goalTitle}),e.jsx($e,{user:g.user,compact:!0})]}),g.description?e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:g.description}):null]}),e.jsx(W,{type:"button",className:"w-full sm:w-auto",variant:B?"secondary":"primary",disabled:B,onClick:()=>Te("project",g.id),children:B?"In sequence":"Add step"})]})},`sequence-project:${g.id}`)}),Se.length>0?e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Tasks"}):null,Se.map(g=>{const B=ct.has(`task:${g.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(ke,{kind:"task",label:g.title,compact:!0,gradient:!1}),e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:g.status}),e.jsx($e,{user:g.user,compact:!0})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:g.description||`${g.owner} · ${g.projectId}`})]}),e.jsx(W,{type:"button",className:"w-full sm:w-auto",variant:B?"secondary":"primary",disabled:B,onClick:()=>Te("task",g.id),children:B?"In sequence":"Add step"})]})},`sequence-task:${g.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."}):xe.length>0||Ie.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"}),xe.map(g=>{const B=ct.has(`project:${g.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(ke,{kind:"project",label:g.title,compact:!0,gradient:!1}),e.jsx($e,{user:g.user,compact:!0})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:g.description||g.goalTitle})]}),e.jsx(W,{type:"button",className:"w-full sm:w-auto",variant:B?"secondary":"primary",disabled:B,onClick:()=>Te("project",g.id),children:B?"In sequence":"Add step"})]})},`suggested-project:${g.id}`)}),Ie.map(g=>{const B=ct.has(`task:${g.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(ke,{kind:"task",label:g.title,compact:!0,gradient:!1}),e.jsx($e,{user:g.user,compact:!0})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:g.description||`${g.owner} · ${g.status}`})]}),e.jsx(W,{type:"button",className:"w-full sm:w-auto",variant:B?"secondary":"primary",disabled:B,onClick:()=>Te("task",g.id),children:B?"In sequence":"Add step"})]})},`suggested-task:${g.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(O,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[h.nodes.length," planned steps"]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[h.targetGoalIds.map(g=>{const B=R.get(g);return B?e.jsx(ke,{kind:"goal",label:B.title,compact:!0,gradient:!1},g):null}),h.targetProjectIds.map(g=>{const B=C.get(g);return B?e.jsx(ke,{kind:"project",label:B.title,compact:!0,gradient:!1},g):null})]})]}),e.jsx(od,{sensors:kt,collisionDetection:Mh,onDragEnd:Bt,children:e.jsx(Ln,{items:h.nodes.map(g=>g.id),strategy:Dn,children:e.jsx("div",{className:"grid gap-3",children:h.nodes.map((g,B)=>e.jsx($b,{node:g,index:B,total:h.nodes.length,projectsById:C,tasksById:J,usersById:ee,allNodes:h.nodes,onUpdate:ut,onRemove:rt},g.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:he.map(g=>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:g.label}),e.jsx(O,{className:g.satisfied?"bg-emerald-500/12 text-emerald-200":"bg-amber-500/12 text-amber-200",children:g.satisfied?"Ready":"Missing"})]},g.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:ze.map(g=>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:g.label}),e.jsxs("span",{children:[g.value,"%"]})]}),e.jsx(ts,{value:g.value,className:"mt-2"})]},g.id))})]})]})]})}];return e.jsx(it,{open:t,onOpenChange:b,eyebrow:"Strategy",title:i?"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:h,onChange:p,steps:Os,initialStepId:f,contentClassName:"lg:h-[min(56rem,calc(100vh-1rem))] lg:w-[min(78rem,calc(100vw-1.5rem))]",submitLabel:i?ye?"Save strategy":"Save draft":ye?"Create strategy":"Create draft",pending:s,pendingLabel:"Saving strategy",resolveError:Pe,onSubmit:$s})}function Ob(t){return t.trim().toLowerCase()}function Fb(){const t=Ye(),s=ht(),i=We(),[n,a]=ft(),[r,l]=c.useState(!1),[d,o]=c.useState(null),[x,f]=c.useState(""),b=Nt(t.selectedUserIds);c.useEffect(()=>{n.get("create")==="1"&&(o(null),l(!0),a(S=>{const M=new URLSearchParams(S);return M.delete("create"),M},{replace:!0}))},[n,a]);const m=async()=>{await i.invalidateQueries({queryKey:["strategy-detail"]}),await t.refresh()},h=ge({mutationFn:async({input:S,strategyId:M})=>M?(await Fn(M,S)).strategy:(await sx(S)).strategy,onSuccess:async()=>{await m()}}),p=ge({mutationFn:async S=>Ed(S),onSuccess:async()=>{await m()}}),w=c.useMemo(()=>new Map(t.snapshot.goals.map(S=>[S.id,S])),[t.snapshot.goals]),v=c.useMemo(()=>new Map(t.snapshot.dashboard.projects.map(S=>[S.id,S])),[t.snapshot.dashboard.projects]),I=c.useMemo(()=>new Map(t.snapshot.tasks.map(S=>[S.id,S])),[t.snapshot.tasks]),k=c.useMemo(()=>{const S=Ob(x);return S?t.snapshot.strategies.filter(M=>{var A,T,F;const P=M.targetGoalIds.map(u=>{var j;return((j=w.get(u))==null?void 0:j.title)??""}).join(" "),y=M.targetProjectIds.map(u=>{var j;return((j=v.get(u))==null?void 0:j.title)??""}).join(" "),N=M.graph.nodes.map(u=>{var j,L;return u.entityType==="project"?((j=v.get(u.entityId))==null?void 0:j.title)??"":((L=I.get(u.entityId))==null?void 0:L.title)??""}).join(" ");return[M.title,M.overview,M.endStateDescription,M.status,((A=M.user)==null?void 0:A.displayName)??"",((T=M.user)==null?void 0:T.handle)??"",((F=M.user)==null?void 0:F.kind)??"",P,y,N].join(" ").toLowerCase().includes(S)}):t.snapshot.strategies},[w,v,x,t.snapshot.strategies,I]);return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{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:()=>{o(null),l(!0)},children:[e.jsx(Wt,{className:"size-4"}),"New strategy"]})}),e.jsxs(se,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(dt,{className:"size-4 text-white/38"}),e.jsx(ie,{value:x,onChange:S=>f(S.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."})]}),k.length===0?e.jsx(gt,{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:()=>{o(null),l(!0)},children:"Create strategy"})}):e.jsx("div",{className:"grid gap-4",children:k.map(S=>{const M=S.graph.nodes.filter(y=>S.metrics.activeNodeIds.includes(y.id)),P=jr(S.metrics);return e.jsxs(se,{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/${S.id}`),children:[e.jsx("div",{className:"font-display text-2xl text-white",children:S.title}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:S.overview||S.endStateDescription})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($e,{user:S.user}),e.jsx(O,{className:S.isLocked?"bg-amber-500/12 text-amber-200":"bg-emerald-500/12 text-emerald-200",children:S.isLocked?"Contract locked":"Editable draft"}),e.jsx(O,{className:"bg-white/[0.08] text-white/78",children:S.status}),e.jsxs(O,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[S.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:[S.metrics.startedNodeCount,"/",S.metrics.totalNodeCount]}),e.jsxs("div",{className:"text-xs leading-5 text-white/46",children:[S.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:S.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:[S.metrics.completedTargetCount,"/",S.metrics.totalTargetCount||0]}),e.jsxs("div",{className:"text-xs leading-5 text-white/46",children:[S.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:[S.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:M.length===0?e.jsx("div",{className:"text-sm text-white/52",children:"No currently open branch."}):M.map(y=>e.jsx(O,{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:P.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:[S.isLocked?null:e.jsxs(W,{variant:"secondary",onClick:()=>{o(S),l(!0)},children:[e.jsx(Us,{className:"size-4"}),"Edit"]}),e.jsxs(W,{variant:"secondary",pending:p.isPending&&p.variables===S.id,pendingLabel:"Deleting strategy",onClick:()=>{window.confirm(`Delete strategy "${S.title}"?`)&&p.mutateAsync(S.id)},children:[e.jsx(bt,{className:"size-4"}),"Delete"]}),e.jsx(W,{onClick:()=>s(`/strategies/${S.id}`),children:"Open strategy"})]})]})]},S.id)})}),e.jsx(Nc,{open:r,pending:h.isPending,editingStrategy:d,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:b,onOpenChange:l,onSubmit:async(S,M)=>{await h.mutateAsync({input:S,strategyId:M})}})]})}function kc(t){const s=new Map;for(const a of t.nodes)s.set(a.id,[]);for(const a of t.edges)s.set(a.to,[...s.get(a.to)??[],a.from]);const i=new Map,n=a=>{const r=i.get(a);if(r!==void 0)return r;const l=s.get(a)??[],d=l.length===0?0:Math.max(...l.map(o=>n(o)))+1;return i.set(a,d),d};for(const a of t.nodes)n(a.id);return i}function _b(t){const s=kc(t),i=new Map;for(const n of t.nodes){const a=s.get(n.id)??0;i.set(a,[...i.get(a)??[],n.id])}return Array.from(i.entries()).sort((n,a)=>n[0]-a[0]).map(([n,a])=>({level:n,nodeIds:a}))}function Rb(t,s){const i=kc(t.graph),n=new Map;for(const a of t.graph.nodes){const r=i.get(a.id)??0;n.set(r,[...n.get(r)??[],a.id])}return t.graph.nodes.map(a=>{const r=i.get(a.id)??0,l=(n.get(r)??[]).indexOf(a.id),d=t.metrics.activeNodeIds.includes(a.id),o=t.metrics.blockedNodeIds.includes(a.id),x=t.metrics.outOfOrderNodeIds.includes(a.id),f=!d&&!o&&!x,b=(s==null?void 0:s.get(a.id))??null;let m="border-white/10 bg-[rgba(8,14,26,0.92)]";return d?m="border-emerald-400/30 bg-emerald-500/[0.08]":o?m="border-rose-400/28 bg-rose-500/[0.08]":x?m="border-amber-400/28 bg-amber-500/[0.08]":t.metrics.completedNodeCount>0&&(m="border-sky-400/20 bg-sky-500/[0.05]"),{id:a.id,position:{x:72+r*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)] ${m}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(O,{className:"bg-white/[0.08] text-white/74",children:a.entityType}),d?e.jsx(O,{className:"bg-emerald-500/12 text-emerald-200",children:"Active"}):null,o?e.jsx(O,{className:"bg-rose-500/12 text-rose-200",children:"Blocked"}):null,x?e.jsx(O,{className:"bg-amber-500/12 text-amber-200",children:"Out of order"}):null,f&&!o&&!x?e.jsx(O,{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:a.title}),a.branchLabel?e.jsx("div",{className:"mt-2 text-xs uppercase tracking-[0.16em] text-white/45",children:a.branchLabel}):null,a.notes?e.jsx("div",{className:"mt-2 text-sm leading-5 text-white/56",children:a.notes}):null,b?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:b.color}}),e.jsx("span",{children:b.label})]}):null]})},style:{background:"transparent",border:"none",padding:0}}})}function zb(t){return t.graph.edges.map(s=>{const i=t.metrics.activeNodeIds.includes(s.to),n=t.metrics.blockedNodeIds.includes(s.to),a=t.metrics.outOfOrderNodeIds.includes(s.to);let r="rgba(255,255,255,0.3)";return i?r="#4ade80":n?r="#fb7185":a&&(r="#f59e0b"),{id:`${s.from}->${s.to}`,source:s.from,target:s.to,label:s.label||void 0,animated:i,markerEnd:{type:Zo.ArrowClosed,color:r},style:{stroke:r,strokeWidth:i?2.4:1.5},labelStyle:{fill:"rgba(255,255,255,0.56)",fontSize:11,fontWeight:600}}})}function qb({strategy:t,ownerByNodeId:s,heightClassName:i="h-[540px]"}){const n=c.useMemo(()=>Rb(t,s),[s,t]),a=c.useMemo(()=>zb(t),[t]);return e.jsx("div",{className:`${i} 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(Jo,{fitView:!0,nodes:n,edges:a,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!1,attributionPosition:"bottom-left",children:[e.jsx(Yo,{showInteractive:!1}),e.jsx(Vo,{gap:28,size:1,color:"rgba(255,255,255,0.06)"})]})})}function Bb(t,s){const i=t.metrics.activeNodeIds.includes(s),n=t.metrics.blockedNodeIds.includes(s),a=t.metrics.outOfOrderNodeIds.includes(s);return n?{label:"Blocked",className:"bg-rose-500/12 text-rose-200"}:a?{label:"Out of order",className:"bg-amber-500/12 text-amber-200"}:i?{label:"Ready now",className:"bg-emerald-500/12 text-emerald-200"}:{label:"In plan",className:"bg-sky-500/12 text-sky-200"}}function Kb({strategy:t,projectsById:s,tasksById:i,className:n}){const a=c.useMemo(()=>_b(t.graph),[t.graph]),r=c.useMemo(()=>{const o=new Map;for(const x of t.graph.nodes)o.set(x.id,[]);for(const x of t.graph.edges)o.set(x.to,[...o.get(x.to)??[],x.from]);return o},[t.graph]),[l,d]=c.useState([]);return e.jsxs("div",{className:n??"grid gap-3",children:[a.map(o=>{const x=l.includes(o.level),f=o.level===0?"Launch phase":`Phase ${o.level+1}`,b=o.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:()=>d(m=>x?m.filter(h=>h!==o.level):[...m,o.level]),children:[e.jsx("span",{className:"rounded-full bg-white/[0.06] p-2 text-white/72",children:x?e.jsx(An,{className:"size-4"}):e.jsx(Si,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:f}),e.jsx("div",{className:"mt-1 text-sm text-white/60",children:b?"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(O,{className:"bg-white/[0.08] text-white/76",children:[o.nodeIds.length," node",o.nodeIds.length===1?"":"s"]}),e.jsx(O,{className:"bg-white/[0.08] text-white/76",children:b?e.jsxs(e.Fragment,{children:[e.jsx($m,{className:"mr-1 size-3.5"}),"Parallel"]}):e.jsxs(e.Fragment,{children:[e.jsx(Om,{className:"mr-1 size-3.5"}),"Sequential"]})})]})]}),x?null:e.jsx("div",{className:"grid gap-3 border-t border-white/8 px-4 py-4 lg:grid-cols-2",children:o.nodeIds.map(m=>{var S,M,P;const h=t.graph.nodes.find(y=>y.id===m);if(!h)return null;const p=h.entityType==="project"?s.get(h.entityId):i.get(h.entityId),w=h.entityType==="project"?`/projects/${h.entityId}`:`/tasks/${h.entityId}`,v=h.entityType==="project"?(S=s.get(h.entityId))==null?void 0:S.user:(M=i.get(h.entityId))==null?void 0:M.user,I=((P=r.get(h.id))==null?void 0:P.map(y=>{var N;return((N=t.graph.nodes.find(A=>A.id===y))==null?void 0:N.title)??y}))??[],k=Bb(t,h.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(O,{className:"bg-white/[0.08] text-white/76",children:h.entityType}),e.jsx(O,{className:k.className,children:k.label})]}),e.jsx(Le,{to:w,className:"mt-3 block text-lg font-medium text-white transition hover:text-[var(--primary)]",children:h.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:h.notes||("description"in(p??{})?p==null?void 0:p.description:"")||"No extra step note attached yet."})]}),e.jsx($e,{user:v,compact:!0})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[h.branchLabel?e.jsx(O,{className:"bg-[rgba(192,193,255,0.12)] text-white/82",children:h.branchLabel}):null,I.length===0?e.jsx(O,{className:"bg-emerald-500/10 text-emerald-200",children:"Start node"}):I.map(y=>e.jsxs(O,{className:"bg-white/[0.08] text-white/70",children:["Depends on ",y]},`${h.id}:${y}`))]})]},h.id)})})]},o.level)}),a.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 Ub(){var A;const t=Ye(),{strategyId:s}=Hs(),i=ht(),n=We(),[a,r]=c.useState(!1),[l,d]=c.useState(),o=Nt(t.selectedUserIds),x=t.snapshot.strategies.find(T=>T.id===s)??null,f=pe({queryKey:["strategy-detail",s],queryFn:async()=>(await ix(s)).strategy,enabled:!!(s&&!x)}),b=x??f.data??null,m=async()=>{await Promise.all([n.invalidateQueries({queryKey:["strategy-detail",s]}),t.refresh()])},h=ge({mutationFn:async({input:T,currentStrategyId:F})=>(await Fn(F,T)).strategy,onSuccess:m}),p=ge({mutationFn:async T=>Ed(T),onSuccess:async()=>{await m(),i("/strategies")}}),w=ge({mutationFn:async T=>(await Fn(s,{isLocked:T,lockedByUserId:T?o??(b==null?void 0:b.userId)??"user_operator":null})).strategy,onSuccess:m}),v=c.useMemo(()=>new Map(t.snapshot.goals.map(T=>[T.id,T])),[t.snapshot.goals]),I=c.useMemo(()=>new Map(t.snapshot.dashboard.projects.map(T=>[T.id,T])),[t.snapshot.dashboard.projects]),k=c.useMemo(()=>new Map(t.snapshot.tasks.map(T=>[T.id,T])),[t.snapshot.tasks]),S=c.useMemo(()=>b?new Map(b.graph.nodes.map(T=>{var u,j;const F=T.entityType==="project"?(u=I.get(T.entityId))==null?void 0:u.user:(j=k.get(T.entityId))==null?void 0:j.user;return[T.id,F?{label:`${F.displayName} (${F.kind})`,color:F.accentColor}:null]})):new Map,[I,b,k]),M=b??{title:"",overview:"",endStateDescription:"",targetGoalIds:[],targetProjectIds:[],graph:{nodes:[],edges:[]}},P=c.useMemo(()=>yr(M),[M]),y=c.useMemo(()=>yc(M),[M]),N=c.useMemo(()=>jr((b==null?void 0:b.metrics)??{planCoverageScore:0,sequencingScore:0,scopeDisciplineScore:0,qualityScore:0,targetProgressScore:0,startedNodeCount:0,totalNodeCount:1,offPlanEntityCount:0,offPlanActiveEntityCount:0,blockedNodeIds:[],outOfOrderNodeIds:[]}),[b==null?void 0:b.metrics]);return f.isLoading&&!b?e.jsx(xt,{eyebrow:"Strategy",title:"Loading strategy",description:"Resolving the directed plan, targets, and current alignment."}):f.isError?e.jsx(Oe,{eyebrow:"Strategy",error:f.error,onRetry:()=>void f.refetch()}):b?e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{title:b.title,titleText:b.title,description:b.overview||b.endStateDescription,badge:`${b.metrics.alignmentScore}% aligned`,actions:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Ha,{userId:o,domain:"strategies",entityType:"strategy",entityId:b.id,label:b.title,description:b.overview||b.endStateDescription}),b.isLocked?null:e.jsx(W,{variant:"secondary",onClick:()=>{d(void 0),r(!0)},children:"Edit strategy"}),e.jsx(W,{variant:"secondary",disabled:!b.isLocked&&!y,pending:w.isPending,pendingLabel:b.isLocked?"Unlocking contract":"Locking contract",onClick:()=>{w.mutateAsync(!b.isLocked)},children:b.isLocked?"Unlock contract":"Lock as contract"}),e.jsx(W,{variant:"secondary",pending:p.isPending,pendingLabel:"Deleting strategy",onClick:()=>{window.confirm(`Delete strategy "${b.title}"?`)&&p.mutateAsync(b.id)},children:"Delete"})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($e,{user:b.user}),e.jsx(O,{className:b.isLocked?"bg-amber-500/12 text-amber-200":"bg-emerald-500/12 text-emerald-200",children:b.isLocked?"Contract locked":"Editable draft"}),e.jsx(O,{className:"bg-white/[0.08] text-white/76",children:b.status}),e.jsxs(O,{className:"bg-white/[0.08] text-white/76",children:[b.graph.nodes.length," nodes"]}),e.jsxs(O,{className:"bg-white/[0.08] text-white/76",children:[b.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(se,{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:b.endStateDescription||"No end-state description yet."})]}),e.jsxs(se,{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."})]}),b.isLocked?null:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{variant:"secondary",onClick:()=>{d("sequence"),r(!0)},children:"Refine sequence"}),e.jsx(W,{onClick:()=>{d("sequence"),r(!0)},children:"Add parallel work"})]})]}),e.jsx(qb,{strategy:b,ownerByNodeId:S}),e.jsx(Kb,{strategy:b,projectsById:I,tasksById:k})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(se,{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:b.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."}),b.isLocked?e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-sm text-white/60",children:[e.jsxs("span",{children:["Locked by"," ",((A=b.lockedByUser)==null?void 0:A.displayName)??"Unknown user"]}),b.lockedAt?e.jsxs("span",{children:["· ",new Date(b.lockedAt).toLocaleString()]}):null]}):null,b.isLocked?null:e.jsx("div",{className:"mt-4 grid gap-2",children:P.map(T=>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:T.label}),e.jsx(O,{className:T.satisfied?"bg-emerald-500/12 text-emerald-200":"bg-amber-500/12 text-amber-200",children:T.satisfied?"Ready":"Missing"})]},T.id))})]}),!b.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,b.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(se,{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:[b.metrics.alignmentScore,"%"]}),e.jsxs("div",{className:"mt-3 text-xs leading-5 text-white/48",children:[b.metrics.startedNodeCount,"/",b.metrics.totalNodeCount," planned nodes started,"," ",b.metrics.completedNodeCount," completed,"," ",b.metrics.readyNodeCount," ready now."]})]}),N.map(T=>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:T.label}),e.jsxs("div",{className:"text-sm font-medium text-white",children:[T.value,"%"]})]}),e.jsx(ts,{value:T.value,className:"mt-3"}),e.jsx("div",{className:"mt-3 text-xs leading-5 text-white/48",children:T.detail})]},T.id))]}),e.jsxs(se,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"End targets"}),b.targetGoalIds.map(T=>{const F=v.get(T);return F?e.jsx(Le,{to:`/goals/${F.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: ",F.title]}),e.jsx($e,{user:F.user,compact:!0})]})},F.id):null}),b.targetProjectIds.map(T=>{const F=I.get(T);return F?e.jsx(Le,{to:`/projects/${F.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: ",F.title]}),e.jsx($e,{user:F.user,compact:!0})]})},F.id):null}),b.targetGoalIds.length===0&&b.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(se,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Linked entities"}),b.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."}):b.linkedEntities.map(T=>{var j,L,q,G,Q,ne,H;const F=Es(T.entityType,T.entityId),u=T.entityType==="goal"?(j=v.get(T.entityId))==null?void 0:j.title:T.entityType==="project"?(L=I.get(T.entityId))==null?void 0:L.title:T.entityType==="task"?(q=k.get(T.entityId))==null?void 0:q.title:`${T.entityType}:${T.entityId}`;return F?e.jsx(Le,{to:F,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:u}),e.jsx($e,{user:T.entityType==="goal"?(G=v.get(T.entityId))==null?void 0:G.user:T.entityType==="project"?(Q=I.get(T.entityId))==null?void 0:Q.user:T.entityType==="task"?(ne=k.get(T.entityId))==null?void 0:ne.user:T.entityType==="strategy"?(H=t.snapshot.strategies.find(_=>_.id===T.entityId))==null?void 0:H.user:null,compact:!0})]})},`${T.entityType}:${T.entityId}`):e.jsx("div",{className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/52",children:u},`${T.entityType}:${T.entityId}`)})]})]})]}),e.jsx(Nc,{open:a,pending:h.isPending,editingStrategy:b,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:o,initialStepId:l,onOpenChange:T=>{r(T),T||d(void 0)},onSubmit:async T=>{await h.mutateAsync({input:T,currentStrategyId:b.id})}})]}):e.jsx(Oe,{eyebrow:"Strategy",error:new Error("Strategy not found."),onRetry:()=>i("/strategies")})}const ca=[{to:"/psyche",label:"Overview",icon:Hn},{to:"/psyche/values",label:"Values",icon:Fm},{to:"/psyche/patterns",label:"Patterns",icon:_m},{to:"/psyche/behaviors",label:"Behaviors",icon:Rm},{to:"/psyche/reports",label:"Reports",icon:vt},{to:"/psyche/goal-map",label:"Goal Map",icon:zm},{to:"/psyche/schemas-beliefs",label:"Schemas & Beliefs",icon:qm},{to:"/psyche/modes",label:"Modes",icon:Bm},{to:"/preferences",label:"Preferences",icon:Fa},{to:"/sleep",label:"Sleep",icon:Ko}];function bn(t,s){return t===s||t.startsWith(`${s}/`)}function Ht({className:t}){const s=ki(),[i,n]=c.useState(!1),a=c.useMemo(()=>[...ca].sort((r,l)=>l.to.length-r.to.length).find(r=>bn(s.pathname,r.to))??ca[0],[s.pathname]);return e.jsxs(e.Fragment,{children:[e.jsxs(se,{className:re("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:ca.map(r=>e.jsxs(Ks,{to:r.to,className:({isActive:l})=>re("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||bn(s.pathname,r.to)?"bg-[rgba(110,231,183,0.18)] text-[var(--tertiary)]":"bg-white/[0.04] text-white/58 hover:bg-white/[0.08] hover:text-white"),children:[e.jsx(r.icon,{className:"size-3.5"}),e.jsx("span",{children:r.label})]},r.to))})}),e.jsx("div",{className:"flex items-center justify-between gap-3 lg:hidden",children:e.jsxs("button",{type:"button",className:"inline-flex min-w-0 flex-1 items-center justify-between rounded-full bg-white/[0.06] px-4 py-3 text-left",onClick:()=>n(!0),children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(a.icon,{className:"size-4 shrink-0 text-[var(--tertiary)]"}),e.jsx("span",{className:"truncate text-sm font-medium text-white",children:a.label})]}),e.jsx("span",{className:"text-[10px] uppercase tracking-[0.16em] text-white/42",children:"Switch"})]})})]}),i?e.jsx("div",{className:"fixed inset-0 z-50 bg-[rgba(5,10,18,0.86)] px-4 py-5 backdrop-blur-xl lg:hidden",children:e.jsxs("div",{className:"mx-auto flex h-full max-w-xl flex-col rounded-[32px] bg-[linear-gradient(180deg,rgba(16,25,33,0.98),rgba(11,18,25,0.98))] p-5 shadow-[0_30px_80px_rgba(0,0,0,0.35)]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/38",children:"Psyche sections"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:"Move through the inner map"})]}),e.jsx(W,{variant:"secondary",onClick:()=>n(!1),children:"Close"})]}),e.jsx("div",{className:"mt-6 grid gap-3 overflow-y-auto",children:ca.map(r=>e.jsxs(Ks,{to:r.to,onClick:()=>n(!1),className:re("flex items-center justify-between rounded-[24px] px-4 py-4 transition",bn(s.pathname,r.to)?"bg-[rgba(110,231,183,0.14)] text-white":"bg-white/[0.04] text-white/70"),children:[e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(r.icon,{className:"size-4 text-[var(--tertiary)]"}),e.jsx("span",{className:"text-base font-medium",children:r.label})]}),e.jsx("span",{className:"text-[10px] uppercase tracking-[0.16em] text-white/36",children:"Open"})]},r.to))})]})}):null]})}const Sc=[{id:"overview",label:"Overview",icon:Go},{id:"map",label:"Map",icon:Km},{id:"table",label:"Table",icon:Um},{id:"history",label:"History",icon:ed},{id:"contexts",label:"Contexts",icon:Fa},{id:"concepts",label:"Concepts",icon:vt}],Qb=new Set(["projects","tasks","strategies","habits"]),ma=[{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"}],qn={novelty:"Novelty",simplicity:"Simplicity",rigor:"Rigor",aesthetics:"Aesthetics",depth:"Depth",structure:"Structure",familiarity:"Familiarity",surprise:"Surprise"},ha={novelty:0,simplicity:0,rigor:0,aesthetics:0,depth:0,structure:0,familiarity:0,surprise:0},so={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"},Wb=[{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 ua(t){return t.trim().toLowerCase()}function bi(t){return`${Math.round(t*100)}%`}function Gb(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:qe([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:qe([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:qe([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:qe([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:qe([s.title,s.description,s.status,s.frequency],s)}))]}function Hb(t,s){return!t||!s?null:t==="goal"?`/goals/${s}`:t==="project"?`/projects/${s}`:t==="task"?`/tasks/${s}`:t==="strategy"?`/strategies/${s}`:null}function pa(t){return t.manualStatus??t.status}function Xb(t){return t&&Sc.some(s=>s.id===t)?t:"overview"}function Jb(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 Yb({summary:t}){const s=Math.max(-1,Math.min(1,t.leaning)),i=(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:qn[t.dimensionId]}),e.jsxs("span",{children:[t.movement>.08?"Rising":t.movement<-.08?"Falling":"Stable"," ","· ",bi(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:re("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:`${i}%`}})]}),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"," ",qn[t.dimensionId].toLowerCase()]}),e.jsxs("span",{children:["Context ",bi(t.contextSensitivity)]})]})]})}function io({title:t,description:s,sideLabel:i,onClick:n}){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:n,children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:i}),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 Vb(){var Bt,ds,Ds,$s,Os;const t=Ye(),s=We(),[i,n]=ft(),[a,r]=c.useState(""),[l,d]=c.useState(""),[o,x]=c.useState(""),[f,b]=c.useState(""),[m,h]=c.useState(""),[p,w]=c.useState({open:!1,phase:"domain",domain:i.get("domain")??"projects"}),[v,I]=c.useState(null),[k,S]=c.useState(!1),[M,P]=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"}}),[A,T]=c.useState({label:"",description:"",tags:""}),[F,u]=c.useState({name:"",description:"",shareMode:"blended",decayDays:"90"}),[j,L]=c.useState({title:"",description:""}),[q,G]=c.useState({}),[Q,ne]=c.useState(null),[H,_]=c.useState({title:"",description:""}),[U,R]=c.useState(null),[C,J]=c.useState({label:"",description:"",tags:""}),ee=i.get("userId")??Nt(t.selectedUserIds)??((Bt=t.snapshot.users[0])==null?void 0:Bt.id)??null,le=i.get("domain")??"projects",oe=Xb(i.get("tab")),ue=i.get("contextId"),me=i.get("focusItem"),$=c.useMemo(()=>t.snapshot.users.find(g=>g.id===ee)??null,[ee,t.snapshot.users]),ce=c.useMemo(()=>Gb(t.snapshot),[t.snapshot]),E=pe({queryKey:["forge-preferences",ee,le,ue],queryFn:async()=>(await hl({userId:ee??void 0,domain:le,contextId:ue??void 0})).workspace,enabled:!!ee}),z=pe({queryKey:["forge-preferences-game",ee,p.domain,ue],queryFn:async()=>(await hl({userId:ee??void 0,domain:p.domain,contextId:ue??void 0})).workspace,enabled:!!ee&&p.open}),K=E.data??null,je=p.domain===le?K:z.data??null;c.useEffect(()=>{var B;if(!K)return;const g=me&&K.scores.some(de=>de.itemId===me)?me:((B=K.scores[0])==null?void 0:B.itemId)??null;P(de=>de&&K.scores.some(be=>be.itemId===de)?de:g)},[me,K]);const V=c.useMemo(()=>{if(!K)return[];const g=ua(a);return g?K.scores.filter(B=>{var de,be,Ne;return[((de=B.item)==null?void 0:de.label)??"",((be=B.item)==null?void 0:be.description)??"",((Ne=B.item)==null?void 0:Ne.tags.join(" "))??"",B.status,B.manualStatus??"",B.dominantDimensions.join(" "),B.explanation.join(" ")].join(" ").toLowerCase().includes(g)}):K.scores},[a,K]),D=V.find(g=>g.itemId===M)??(K==null?void 0:K.scores.find(g=>g.itemId===M))??V[0]??(K==null?void 0:K.scores[0])??null;c.useEffect(()=>{var g,B,de,be,Ne,lt,fs,cs,Pi,Mi,Ei;D&&N({label:((g=D.item)==null?void 0:g.label)??"",description:((B=D.item)==null?void 0:B.description)??"",tags:((de=D.item)==null?void 0:de.tags.join(", "))??"",manualStatus:D.manualStatus??"",manualScore:typeof D.manualScore=="number"?String(D.manualScore):"",confidenceLock:typeof D.confidenceLock=="number"?String(D.confidenceLock):"",bookmarked:D.bookmarked,compareLater:D.compareLater,frozen:D.frozen,featureWeights:{novelty:String(((be=D.item)==null?void 0:be.featureWeights.novelty)??0),simplicity:String(((Ne=D.item)==null?void 0:Ne.featureWeights.simplicity)??0),rigor:String(((lt=D.item)==null?void 0:lt.featureWeights.rigor)??0),aesthetics:String(((fs=D.item)==null?void 0:fs.featureWeights.aesthetics)??0),depth:String(((cs=D.item)==null?void 0:cs.featureWeights.depth)??0),structure:String(((Pi=D.item)==null?void 0:Pi.featureWeights.structure)??0),familiarity:String(((Mi=D.item)==null?void 0:Mi.featureWeights.familiarity)??0),surprise:String(((Ei=D.item)==null?void 0:Ei.featureWeights.surprise)??0)}})},[D]);const X=c.useMemo(()=>{const g=ua(l);return ce.filter(B=>B.domain===le).filter(B=>g?B.searchText.includes(g):!0).slice(0,12)},[ce,l,le]),he=c.useMemo(()=>{const g=oe==="concepts"?K:je??K,B=(g==null?void 0:g.catalogs)??[],de=ua(o);return de?B.filter(be=>[be.title,be.description,be.source,...be.items.flatMap(Ne=>[Ne.label,Ne.description,Ne.tags.join(" ")])].join(" ").toLowerCase().includes(de)):B},[je,o,oe,K]),ye=async()=>{await s.invalidateQueries({queryKey:["forge-preferences"]}),await s.invalidateQueries({queryKey:["forge-preferences-game"]})},ze=ge({mutationFn:On,onSuccess:ye}),fe=ge({mutationFn:Au,onSuccess:async({item:g})=>{await ye(),T({label:"",description:"",tags:""}),P(g.id)}}),Pe=ge({mutationFn:Nu,onSuccess:async()=>{await ye(),L({title:"",description:""}),n(g=>{const B=new URLSearchParams(g);return B.set("tab","concepts"),B})}}),Ge=ge({mutationFn:({catalogId:g,patch:B})=>ku(g,B),onSuccess:async()=>{await ye(),ne(null)}}),Z=ge({mutationFn:Su,onSuccess:ye}),He=ge({mutationFn:Cu,onSuccess:async()=>{await ye()}}),Ue=ge({mutationFn:({catalogItemId:g,patch:B})=>Iu(g,B),onSuccess:async()=>{await ye(),R(null)}}),Qe=ge({mutationFn:Tu,onSuccess:ye}),ct=ge({mutationFn:ju,onSuccess:async()=>{await ye(),w(g=>({...g,phase:"play"}))}}),zt=ge({mutationFn:Du,onSuccess:ye}),qt=ge({mutationFn:$u,onSuccess:ye}),Pt=ge({mutationFn:async()=>{!(D!=null&&D.item)||!ee||!K||(await Lu(D.item.id,{label:y.label,description:y.description,tags:y.tags.split(",").map(g=>g.trim()).filter(Boolean),featureWeights:Object.fromEntries(Object.keys(ha).map(g=>[g,Number(y.featureWeights[g]||0)]))}),await Ou(D.item.id,{userId:ee,domain:le,contextId:K.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:ye}),Mt=ge({mutationFn:Pu,onSuccess:async({context:g})=>{await ye(),u({name:"",description:"",shareMode:"blended",decayDays:"90"}),n(B=>{const de=new URLSearchParams(B);return de.set("contextId",g.id),de.set("tab","contexts"),de})}}),Et=ge({mutationFn:Eu,onSuccess:async()=>{await ye(),b(""),h("")}}),te=ge({mutationFn:({contextId:g,patch:B})=>Mu(g,B),onSuccess:ye}),we=g=>{n(B=>{const de=new URLSearchParams(B);for(const[be,Ne]of Object.entries(g))Ne?de.set(be,Ne):de.delete(be);return de})},Me=(g=le)=>{I(null),w({open:!0,phase:"domain",domain:g})},Ve=async g=>{if(!ee)return;I(null),S(!0);const B=ce.filter(Ne=>{var lt;return Ne.domain===g&&((lt=Ne.user)==null?void 0:lt.id)===ee}),de=ce.filter(Ne=>Ne.domain===g),be=(B.length>0?B:de).slice(0,12);if(be.length<2){I("Forge needs at least two matching records in this domain before it can start the game."),S(!1),w(Ne=>({...Ne,phase:"domain"}));return}try{we({domain:g,tab:"overview",contextId:null,focusItem:null}),await Promise.all(be.map(Ne=>On({userId:ee,domain:g,entityType:Ne.entityType,entityId:Ne.entityId,label:Ne.label,description:Ne.description,tags:[]}))),await ye(),w({open:!0,phase:"play",domain:g})}catch(Ne){I(Ne instanceof Error?Ne.message:"Forge could not start the game."),w(lt=>({...lt,phase:"domain"}))}finally{S(!1)}},Se=async(g,B)=>{if(ee){I(null),we({domain:g,tab:"overview",contextId:null,focusItem:null});try{await ct.mutateAsync({userId:ee,domain:g,contextId:ue??void 0,catalogId:B}),w({open:!0,phase:"play",domain:g})}catch(de){I(de instanceof Error?de.message:"Forge could not start the game.")}}},xe=async g=>{if(Qb.has(g)){await Ve(g);return}I(null),w({open:!0,phase:"catalog",domain:g})},Ie=async(g,B=1)=>{if(!ee||!(je!=null&&je.compare.nextPair))return;const de=je.compare.nextPair;await zt.mutateAsync({userId:ee,domain:p.domain,contextId:je.selectedContext.id,leftItemId:de.left.id,rightItemId:de.right.id,outcome:g,strength:B})},Ee=async(g,B)=>{!ee||!je||await qt.mutateAsync({userId:ee,domain:p.domain,contextId:je.selectedContext.id,itemId:g,signalType:B,strength:1})};if(!ee)return e.jsx(gt,{eyebrow:"Preferences",title:"No Forge user available",description:"Forge needs at least one human or bot user before it can learn preferences."});if(E.isLoading&&!K)return e.jsx(xt,{eyebrow:"Preferences",title:"Loading preference model",description:"Reconstructing current scores, uncertainty, and concept libraries."});if(E.isError)return e.jsx(Oe,{eyebrow:"Preferences",error:E.error,onRetry:()=>void E.refetch()});if(!K)return null;const et=[...K.dimensions].sort((g,B)=>B.confidence-g.confidence).slice(0,6),Fe=K.scores.filter(g=>pa(g)==="liked"||pa(g)==="favorite").slice(0,4),ut=K.scores.filter(g=>g.uncertainty>=.5).slice(0,4),Te=Jb(K),rt=Hb(((ds=D==null?void 0:D.item)==null?void 0:ds.sourceEntityType)??null,((Ds=D==null?void 0:D.item)==null?void 0:Ds.sourceEntityId)??null),kt=(je==null?void 0:je.compare.nextPair)??null;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{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:`${K.summary.totalItems} items · ${bi(K.summary.averageConfidence)} confidence`,actions:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{className:"min-w-[10rem]",onClick:()=>Me(),children:"Start the game"}),e.jsx(W,{variant:"secondary",onClick:()=>void ye(),children:"Refresh model"})]})}),e.jsx(Ht,{}),e.jsxs(se,{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:ee,onChange:g=>we({userId:g.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(g=>e.jsxs("option",{value:g.id,children:[g.displayName," · ",g.kind]},g.id))}),e.jsx($e,{user:$}),e.jsx("div",{className:"text-sm text-white/54",children:Qt($)})]})]}),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:ma.map(g=>e.jsx("button",{type:"button",className:re("rounded-full border px-3 py-2 text-sm transition",g.value===le?"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:()=>we({domain:g.value,contextId:null,focusItem:null}),children:g.label},g.value))}),e.jsx("div",{className:"text-sm text-white/48",children:($s=ma.find(g=>g.value===le))==null?void 0:$s.description})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-white/50",children:[e.jsx(O,{className:"bg-white/[0.08] text-white/70",children:K.selectedContext.name}),e.jsx("span",{children:K.selectedContext.shareMode}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[K.compare.pendingCount," queued comparisons"]}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[K.libraries.totalCatalogItems," concept items ready"]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Sc.map(g=>e.jsxs("button",{type:"button",className:re("inline-flex items-center gap-2 rounded-full border px-3 py-2 text-sm transition",g.id===oe?"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:()=>we({tab:g.id}),children:[e.jsx(g.icon,{className:"size-4"}),g.label]},g.id))}),oe==="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(se,{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:Te.title}),e.jsx("div",{className:"max-w-[70ch] text-sm leading-6 text-white/58",children:Te.description})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[{label:"Known items",value:K.summary.totalItems,detail:"Items inside this domain"},{label:"Confidence",value:bi(K.summary.averageConfidence),detail:"Average certainty"},{label:"Unknowns",value:K.summary.uncertainCount,detail:"Need more rounds"},{label:"Libraries",value:K.libraries.totalCatalogItems,detail:"Seeded concepts ready"}].map(g=>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:g.label}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:g.value}),e.jsx("div",{className:"mt-1 text-sm text-white/52",children:g.detail})]},g.label))}),e.jsx("div",{className:"grid gap-4 lg:grid-cols-2",children:et.map(g=>e.jsx(Yb,{summary:g},g.dimensionId))})]}),e.jsxs(se,{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:()=>Me(),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: ",K.compare.pendingCount," comparison",K.compare.pendingCount===1?"":"s"]}),e.jsxs("div",{children:["Active context: ",K.selectedContext.name]}),e.jsxs("div",{children:["Library coverage: ",K.libraries.seededCatalogCount," ","seeded lists and ",K.libraries.customCatalogCount," ","custom lists"]})]})]})]}),e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.3fr)_360px]",children:[e.jsxs(se,{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(Le,{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"}),K.map.map(g=>e.jsx("button",{type:"button",className:re("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]",g.itemId===(D==null?void 0:D.itemId)?"border-white/30 bg-white/16 text-white":g.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+g.x*30}%`,top:`${50-g.y*30}%`,opacity:.55+g.confidence*.45},onClick:()=>P(g.itemId),children:g.label},g.itemId))]})]}),e.jsxs(se,{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:Fe.length>0?Fe.map(g=>{var B;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:()=>{P(g.itemId),we({focusItem:g.itemId})},children:[e.jsx("div",{className:"font-medium text-white",children:((B=g.item)==null?void 0:B.label)??g.itemId}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:g.explanation[0]||"Forge has positive evidence here."})]},g.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:ut.length>0?ut.map(g=>{var B;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:((B=g.item)==null?void 0:B.label)??g.itemId}),e.jsxs("div",{className:"mt-1",children:["Uncertainty ",bi(g.uncertainty)]})]},g.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(se,{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(O,{className:"bg-white/[0.08] text-white/70",children:[X.length," visible"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(dt,{className:"size-4 text-white/38"}),e.jsx(ie,{value:l,onChange:g=>d(g.target.value),placeholder:"Search across owners, handles, user kind, title, and description"})]}),e.jsx("div",{className:"grid gap-2",children:X.map(g=>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:g.label}),e.jsx(O,{className:"bg-white/[0.08] text-white/70",children:g.entityType}),g.user?e.jsx($e,{user:g.user,compact:!0}):null]}),e.jsx("div",{className:"mt-1 text-sm text-white/52",children:g.description||"No description yet."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[g.href?e.jsx(Le,{to:g.href,children:e.jsx(W,{variant:"ghost",size:"sm",children:"Open"})}):null,e.jsx(W,{variant:"secondary",size:"sm",pending:ze.isPending,pendingLabel:"Adding",onClick:()=>void ze.mutateAsync({userId:ee,domain:le,entityType:g.entityType,entityId:g.entityId,label:g.label,description:g.description,tags:[]}),children:"Add to model"})]})]},`${g.entityType}-${g.entityId}`))})]})]}):null,oe==="map"?e.jsxs(se,{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:[K.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"}),K.map.map(g=>e.jsx("button",{type:"button",className:re("absolute -translate-x-1/2 -translate-y-1/2 rounded-full border px-3 py-1 text-xs transition hover:scale-[1.04]",g.itemId===(D==null?void 0:D.itemId)?"border-white/30 bg-white/16 text-white":g.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+g.x*34}%`,top:`${50-g.y*34}%`,opacity:.45+g.confidence*.55},onClick:()=>{P(g.itemId),we({focusItem:g.itemId})},children:g.label},g.itemId))]})]}):null,oe==="table"?e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.2fr)_380px]",children:[e.jsxs(se,{className:"grid gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(dt,{className:"size-4 text-white/38"}),e.jsx(ie,{value:a,onChange:g=>r(g.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(g=>{var B,de;return e.jsxs("tr",{className:re("cursor-pointer border-t border-white/6 transition hover:bg-white/[0.04]",g.itemId===(D==null?void 0:D.itemId)?"bg-white/[0.05]":""),onClick:()=>{P(g.itemId),we({focusItem:g.itemId})},children:[e.jsxs("td",{className:"px-3 py-3",children:[e.jsx("div",{className:"font-medium text-white",children:((B=g.item)==null?void 0:B.label)??g.itemId}),e.jsx("div",{className:"text-xs text-white/48",children:(((de=g.item)==null?void 0:de.tags)??[]).join(" · ")})]}),e.jsx("td",{className:"px-3 py-3 text-white/68",children:g.latentScore.toFixed(2)}),e.jsx("td",{className:"px-3 py-3 text-white/68",children:bi(g.confidence)}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(O,{className:so[pa(g)],children:pa(g)})}),e.jsx("td",{className:"px-3 py-3 text-white/68",children:g.evidenceCount})]},g.itemId)})})]})})]}),e.jsxs(se,{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Item editor"}),D!=null&&D.item?e.jsxs(e.Fragment,{children:[e.jsx(ie,{value:y.label,onChange:g=>N(B=>({...B,label:g.target.value})),placeholder:"Item label"}),e.jsx(Ce,{value:y.description,onChange:g=>N(B=>({...B,description:g.target.value})),className:"min-h-24",placeholder:"Item description"}),e.jsx(ie,{value:y.tags,onChange:g=>N(B=>({...B,tags:g.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:g=>N(B=>({...B,manualStatus:g.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(so).map(g=>e.jsx("option",{value:g,children:g},g))]}),e.jsx(ie,{value:y.manualScore,onChange:g=>N(B=>({...B,manualScore:g.target.value})),placeholder:"Manual score"}),e.jsx(ie,{value:y.confidenceLock,onChange:g=>N(B=>({...B,confidenceLock:g.target.value})),placeholder:"Confidence lock 0-1"})]}),e.jsx("div",{className:"grid gap-2",children:Object.keys(ha).map(g=>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:qn[g]}),e.jsx(ie,{value:y.featureWeights[g],onChange:B=>N(de=>({...de,featureWeights:{...de.featureWeights,[g]:B.target.value}}))})]},g))}),e.jsx("div",{className:"grid gap-2 text-sm text-white/58",children:[["bookmarked","Bookmarked"],["compareLater","Compare later"],["frozen","Frozen"]].map(([g,B])=>e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:y[g],onChange:de=>N(be=>({...be,[g]:de.target.checked}))}),e.jsx("span",{children:B})]},g))}),e.jsx(W,{pending:Pt.isPending,pendingLabel:"Saving item",onClick:()=>void Pt.mutateAsync(),children:"Save item model"}),rt?e.jsx(Le,{className:"text-sm text-[var(--primary)]",to:rt,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(ie,{value:A.label,onChange:g=>T(B=>({...B,label:g.target.value})),placeholder:"Custom item label"}),e.jsx(Ce,{value:A.description,onChange:g=>T(B=>({...B,description:g.target.value})),className:"min-h-24",placeholder:"What is this preference item?"}),e.jsx(ie,{value:A.tags,onChange:g=>T(B=>({...B,tags:g.target.value})),placeholder:"comma, separated, tags"}),e.jsx(W,{disabled:!A.label.trim(),pending:fe.isPending,pendingLabel:"Creating item",onClick:()=>void fe.mutateAsync({userId:ee,domain:le,label:A.label,description:A.description,tags:A.tags.split(",").map(g=>g.trim()).filter(Boolean),featureWeights:ha,queueForCompare:!0}),children:"Create custom item"})]})]})]})]}):null,oe==="history"?e.jsxs("div",{className:"grid gap-5 xl:grid-cols-3",children:[e.jsxs(se,{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:K.history.judgments.slice(0,12).map(g=>{var be,Ne,lt,fs;const B=((Ne=(be=K.scores.find(cs=>cs.itemId===g.leftItemId))==null?void 0:be.item)==null?void 0:Ne.label)??g.leftItemId,de=((fs=(lt=K.scores.find(cs=>cs.itemId===g.rightItemId))==null?void 0:lt.item)==null?void 0:fs.label)??g.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:[B," vs ",de]}),e.jsxs("div",{className:"mt-1",children:["Outcome ",g.outcome," · strength"," ",g.strength," ·"," ",new Date(g.createdAt).toLocaleString()]})]},g.id)})})]}),e.jsxs(se,{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:K.history.signals.slice(0,8).map(g=>{var de,be;const B=((be=(de=K.scores.find(Ne=>Ne.itemId===g.itemId))==null?void 0:de.item)==null?void 0:be.label)??g.itemId;return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-2 text-sm text-white/58",children:[B," · ",g.signalType," ·"," ",new Date(g.createdAt).toLocaleString()]},g.id)})}),e.jsx("div",{className:"grid gap-2",children:K.history.snapshots.slice(0,5).map(g=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-2 text-sm text-white/58",children:["Snapshot ",new Date(g.createdAt).toLocaleString()]},g.id))}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/58",children:["Stale items: ",K.history.staleItemIds.length," · Flipped items: ",K.history.flippedItemIds.length]})]})]}):null,oe==="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:K.contexts.map(g=>e.jsxs(se,{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:g.name}),e.jsx("div",{className:"text-sm text-white/54",children:g.description||"No description yet."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[g.isDefault?e.jsx(O,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"Default"}):null,e.jsx(O,{className:"bg-white/[0.08] text-white/70",children:g.shareMode}),g.active?null:e.jsx(O,{className:"bg-amber-500/12 text-amber-200",children:"Inactive"})]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[e.jsx(ie,{value:g.name,onChange:B=>void te.mutateAsync({contextId:g.id,patch:{name:B.target.value}}),placeholder:"Context name"}),e.jsxs("select",{value:g.shareMode,onChange:B=>void te.mutateAsync({contextId:g.id,patch:{shareMode:B.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(ie,{value:String(g.decayDays),onChange:B=>void te.mutateAsync({contextId:g.id,patch:{decayDays:Number(B.target.value||90)}}),placeholder:"Decay days"}),e.jsx(W,{variant:"secondary",onClick:()=>we({contextId:g.id,tab:"overview"}),children:"Open context"})]}),e.jsx(Ce,{value:g.description,onChange:B=>void te.mutateAsync({contextId:g.id,patch:{description:B.target.value}}),className:"min-h-20"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{variant:"secondary",onClick:()=>void te.mutateAsync({contextId:g.id,patch:{active:!g.active}}),children:g.active?"Deactivate":"Activate"}),g.isDefault?null:e.jsx(W,{variant:"secondary",onClick:()=>void te.mutateAsync({contextId:g.id,patch:{isDefault:!0}}),children:"Make default"})]})]},g.id))}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(se,{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Create context"}),e.jsx(ie,{value:F.name,onChange:g=>u(B=>({...B,name:g.target.value})),placeholder:"Context name"}),e.jsx(Ce,{value:F.description,onChange:g=>u(B=>({...B,description:g.target.value})),className:"min-h-24",placeholder:"What changes in this context?"}),e.jsxs("select",{value:F.shareMode,onChange:g=>u(B=>({...B,shareMode:g.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(ie,{value:F.decayDays,onChange:g=>u(B=>({...B,decayDays:g.target.value})),placeholder:"Decay days"}),e.jsx(W,{disabled:!F.name.trim(),pending:Mt.isPending,pendingLabel:"Creating context",onClick:()=>void Mt.mutateAsync({userId:ee,domain:le,name:F.name,description:F.description,shareMode:F.shareMode,decayDays:Number(F.decayDays||90),active:!0,isDefault:!1}),children:"Create context"})]}),e.jsxs(se,{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:f,onChange:g=>b(g.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"}),K.contexts.map(g=>e.jsx("option",{value:g.id,children:g.name},g.id))]}),e.jsxs("select",{value:m,onChange:g=>h(g.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"}),K.contexts.map(g=>e.jsx("option",{value:g.id,children:g.name},g.id))]}),e.jsx(W,{pending:Et.isPending,pendingLabel:"Merging",disabled:!f||!m||f===m,onClick:()=>void Et.mutateAsync({sourceContextId:f,targetContextId:m}),children:"Merge into target"})]})]})]}):null,oe==="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(se,{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",K.libraries.totalCatalogs],["Concepts",K.libraries.totalCatalogItems],["Seeded",K.libraries.seededCatalogCount],["Custom",K.libraries.customCatalogCount]].map(([g,B])=>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:g}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:B})]},g))}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(dt,{className:"size-4 text-white/38"}),e.jsx(ie,{value:o,onChange:g=>x(g.target.value),placeholder:"Search lists, concepts, tags, and seeded domains"})]})]}),e.jsxs(se,{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Create concept list"}),e.jsx(ie,{value:j.title,onChange:g=>L(B=>({...B,title:g.target.value})),placeholder:"List title"}),e.jsx(Ce,{value:j.description,onChange:g=>L(B=>({...B,description:g.target.value})),className:"min-h-24",placeholder:"What should this list help compare?"}),e.jsx(W,{disabled:!j.title.trim(),pending:Pe.isPending,pendingLabel:"Creating list",onClick:()=>void Pe.mutateAsync({userId:ee,domain:le,title:j.title,description:j.description}),children:"Create list"})]})]}),e.jsx("div",{className:"grid gap-4",children:he.map(g=>{const B=q[g.id]??{label:"",description:"",tags:""},de=g.items.filter(be=>o.trim()?[be.label,be.description,be.tags.join(" ")].join(" ").toLowerCase().includes(ua(o)):!0);return e.jsxs(se,{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:Q===g.id?e.jsxs("div",{className:"grid gap-3",children:[e.jsx(ie,{value:H.title,onChange:be=>_(Ne=>({...Ne,title:be.target.value}))}),e.jsx(Ce,{value:H.description,onChange:be=>_(Ne=>({...Ne,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:g.title}),e.jsx(O,{className:"bg-white/[0.08] text-white/70",children:g.source}),e.jsxs(O,{className:"bg-white/[0.08] text-white/70",children:[g.items.length," items"]})]}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:g.description||"No description yet."})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>void Se(le,g.id),children:"Start from this list"}),Q===g.id?e.jsxs(e.Fragment,{children:[e.jsx(W,{size:"sm",pending:Ge.isPending,pendingLabel:"Saving",onClick:()=>void Ge.mutateAsync({catalogId:g.id,patch:{title:H.title,description:H.description}}),children:"Save"}),e.jsx(W,{variant:"ghost",size:"sm",onClick:()=>ne(null),children:"Cancel"})]}):e.jsx(W,{variant:"ghost",size:"sm",onClick:()=>{ne(g.id),_({title:g.title,description:g.description})},children:"Edit list"}),e.jsx(W,{variant:"ghost",size:"sm",pending:Z.isPending,pendingLabel:"Deleting",onClick:()=>void Z.mutateAsync(g.id),children:"Delete list"})]})]}),e.jsx("div",{className:"grid gap-2",children:de.map(be=>e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:U===be.id?e.jsxs("div",{className:"grid gap-3",children:[e.jsx(ie,{value:C.label,onChange:Ne=>J(lt=>({...lt,label:Ne.target.value}))}),e.jsx(Ce,{value:C.description,onChange:Ne=>J(lt=>({...lt,description:Ne.target.value})),className:"min-h-20"}),e.jsx(ie,{value:C.tags,onChange:Ne=>J(lt=>({...lt,tags:Ne.target.value})),placeholder:"comma, separated, tags"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{size:"sm",pending:Ue.isPending,pendingLabel:"Saving",onClick:()=>void Ue.mutateAsync({catalogItemId:be.id,patch:{label:C.label,description:C.description,tags:C.tags.split(",").map(Ne=>Ne.trim()).filter(Boolean)}}),children:"Save concept"}),e.jsx(W,{variant:"ghost",size:"sm",onClick:()=>R(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(Ne=>e.jsx(O,{className:"bg-white/[0.08] text-white/70",children:Ne},`${be.id}-${Ne}`))})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{variant:"ghost",size:"sm",onClick:()=>{R(be.id),J({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(bt,{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(Wt,{className:"size-4"}),"Add concept to ",g.title]}),e.jsx(ie,{value:B.label,onChange:be=>G(Ne=>({...Ne,[g.id]:{...B,label:be.target.value}})),placeholder:"Concept label"}),e.jsx(Ce,{value:B.description,onChange:be=>G(Ne=>({...Ne,[g.id]:{...B,description:be.target.value}})),className:"min-h-20",placeholder:"Short description"}),e.jsx(ie,{value:B.tags,onChange:be=>G(Ne=>({...Ne,[g.id]:{...B,tags:be.target.value}})),placeholder:"comma, separated, tags"}),e.jsx(W,{disabled:!B.label.trim(),pending:He.isPending,pendingLabel:"Adding",onClick:()=>void He.mutateAsync({catalogId:g.id,label:B.label,description:B.description,tags:B.tags.split(",").map(be=>be.trim()).filter(Boolean),featureWeights:ha}).then(()=>G(be=>({...be,[g.id]:{label:"",description:"",tags:""}}))),children:"Add concept"})]})]},g.id)})})]}):null]}),e.jsx(Lt,{open:p.open,onOpenChange:g=>{g||I(null),w(B=>({...B,open:g}))},children:e.jsxs(Dt,{children:[e.jsx($t,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.74)] backdrop-blur-xl"}),e.jsxs(Ot,{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(Rt,{className:"sr-only",children:"Preference game"}),e.jsx(Gt,{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(_t,{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(mt,{className:"size-4"})})})]}),e.jsxs("div",{className:"grid gap-5 px-5 py-5",children:[v?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:v}):null,p.phase==="domain"?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:ma.map(g=>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 xe(g.value),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:g.label}),e.jsx(O,{className:"bg-white/[0.08] text-white/70",children:g.mode==="forge"?"Forge":"Concept"})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:g.description})]},g.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(dt,{className:"size-4 text-white/38"}),e.jsx(ie,{value:o,onChange:g=>x(g.target.value),placeholder:"Search concept lists"})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:he.length>0?he.map(g=>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 Se(p.domain,g.id),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:g.title}),e.jsxs(O,{className:"bg-white/[0.08] text-white/70",children:[g.items.length," items"]})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:g.description||"No description yet."})]},g.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:k||z.isLoading?e.jsx(xt,{eyebrow:"Preference game",title:"Preparing the next round",description:"Forge is lining up comparison candidates."}):kt?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-white/52",children:[e.jsx(O,{className:"bg-white/[0.08] text-white/70",children:((Os=ma.find(g=>g.value===p.domain))==null?void 0:Os.label)??p.domain}),e.jsx("span",{children:je==null?void 0:je.selectedContext.name}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[(je==null?void 0:je.compare.pendingCount)??0," ","queued comparisons"]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx(io,{title:kt.left.label,description:kt.left.description,sideLabel:"Left",onClick:()=>void Ie("left",1)}),e.jsx(io,{title:kt.right.label,description:kt.right.description,sideLabel:"Right",onClick:()=>void Ie("right",1)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{onClick:()=>void Ie("left",1),children:"Left"}),e.jsx(W,{onClick:()=>void Ie("right",1),children:"Right"}),e.jsx(W,{variant:"secondary",onClick:()=>void Ie("left",1.75),children:"Strong left"}),e.jsx(W,{variant:"secondary",onClick:()=>void Ie("right",1.75),children:"Strong right"}),e.jsx(W,{variant:"secondary",onClick:()=>void Ie("tie",1),children:"Tie"}),e.jsx(W,{variant:"secondary",onClick:()=>void Ie("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:[kt.left,kt.right].map(g=>e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:g.label}),e.jsx("div",{className:"text-sm text-white/56",children:"Quick signals"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Wb.map(B=>e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>void Ee(g.id,B.signalType),children:B.label},`${g.id}-${B.signalType}`))})]},g.id))})]}):e.jsx(gt,{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 Nr(t,s,i){return Math.min(Math.max(t,s),i)}function kr(t,s,i){return Math.min(i,Math.max(1,Math.ceil(t.trim().length/s)))}function Zb(t,{compact:s}){const i=kr(t,s?13:14,4),a=(s?114:156)+(i-1)*(s?12:18)+Math.min(24,Math.max(0,t.trim().length-18))*(s?.7:1);return Nr(a,s?118:164,s?154:210)}function ef(t,{compact:s}){const i=kr(t,s?11:13,3),a=(s?40:48)+(i-1)*(s?6:8)+Math.min(s?18:26,Math.max(0,t.trim().length-(s?12:16)))*(s?.45:.55);return Nr(a,s?42:50,s?56:68)}function $i(t,{compact:s,emphasis:i=!1}){const a=kr(t,s?16:i?22:20,i?3:2);return{width:Nr((s?i?184:152:i?224:176)+Math.min(t.length,48)*(s?1.8:2.15),s?i?188:156:i?228:184,s?i?248:208:i?300:244),height:a===1?s?64:70:a===2?s?82:92:s?98:110}}function ao(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 tf(t,{compact:s}){const i=t.map(r=>({...r,homeX:r.x,homeY:r.y,locked:r.kind==="goal"||r.kind==="ghost"})),n=s?28:40,a=s?.08:.06;for(let r=0;r<180;r+=1){for(const l of i)l.locked||(l.x+=(l.homeX-l.x)*a,l.y+=(l.homeY-l.y)*a);for(let l=0;l<i.length;l+=1)for(let d=l+1;d<i.length;d+=1){const o=i[l],x=i[d],f=ao(o),b=ao(x),m=x.x-o.x,h=x.y-o.y,p=f.halfWidth+b.halfWidth+n-Math.abs(m),w=f.halfHeight+b.halfHeight+n-Math.abs(h);if(p<=0||w<=0)continue;const v=p<w?"x":"y",I=Math.sign(v==="x"?m||d-l||1:h||d-l||1),k=(v==="x"?p:w)/(o.locked||x.locked?1:2);o.locked||(v==="x"?o.x-=I*k:o.y-=I*k),x.locked||(v==="x"?x.x+=I*k:x.y+=I*k)}}return i.map(({homeX:r,homeY:l,locked:d,...o})=>o)}function sf(){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 Cc(t,{compact:s=!1}={}){var x;if(t.length===0)return sf();const i=[],n=[],a=[],r={},l=s?560:840,d=-((t.length-1)*l)/2;t.forEach((f,b)=>{const m=d+b*l,h=b%2===0?92:146,p=f.linkedBehaviors.length+f.linkedBeliefs.length+f.linkedReports.length+f.linkedHabits.length,w=`goal:${f.goal.id}`;i.push({id:w,kind:"goal",x:m,y:h,radius:Zb(f.goal.title,{compact:s}),tone:"amber",label:f.goal.title,href:`/goals/${f.goal.id}`}),r[w]={id:w,eyebrow:"Goal",title:f.goal.title,summary:f.goal.description,href:`/goals/${f.goal.id}`,ctaLabel:"Open goal",tone:"amber",entityKind:"goal",chips:f.linkedValues.slice(0,4).map(u=>u.title),stats:[`${f.linkedValues.length} linked value${f.linkedValues.length===1?"":"s"}`,`${f.linkedProjects.length} live project${f.linkedProjects.length===1?"":"s"}`,`${f.linkedHabits.length} linked habit${f.linkedHabits.length===1?"":"s"}`,`${p} friction signal${p===1?"":"s"}`]},p>0&&a.push({id:`field:${f.goal.id}`,x:m+18,y:h+20,radiusX:s?144:176,radiusY:s?104:132,tone:"rose",opacity:Math.min(.42,.14+p*.04)});const v=s?208:282;f.linkedValues.slice(0,s?4:5).forEach((u,j)=>{const L=(-95+j*(s?78:64))*(Math.PI/180),q=ef(u.title,{compact:s}),G=m+Math.cos(L)*v,Q=h+Math.sin(L)*v,ne=`value:${u.id}`;i.push({id:ne,kind:"value",x:G,y:Q,radius:q,tone:"mint",label:u.title,meta:`${u.linkedGoalIds.length} goal${u.linkedGoalIds.length===1?"":"s"}`,href:`/psyche/values?focus=${u.id}#values-atlas`}),n.push({id:`${w}->${ne}`,from:w,to:ne,tone:"mint",strength:"medium"}),r[ne]={id:ne,eyebrow:"Value",title:u.title,summary:u.valuedDirection||u.whyItMatters||u.description,href:`/psyche/values?focus=${u.id}#values-atlas`,ctaLabel:"Open values",tone:"mint",entityKind:"value",chips:u.committedActions.slice(0,3),stats:[`${u.linkedProjectIds.length} linked project${u.linkedProjectIds.length===1?"":"s"}`,`${u.linkedTaskIds.length} linked task${u.linkedTaskIds.length===1?"":"s"}`]}});const I=f.linkedProjects.slice(0,s?2:3).map(u=>({project:u,size:$i(u.title,{compact:s,emphasis:!0})})),k=s?24:30;let M=-(I.reduce((u,j)=>u+j.size.width,0)+Math.max(0,I.length-1)*k)/2;I.forEach(({project:u,size:j},L)=>{const q=`project:${u.id}`,G=m+M+j.width/2,Q=h-(s?330:434)-L*(s?16:20);M+=j.width+k,i.push({id:q,kind:"project",x:G,y:Q,width:j.width,height:j.height,tone:"sky",label:u.title,meta:"Project",href:`/projects/${u.id}`}),n.push({id:`${w}->${q}`,from:w,to:q,tone:"sky",strength:"medium"}),r[q]={id:q,eyebrow:"Project",title:u.title,summary:u.description,href:`/projects/${u.id}`,ctaLabel:"Open project",tone:"sky",entityKind:"project",chips:[u.status,u.goalTitle],stats:[`${u.progress}% progress`,`${u.activeTaskCount} active task${u.activeTaskCount===1?"":"s"}`]}}),f.linkedHabits.slice(0,s?2:3).forEach((u,j)=>{const L=`habit:${u.id}`,q=$i(u.title,{compact:s}),G=m-(s?44:58),Q=h+(s?228:294)+j*(s?92:104);i.push({id:L,kind:"habit",x:G,y:Q,width:q.width,height:q.height,tone:"mint",label:u.title,meta:u.polarity,href:"/habits"}),n.push({id:`${w}->${L}`,from:w,to:L,tone:"mint",strength:u.dueToday?"high":"medium"}),r[L]={id:L,eyebrow:"Habit",title:u.title,summary:u.description||"Recurring operating record connected directly to this goal field.",href:"/habits",ctaLabel:"Open habits",tone:"mint",entityKind:"habit",chips:[u.polarity,u.frequency,u.dueToday?"due today":"checked in"],stats:[`${u.streakCount} streak`,`${u.rewardXp}/${u.penaltyXp} xp flow`]}});let P=h+(s?132:156);f.linkedBehaviors.slice(0,s?2:3).forEach(u=>{const j=`behavior:${u.id}`,L=$i(u.title,{compact:s}),q=m-(s?272:352);i.push({id:j,kind:"behavior",x:q,y:P,width:L.width,height:L.height,tone:"orange",label:u.title,meta:u.kind,href:`/psyche/behaviors?focus=${u.id}#behavior-columns`}),n.push({id:`${w}->${j}`,from:w,to:j,tone:"orange",dashed:u.kind!=="committed",strength:u.kind==="committed"?"medium":"low"}),r[j]={id:j,eyebrow:"Behavior",title:u.title,summary:u.replacementMove||u.description||u.urgeStory,href:`/psyche/behaviors?focus=${u.id}#behavior-columns`,ctaLabel:"Open behaviors",tone:"orange",entityKind:"behavior",chips:[u.kind,...u.commonCues.slice(0,2)],stats:[u.shortTermPayoff?"Short-term payoff mapped":"Payoff still to map",u.longTermCost?"Long-term cost mapped":"Cost still to map"]},P+=L.height+(s?18:22)});let y=h+(s?8:10);f.linkedBeliefs.slice(0,s?2:3).forEach(u=>{const j=`belief:${u.id}`,L=$i(u.statement,{compact:s,emphasis:!0}),q=m+(s?278:362);i.push({id:j,kind:"belief",x:q,y,width:L.width,height:L.height,tone:"violet",label:u.statement,meta:"belief",href:`/psyche/schemas-beliefs?focus=${u.id}`}),n.push({id:`${w}->${j}`,from:w,to:j,tone:"violet",dashed:!0,strength:"low"}),r[j]={id:j,eyebrow:"Belief",title:u.statement,summary:u.flexibleAlternative||u.originNote||"Belief script attached to this part of the map.",href:`/psyche/schemas-beliefs?focus=${u.id}`,ctaLabel:"Open beliefs",tone:"violet",entityKind:"belief",chips:[u.beliefType,`${u.confidence}% grip`],stats:[`${u.linkedBehaviorIds.length} linked behavior${u.linkedBehaviorIds.length===1?"":"s"}`,`${u.linkedReportIds.length} linked report${u.linkedReportIds.length===1?"":"s"}`]},y+=L.height+(s?18:22)});const N=f.linkedReports.slice(0,s?2:3).map(u=>({report:u,size:$i(u.title,{compact:s})})),A=s?20:26;let F=-(N.reduce((u,j)=>u+j.size.width,0)+Math.max(0,N.length-1)*A)/2;N.forEach(({report:u,size:j})=>{const L=`report:${u.id}`,q=m+F+j.width/2,G=h+(s?332:430);F+=j.width+A,i.push({id:L,kind:"report",x:q,y:G,width:j.width,height:j.height,tone:"blue",label:u.title,meta:u.status,href:`/psyche/reports/${u.id}`}),n.push({id:`${w}->${L}`,from:w,to:L,tone:"sky",strength:"medium"}),r[L]={id:L,eyebrow:"Report",title:u.title,summary:u.eventSituation||u.customEventType||"Reflective chain linked into this goal.",href:`/psyche/reports/${u.id}`,ctaLabel:"Open report",tone:"blue",entityKind:"report",chips:[u.status,...u.nextMoves.slice(0,2)],stats:[`${u.emotions.length} emotion${u.emotions.length===1?"":"s"}`,`${u.behaviors.length} move${u.behaviors.length===1?"":"s"}`]}})});const o=((x=i[0])==null?void 0:x.id)??"ghost_goal_center";return{nodes:tf(i,{compact:s}),edges:n,fields:a,inspectors:r,defaultSelectedId:o}}const Fs={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)"},fn={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)"},_s={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 Ic(t){switch(t){case"goal":case"value":case"behavior":case"belief":case"report":case"project":case"habit":return t;default:return null}}function af(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 nf(t){if(t.kind==="ghost")return t.meta??null;const s=Ic(t.kind);return s?Ts(s).label:t.meta??null}function wn(t,s,i){return Math.min(Math.max(t,s),i)}function xa(t,s,i=3){const n=t.trim().split(/\s+/),a=[];let r="";for(let o=0;o<n.length;o+=1){const x=n[o],f=r?`${r} ${x}`:x;if(f.length>s&&r){if(a.push(r),a.length>=i-1){r=[x,...n.slice(o+1)].join(" ");break}r=x}else r=f}r&&a.push(r);const l=a.slice(0,i),d=l.length-1;return d>=0&&l[d].length>s&&(l[d]=`${l[d].slice(0,Math.max(1,s-1)).trimEnd()}…`),l}function rf(t,s){if(t.length===0&&s.length===0)return{minX:-360,maxX:360,minY:-240,maxY:240};let i=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY,a=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(const l of t){const d=l.kind==="goal"||l.kind==="value"||l.kind==="ghost"?l.radius??32:(l.width??124)/2,o=l.kind==="goal"||l.kind==="value"||l.kind==="ghost"?l.radius??32:(l.height??56)/2,x=l.meta&&(l.kind==="goal"||l.kind==="ghost")?48:0;i=Math.min(i,l.x-d),n=Math.max(n,l.x+d),a=Math.min(a,l.y-o-x),r=Math.max(r,l.y+o)}for(const l of s)i=Math.min(i,l.x-l.radiusX),n=Math.max(n,l.x+l.radiusX),a=Math.min(a,l.y-l.radiusY),r=Math.max(r,l.y+l.radiusY);return{minX:i,maxX:n,minY:a,maxY:r}}function no(t){return{x:t.x,y:t.y}}function lf(t){if(t.kind==="goal"){const s=t.radius??112;return xa(t.label,Math.max(14,Math.floor(s/7.2)),4)}if(t.kind==="value"||t.kind==="ghost"){const s=t.radius??40;return xa(t.label,Math.max(12,Math.floor(s/3)),3)}return t.kind==="project"?xa(t.label,Math.max(18,Math.floor((t.width??220)/10)),3):xa(t.label,Math.max(16,Math.floor((t.width??180)/10.5)),2)}function of(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 Tc({nodes:t,edges:s,fields:i=[],title:n,hint:a,action:r,legend:l,selectedNodeId:d,onSelectNode:o,minHeightClassName:x="min-h-[34rem] lg:min-h-[44rem]",compact:f=!1,testId:b}){const m=c.useRef(null),h=ht(),[p,w]=c.useState({width:0,height:0}),[v,I]=c.useState({scale:1,x:0,y:0}),[k,S]=c.useState(null),M=c.useRef(null),P=c.useRef({scale:1,x:0,y:0}),y=c.useRef(new Map),N=c.useRef(null),A=c.useRef(0),T=c.useRef(!1),F=c.useMemo(()=>new Map(t.map(C=>[C.id,C])),[t]),u=c.useMemo(()=>rf(t,i),[i,t]),j=p.width>0&&p.width<640;c.useEffect(()=>{if(!m.current||typeof ResizeObserver>"u")return;const C=new ResizeObserver(J=>{const ee=J[0];w({width:ee.contentRect.width,height:ee.contentRect.height})});return C.observe(m.current),()=>C.disconnect()},[]);const L=c.useCallback(()=>{if(!p.width||!p.height)return;const C=j?132:f?140:190,J=Math.max(u.maxX-u.minX,1),ee=Math.max(u.maxY-u.minY,1),le=wn(Math.min(p.width/(J+C),p.height/(ee+C)),j?.24:f?.4:.46,j?.76:f?1.04:1.18),oe=(u.minX+u.maxX)/2,ue=(u.minY+u.maxY)/2;I({scale:le,x:p.width/2-oe*le,y:p.height/2-ue*le})},[u.maxX,u.maxY,u.minX,u.minY,f,p.height,p.width,j]);c.useEffect(()=>{P.current=v},[v]),c.useEffect(()=>{T.current||L()},[L]);const q=c.useCallback((C,J,ee)=>{const le=wn(C,.28,1.9);I(oe=>{if(J==null||ee==null)return{...oe,scale:le};const ue=(J-oe.x)/oe.scale,me=(ee-oe.y)/oe.scale;return{scale:le,x:J-ue*le,y:ee-me*le}})},[]),G=c.useCallback(()=>{const C=[...y.current.values()];if(C.length<2){N.current=null;return}const[J,ee]=C,le=Math.hypot(ee.x-J.x,ee.y-J.y);if(!Number.isFinite(le)||le<=0){N.current=null;return}const oe=P.current;N.current={startDistance:le,startScale:oe.scale,startViewportX:oe.x,startViewportY:oe.y,startMidpointX:(J.x+ee.x)/2,startMidpointY:(J.y+ee.y)/2}},[]),Q=C=>{var le;C.preventDefault();const J=(le=m.current)==null?void 0:le.getBoundingClientRect();if(!J)return;T.current=!0;const ee=C.deltaY<0?1.1:.9;q(v.scale*ee,C.clientX-J.left,C.clientY-J.top)},ne=C=>{var oe;const J=(oe=m.current)==null?void 0:oe.getBoundingClientRect(),ee=C.clientX-((J==null?void 0:J.left)??0),le=C.clientY-((J==null?void 0:J.top)??0);if(y.current.set(C.pointerId,{x:ee,y:le}),y.current.size===1){const ue=P.current;M.current={pointerId:C.pointerId,originX:ue.x,originY:ue.y,startX:ee,startY:le}}else M.current=null,G();C.currentTarget.setPointerCapture(C.pointerId)},H=C=>{var me;const J=(me=m.current)==null?void 0:me.getBoundingClientRect(),ee=C.clientX-((J==null?void 0:J.left)??0),le=C.clientY-((J==null?void 0:J.top)??0);if(y.current.has(C.pointerId)&&y.current.set(C.pointerId,{x:ee,y:le}),N.current&&y.current.size>=2){const[$,ce]=[...y.current.values()],E=Math.hypot(ce.x-$.x,ce.y-$.y);if(Number.isFinite(E)&&E>0){T.current=!0,A.current=Date.now()+240;const z=($.x+ce.x)/2,K=($.y+ce.y)/2,je=N.current,V=wn(je.startScale*E/je.startDistance,.24,1.42),D=(je.startMidpointX-je.startViewportX)/je.startScale,X=(je.startMidpointY-je.startViewportY)/je.startScale;I({scale:V,x:z-D*V,y:K-X*V})}return}if(!M.current||M.current.pointerId!==C.pointerId||y.current.size!==1)return;T.current=!0;const oe=ee-M.current.startX,ue=le-M.current.startY;(Math.abs(oe)>3||Math.abs(ue)>3)&&(A.current=Date.now()+240),I($=>{var ce,E;return{...$,x:(((ce=M.current)==null?void 0:ce.originX)??$.x)+oe,y:(((E=M.current)==null?void 0:E.originY)??$.y)+ue}})},_=C=>{if(y.current.delete(C.pointerId),y.current.size<2&&(N.current=null),y.current.size===1){const[J,ee]=[...y.current.entries()][0]??[];if(J!=null&&ee){const le=P.current;M.current={pointerId:J,originX:le.x,originY:le.y,startX:ee.x,startY:ee.y}}}else M.current=null;C.currentTarget.hasPointerCapture(C.pointerId)&&C.currentTarget.releasePointerCapture(C.pointerId)},U=k??d??null,R=c.useCallback(C=>{Date.now()<A.current||(o==null||o(C.id),C.href&&h(C.href))},[h,o]);return e.jsxs("section",{"data-testid":b,className:re("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:re("mt-2 font-display leading-none text-white",f?"text-[clamp(1.25rem,2vw,1.7rem)]":"text-[clamp(1.45rem,2.8vw,2.3rem)]"),children:n}),a?e.jsx("p",{className:"mt-1.5 max-w-3xl text-sm leading-6 text-white/54",children:j?"Select a node, pan the field, and open the full map when you need the wider structure.":a}):null]}),e.jsx("div",{className:"flex min-w-0 flex-wrap items-center justify-end gap-2",children:r})]}),e.jsxs("div",{ref:m,className:re("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",x),style:{touchAction:"none"},onWheel:Q,onPointerDown:ne,onPointerMove:H,onPointerUp:_,onPointerCancel:_,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:C=>C.stopPropagation(),children:[e.jsx(Qm,{className:"size-3.5"}),j?"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:C=>C.stopPropagation(),children:[e.jsx(W,{type:"button",variant:"secondary",size:"sm",className:"px-2.5 sm:px-3","aria-label":"Zoom in",onClick:()=>{T.current=!0,q(v.scale*1.12,p.width-96,72)},children:e.jsx(Wt,{className:"size-4"})}),e.jsx(W,{type:"button",variant:"secondary",size:"sm",className:"px-2.5 sm:px-3","aria-label":"Zoom out",onClick:()=>{T.current=!0,q(v.scale*.88,p.width-96,72)},children:e.jsx(Wm,{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:()=>{T.current=!0,L()},children:[e.jsx(Gm,{className:"size-4"}),j?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:()=>{T.current=!1,L()},children:[e.jsx(Hm,{className:"size-4"}),j?null:"Reset"]})]}),l&&l.length>0&&!j?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(C=>{const J=C.kind?of(C.kind):C.tone??"slate",ee=C.kind?Ts(C.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:[ee?e.jsx(ee,{className:"size-3.5",color:_s[J],strokeWidth:2.1}):e.jsx("span",{className:"size-2 rounded-full",style:{backgroundColor:Fs[J]}}),C.label]},C.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":n,children:[e.jsx("defs",{children:e.jsx("filter",{id:"forge-graph-blur",children:e.jsx("feGaussianBlur",{stdDeviation:"34"})})}),e.jsxs("g",{transform:`translate(${v.x} ${v.y}) scale(${v.scale})`,children:[i.map(C=>e.jsx("ellipse",{cx:C.x,cy:C.y,rx:C.radiusX,ry:C.radiusY,fill:fn[C.tone??"rose"],opacity:C.opacity??.42,filter:"url(#forge-graph-blur)"},C.id)),t.filter(C=>C.kind==="goal"||C.kind==="ghost").map(C=>{const J=C.radius??76;return e.jsx("g",{opacity:C.kind==="ghost"?.28:.55,children:[J+74,J+124].map((ee,le)=>e.jsx("circle",{cx:C.x,cy:C.y,r:ee,fill:"none",stroke:le===0?"rgba(255,255,255,0.08)":"rgba(255,255,255,0.045)",strokeDasharray:le===0?"0":"10 10"},`${C.id}-ring-${ee}`))},`${C.id}-orbital-lanes`)}),s.map(C=>{const J=F.get(C.from),ee=F.get(C.to);if(!J||!ee)return null;const le=no(J),oe=no(ee),ue=(le.x+oe.x)/2,me=(le.y+oe.y)/2,$=Math.max(24,Math.abs(le.x-oe.x)*.08),ce=ue,E=me-$;return e.jsx("path",{d:`M ${le.x} ${le.y} Q ${ce} ${E} ${oe.x} ${oe.y}`,fill:"none",stroke:Fs[C.tone??"slate"],strokeWidth:C.strength==="high"?3:C.strength==="medium"?2.2:1.6,strokeDasharray:C.dashed?"8 8":void 0,opacity:U&&C.from!==U&&C.to!==U?.18:.62},C.id)}),t.map(C=>{C.id;const J=k===C.id,ee=U===C.id,le=af(C),oe=nf(C),ue=lf(C),me=Ic(C.kind),$=me?Ts(me).icon:null;if(C.kind==="goal"||C.kind==="value"||C.kind==="ghost"){const fe=C.radius??(C.kind==="goal"?76:34),Pe=oe?C.y-fe-(C.kind==="goal"?18:10):null,Ge=C.kind==="goal"?20:14.5,Z=C.kind==="goal"?28:16,He=C.kind==="goal"?C.y-fe*.34:C.kind==="value"?C.y-fe*.3:C.y-fe*.2,Ue=C.kind==="goal"?C.y+fe*.2:C.y+10;return e.jsxs("g",{tabIndex:0,role:"button",onPointerEnter:()=>{S(C.id),o==null||o(C.id)},onPointerLeave:()=>S(Qe=>Qe===C.id?null:Qe),onFocus:()=>o==null?void 0:o(C.id),onClick:()=>R(C),onKeyDown:Qe=>{(Qe.key==="Enter"||Qe.key===" ")&&(Qe.preventDefault(),R(C))},className:"cursor-pointer outline-none",children:[e.jsx("circle",{cx:C.x,cy:C.y,r:fe+(ee?14:0),fill:ee?`${Fs[le]}22`:"transparent",stroke:ee?Fs[le]:"transparent",opacity:J?.98:.9}),e.jsx("circle",{cx:C.x,cy:C.y,r:fe+(J?2:0),fill:C.kind==="ghost"?"rgba(255,255,255,0.03)":fn[le],stroke:C.kind==="ghost"?"rgba(255,255,255,0.18)":Fs[le],strokeDasharray:C.kind==="ghost"?"8 8":void 0,strokeWidth:ee?2.8:1.6}),oe?e.jsx("text",{x:C.x,y:Pe??C.y-12,textAnchor:"middle",fontSize:C.kind==="goal"?"11.5":"10.5",fill:C.kind==="ghost"?"rgba(255,255,255,0.62)":_s[le],style:{letterSpacing:"0.18em",textTransform:"uppercase"},children:oe}):null,$?e.jsx($,{x:C.x-Z/2,y:He-Z/2,width:Z,height:Z,color:_s[le],strokeWidth:2.1}):null,ue.map((Qe,ct)=>e.jsx("text",{x:C.x,y:Ue+ct*Ge-(ue.length-1)*Ge/2,textAnchor:"middle",fontSize:C.kind==="goal"?21:12.8,fontWeight:C.kind==="goal"?600:500,fill:C.kind==="ghost"?"rgba(255,255,255,0.92)":_s[le],children:Qe},`${C.id}-${Qe}-${ct}`))]},C.id)}const ce=C.width??146,E=C.height??58,z=C.x-ce/2,K=C.y-E/2,je=C.kind==="project"?14:13,V=z+14,D=K+13,X=K+22,he=oe?K+E*.65:K+E*.56,ye=C.kind==="project"?16:15,ze=C.kind==="project"?14.2:13.2;return e.jsxs("g",{tabIndex:0,role:"button",onPointerEnter:()=>{S(C.id),o==null||o(C.id)},onPointerLeave:()=>S(fe=>fe===C.id?null:fe),onFocus:()=>o==null?void 0:o(C.id),onClick:()=>R(C),onKeyDown:fe=>{(fe.key==="Enter"||fe.key===" ")&&(fe.preventDefault(),R(C))},className:"cursor-pointer outline-none",children:[e.jsx("rect",{x:z-(ee?6:0),y:K-(ee?6:0),rx:"28",ry:"28",width:ce+(ee?12:0),height:E+(ee?12:0),fill:ee?`${Fs[le]}22`:"transparent"}),e.jsx("rect",{x:z-(J?2:0),y:K-(J?2:0),rx:"22",ry:"22",width:ce+(J?4:0),height:E+(J?4:0),fill:fn[le],stroke:Fs[le],strokeWidth:ee?2.3:1.3}),$?e.jsx($,{x:V,y:D,width:je,height:je,color:_s[le],strokeWidth:2.1}):null,oe?e.jsx("text",{x:V+je+8,y:X,textAnchor:"start",fontSize:"9.5",fill:_s[le],style:{letterSpacing:"0.16em",textTransform:"uppercase",opacity:.82},children:oe}):null,ue.map((fe,Pe)=>e.jsx("text",{x:C.x,y:he+Pe*ye-(ue.length-1)*ye/2,textAnchor:"middle",fontSize:ze,fontWeight:600,fill:_s[le],children:fe},`${C.id}-${fe}-${Pe}`))]},C.id)})]})]})]})]})}const ro={intent:"trigger_report",linkedGoalId:"",linkedProjectId:"",linkedTaskId:""};function df({open:t,onOpenChange:s}){const i=ht(),n=Ye(),[a,r]=c.useState(ro),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:(o,x)=>e.jsx(tt,{columns:3,value:o.intent,onChange:f=>x({intent:f}),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:(o,x)=>e.jsx("div",{className:"grid gap-4",children:e.jsx(Y,{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(ke,{kind:"goal",label:"Goal",compact:!0,gradient:!1}),e.jsx(ke,{kind:"project",label:"Project",compact:!0,gradient:!1}),e.jsx(ke,{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:o.linkedGoalId,onChange:f=>x({linkedGoalId:f.target.value}),children:[e.jsx("option",{value:"",children:"No goal selected"}),n.snapshot.goals.map(f=>e.jsxs("option",{value:f.id,children:["Goal · ",f.title]},f.id))]}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:o.linkedProjectId,onChange:f=>x({linkedProjectId:f.target.value}),children:[e.jsx("option",{value:"",children:"No project selected"}),n.snapshot.dashboard.projects.map(f=>e.jsxs("option",{value:f.id,children:["Project · ",f.title]},f.id))]}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:o.linkedTaskId,onChange:f=>x({linkedTaskId:f.target.value}),children:[e.jsx("option",{value:"",children:"No task selected"}),n.snapshot.tasks.slice(0,40).map(f=>e.jsxs("option",{value:f.id,children:["Task · ",f.title]},f.id))]})]})})})}],d=async()=>{const o=new URLSearchParams({create:"1",intent:a.intent});switch(a.linkedGoalId&&o.set("goalId",a.linkedGoalId),a.linkedProjectId&&o.set("projectId",a.linkedProjectId),a.linkedTaskId&&o.set("taskId",a.linkedTaskId),a.intent){case"behavior":i(`/psyche/behaviors?${o.toString()}`);break;case"belief":i(`/psyche/schemas-beliefs?${o.toString()}`);break;case"pattern":i(`/psyche/patterns?${o.toString()}`);break;case"value":i(`/psyche/values?${o.toString()}`);break;case"execution_tension":case"trigger_report":default:i(`/psyche/reports?${o.toString()}`);break}s(!1),r(ro)};return e.jsx(it,{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:a,onChange:r,steps:l,submitLabel:"Open guided reflection",onSubmit:d})}function cf(){var p;const t=Ye(),[s,i]=ft(),[n,a]=c.useState(s.get("reflect")==="1"),[r,l]=c.useState(null),d=pe({queryKey:["forge-psyche-overview"],queryFn:Ba}),o=(p=d.data)==null?void 0:p.overview,x=c.useMemo(()=>o?t.snapshot.goals.slice(0,3).map(w=>{const v=o.values.filter(y=>y.linkedGoalIds.includes(w.id)),I=t.snapshot.dashboard.projects.filter(y=>y.goalId===w.id),k=t.snapshot.habits.filter(y=>y.linkedGoalIds.includes(w.id)||y.linkedValueIds.some(N=>v.some(A=>A.id===N))),S=o.reports.filter(y=>y.linkedGoalIds.includes(w.id)),M=o.behaviors.filter(y=>y.linkedValueIds.some(N=>v.some(A=>A.id===N))),P=o.beliefs.filter(y=>y.linkedValueIds.some(N=>v.some(A=>A.id===N)));return{goal:w,linkedValues:v,linkedProjects:I,linkedHabits:k,linkedReports:S,linkedBehaviors:M,linkedBeliefs:P}}):[],[o,t.snapshot.dashboard.projects,t.snapshot.goals,t.snapshot.habits]),f=c.useMemo(()=>Cc(x,{compact:!0}),[x]);if(c.useEffect(()=>{l(f.defaultSelectedId)},[f.defaultSelectedId]),d.isLoading)return e.jsx(It,{});if(d.isError||!o)return e.jsx(Oe,{eyebrow:"Psyche",error:d.error,onRetry:()=>void d.refetch()});const b=f.inspectors[r??f.defaultSelectedId]??f.inspectors[f.defaultSelectedId],m=o.patterns[0]??null,h=o.reports[0]??null;return e.jsxs("div",{className:"grid min-w-0 gap-4 overflow-x-clip",children:[e.jsx(Ke,{title:"Psyche",titleText:"Psyche",description:"See your goals, values, habits, beliefs, behaviors, projects, and reports together, then open the goal map when you want the full structure.",badge:`${o.domain.title} active`,actions:e.jsx(e.Fragment,{children:e.jsx(Le,{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"})})}),e.jsx(Ht,{}),e.jsxs("section",{className:"grid min-w-0 gap-4 xl:grid-cols-[minmax(0,1fr)_19rem]",children:[e.jsx(Tc,{testId:"psyche-hub-graph",compact:!0,title:"Reflective pulse and live entity field",hint:"This is the live field. Select any goal, value, habit, belief, behavior, project, or report, then open the full goal map when you want the wider structure.",nodes:f.nodes,edges:f.edges,fields:f.fields,selectedNodeId:r,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(Le,{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:()=>a(!0),children:"Reflect"})]})}),e.jsxs(se,{className:"h-fit min-w-0 xl:sticky xl:top-24",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:b.entityKind?e.jsx(ke,{kind:b.entityKind,compact:!0,gradient:!1,iconOnly:!0}):e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:b.eyebrow})}),e.jsx("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:b.entityKind?e.jsx(_e,{kind:b.entityKind,label:b.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:b.title})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/60",children:b.summary}),b.chips.length>0?e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:b.chips.map(w=>e.jsx(O,{className:"bg-white/[0.08] text-white/74",children:w},w))}):null,b.stats.length>0?e.jsx("div",{className:"mt-4 grid gap-2",children:b.stats.map(w=>e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/68",children:w},w))}):null,e.jsx("div",{className:"mt-5",children:e.jsx(Le,{to:b.href,className:re("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)]",b.entityKind?Ki(b.entityKind,!0):"bg-[linear-gradient(135deg,rgba(192,193,255,0.36),rgba(192,193,255,0.22))] text-white"),children:b.ctaLabel})})]})]}),e.jsxs("section",{className:"grid min-w-0 gap-4 lg:grid-cols-[minmax(0,1.05fr)_minmax(0,0.95fr)]",children:[e.jsxs(js,{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:(m==null?void 0:m.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:(m==null?void 0:m.targetBehavior)||"When the loop is explicit, the return path stops feeling abstract."})]}),e.jsxs(js,{to:h?`/psyche/reports/${h.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:o.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:o.openNotes})]})]}),e.jsx("div",{className:"mt-4 text-sm text-white/60",children:(h==null?void 0:h.title)||"Open the next chain and keep the report field live without adding more dashboard noise."})]})]}),e.jsx(df,{open:n,onOpenChange:w=>{a(w);const v=new URLSearchParams(s);v.delete("reflect"),i(v,{replace:!0})}})]})}function xs({eyebrow:t,title:s,description:i,titleHelp:n,tone:a="default",children:r,className:l}){const d={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:re("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",d[a],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}),n?e.jsx(Xe,{content:n,label:`Explain ${s.toLowerCase()}`,className:"mt-1 shrink-0"}):null]}),i?e.jsx("p",{className:"mt-3 max-w-3xl text-sm leading-7 text-white/60",children:i}):null,e.jsx("div",{className:"mt-5 min-w-0",children:r})]})}function mf({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(i=>e.jsxs(Le,{to:i.href,className:`rounded-[22px] border px-4 py-4 transition hover:-translate-y-0.5 ${s[i.tone]}`,children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:i.tone}),e.jsx("div",{className:"mt-2 font-medium text-white",children:i.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:i.summary}),e.jsxs("div",{className:"mt-4 inline-flex items-center gap-2 text-sm text-white/54",children:["Open",e.jsx(Gs,{className:"size-3.5"})]})]},i.id))})}const hf={maladaptive:"Maladaptive schema",adaptive:"Adaptive schema"},uf={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."},pf={disconnection_rejection:"Disconnection & rejection",impaired_autonomy:"Autonomy & competence",other_directedness:"Boundaries & mutuality",overvigilance_inhibition:"Standards & inhibition",healthy_selfhood:"Healthy selfhood"};function Ya(t){return hf[t]}function Wi(t){return uf[t]}function Sr(t){return pf[t]??t.replaceAll("_"," ")}function wi(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 lo(t){return t.trim().toLowerCase()}function Pc(t,s){const i=lo(s);return[t.id,t.slug,t.title].some(n=>lo(n)===i)}function vi(t,s){return s.find(i=>Pc(i,t))??null}function Mc(t,s){const i=t.filter(n=>!Pc(s,n));return i.length===t.length?[...i,s.id]:i}function Is({label:t,schemaType:s,compact:i=!1,showType:n=!1,className:a}){const r=wi(s);return e.jsxs("span",{className:re("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)]",i?"min-h-8":"min-h-9",r.badgeTone,a),children:[n?e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/58",children:Ya(s)}):null,e.jsx("span",{className:"min-w-0 break-words whitespace-normal",children:t})]})}function xf(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Vi(t){c.useEffect(()=>{if(!t||typeof document>"u")return;const s=window.requestAnimationFrame(()=>{const i=document.querySelector(`[data-psyche-focus-id="${xf(t)}"]`);i&&i.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"})});return()=>window.cancelAnimationFrame(s)},[t])}function Zi(t){return t?"border-[rgba(125,211,252,0.28)] bg-[linear-gradient(180deg,rgba(125,211,252,0.14),rgba(255,255,255,0.06))] shadow-[0_24px_60px_rgba(56,189,248,0.14)]":""}function jt(t,s,i,n){t.setQueryData(s,a=>{const r=(a==null?void 0:a[i])??[];return r.some(l=>l.id===n.id)?a:{...a??{},[i]:[n,...r]}})}const Re=ve().trim(),nt=Re.min(1),gf=Ae(nt).transform(t=>Array.from(new Set(t))),bs=ve().trim().min(1).nullable().optional(),oo=Ze({title:nt,description:Re,valuedDirection:nt,whyItMatters:Re,linkedGoalIds:Ae(ve()).default([]),linkedProjectIds:Ae(ve()).default([]),linkedTaskIds:Ae(ve()).default([]),committedActions:Ae(Re).default([]),userId:bs}),co=Ze({title:nt,description:Re,targetBehavior:nt,cueContexts:Ae(Re).default([]),shortTermPayoff:Re,longTermCost:Re,preferredResponse:nt,linkedValueIds:Ae(ve()).default([]),linkedSchemaLabels:gf.default([]),linkedModeIds:Ae(ve()).default([]),linkedBeliefIds:Ae(ve()).default([]),userId:bs}),mo=Ze({kind:ot(["away","committed","recovery"]),title:nt,description:Re,commonCues:Ae(Re).default([]),urgeStory:Re,shortTermPayoff:Re,longTermCost:Re,replacementMove:Re,repairPlan:Re,linkedPatternIds:Ae(ve()).default([]),linkedValueIds:Ae(ve()).default([]),linkedSchemaIds:Ae(ve()).default([]),linkedModeIds:Ae(ve()).default([]),userId:bs}),ho=Ze({schemaId:ve().nullable(),statement:nt,beliefType:ot(["absolute","conditional"]),originNote:Re,confidence:Jn().int().min(0).max(100),evidenceFor:Ae(Re).default([]),evidenceAgainst:Ae(Re).default([]),flexibleAlternative:Re,linkedValueIds:Ae(ve()).default([]),linkedBehaviorIds:Ae(ve()).default([]),linkedModeIds:Ae(ve()).default([]),linkedReportIds:Ae(ve()).default([]),userId:bs}),uo=Ze({family:ot(["coping","child","critic_parent","healthy_adult","happy_child"]),archetype:Re,title:nt,persona:Re,imagery:Re,symbolicForm:Re,facialExpression:Re,fear:Re,burden:Re,protectiveJob:Re,originContext:Re,firstAppearanceAt:ve().trim().nullable(),linkedPatternIds:Ae(ve()).default([]),linkedBehaviorIds:Ae(ve()).default([]),linkedValueIds:Ae(ve()).default([]),userId:bs}),bf=Ze({summary:nt,answers:Ae(Ze({questionKey:nt,value:nt})).min(1),userId:bs});Ze({label:nt,description:Re,userId:bs});Ze({label:nt,description:Re,category:Re,userId:bs});const ff=Ze({id:nt,emotionDefinitionId:ve().nullable(),label:nt,intensity:Jn().int().min(0).max(100),note:Re}),wf=Ze({id:nt,text:nt,parentMode:Re,criticMode:Re,beliefId:ve().nullable()}),vf=Ze({id:nt,text:nt,mode:Re,behaviorId:ve().nullable()}),yf=Ze({id:nt,stage:nt,modeId:ve().nullable(),label:nt,note:Re}),Bn=Ze({title:nt,status:ot(["draft","reviewed","integrated"]).default("draft"),eventTypeId:ve().nullable(),customEventType:Re,eventSituation:nt,occurredAt:ve().trim().nullable(),emotions:Ae(ff).default([]),thoughts:Ae(wf).default([]),behaviors:Ae(vf).default([]),consequences:Ze({selfShortTerm:Ae(Re).default([]),selfLongTerm:Ae(Re).default([]),othersShortTerm:Ae(Re).default([]),othersLongTerm:Ae(Re).default([])}),linkedPatternIds:Ae(ve()).default([]),linkedValueIds:Ae(ve()).default([]),linkedGoalIds:Ae(ve()).default([]),linkedProjectIds:Ae(ve()).default([]),linkedTaskIds:Ae(ve()).default([]),linkedBehaviorIds:Ae(ve()).default([]),linkedBeliefIds:Ae(ve()).default([]),linkedModeIds:Ae(ve()).default([]),modeOverlays:Ae(Re).default([]),schemaLinks:Ae(Re).default([]),modeTimeline:Ae(yf).default([]),nextMoves:Ae(Re).default([]),userId:bs}),Oi={kind:"away",title:"",description:"",commonCues:[],urgeStory:"",shortTermPayoff:"",longTermCost:"",replacementMove:"",repairPlan:"",linkedPatternIds:[],linkedValueIds:[],linkedSchemaIds:[],linkedModeIds:[],userId:null};function jf(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 po={away:"Away moves",committed:"Committed actions",recovery:"Recovery moves"};function Nf(){var U,R,C,J,ee,le,oe,ue,me,$,ce;const t=Ye(),s=We(),[i,n]=ft(),[a,r]=c.useState(!1),[l,d]=c.useState(null),[o,x]=c.useState(Oi),[f,b]=c.useState(null),m=pe({queryKey:["forge-psyche-behaviors"],queryFn:os}),h=pe({queryKey:["forge-psyche-patterns"],queryFn:Xs}),p=pe({queryKey:["forge-psyche-values"],queryFn:ls}),w=pe({queryKey:["forge-psyche-schema-catalog"],queryFn:Xi}),v=pe({queryKey:["forge-psyche-modes"],queryFn:Ls}),I=((U=m.data)==null?void 0:U.behaviors)??[],k=((R=h.data)==null?void 0:R.patterns)??[],S=((C=p.data)==null?void 0:C.values)??[],M=((J=w.data)==null?void 0:J.schemas)??[],P=((ee=v.data)==null?void 0:ee.modes)??[],y=Nt(t.selectedUserIds),N=i.get("focus"),A=t.snapshot.dashboard.notesSummaryByEntity;Vi(N),c.useEffect(()=>{if(i.get("create")==="1"){r(!0),d(null),x({...Oi,userId:y});const E=new URLSearchParams(i);E.delete("create"),n(E,{replace:!0})}},[y,i,n]);const T=ge({mutationFn:async E=>{const z=mo.parse(E);return l?zu(l.id,z):Ka(z)},onSuccess:async()=>{r(!1),d(null),x({...Oi,userId:y}),b(null),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-behaviors"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]})])}}),F=k.map(E=>({value:E.id,label:Je(E.title,E.user),description:Be(E.preferredResponse||E.targetBehavior,E.user),searchText:qe([E.title,E.preferredResponse,E.targetBehavior,E.description],E),kind:"pattern"})),u=S.map(E=>({value:E.id,label:Je(E.title,E.user),description:Be(E.valuedDirection,E.user),searchText:qe([E.title,E.valuedDirection,E.description],E),kind:"value"})),j=M.map(E=>({value:E.id,label:E.title,description:`${E.description} ${Sr(E.family)}`,searchText:`${E.slug} ${E.family} ${E.schemaType}`,badge:e.jsx(Is,{label:E.title,schemaType:E.schemaType,compact:!0}),menuBadge:e.jsx(Is,{label:E.title,schemaType:E.schemaType,compact:!0})})),L=P.map(E=>({value:E.id,label:Je(E.title,E.user),description:Be(E.archetype||E.family,E.user),searchText:qe([E.title,E.archetype,E.family,E.persona],E),kind:"mode"})),q=async E=>{const{pattern:z}=await dr({title:E,description:"",targetBehavior:E,cueContexts:[],shortTermPayoff:"",longTermCost:"",preferredResponse:"",linkedValueIds:[],linkedSchemaLabels:[],linkedModeIds:[],linkedBeliefIds:[],userId:o.userId});return jt(s,["forge-psyche-patterns"],"patterns",z),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:z.id,label:z.title,description:z.preferredResponse||z.targetBehavior,kind:"pattern"}},G=async E=>{const{value:z}=await Ii({title:E,description:"",valuedDirection:E,whyItMatters:"",linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],committedActions:[],userId:o.userId});return jt(s,["forge-psyche-values"],"values",z),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:z.id,label:z.title,description:z.valuedDirection,kind:"value"}},Q=async E=>{const{mode:z}=await Ji({family:"coping",archetype:"",title:E,persona:"",imagery:"",symbolicForm:"",facialExpression:"",fear:"",burden:"",protectiveJob:"",originContext:"",firstAppearanceAt:null,linkedPatternIds:[],linkedBehaviorIds:[],linkedValueIds:[],userId:o.userId});return jt(s,["forge-psyche-modes"],"modes",z),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:z.id,label:z.title,description:z.archetype||z.family,kind:"mode"}},ne=[{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:(E,z)=>e.jsxs(e.Fragment,{children:[e.jsx(is,{value:E.userId??null,users:t.snapshot.users,onChange:K=>z({userId:K}),defaultLabel:ss(t.snapshot.users.find(K=>K.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(Y,{label:"Behavior title",children:e.jsx(ie,{value:E.title,onChange:K=>z({title:K.target.value}),placeholder:"Scroll to numb the impact"})}),e.jsx(Y,{label:"What does the move look like?",children:e.jsx(Ce,{value:E.description,onChange:K=>z({description:K.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:(E,z)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Common cues",children:e.jsx(Ce,{value:E.commonCues.join(`
|
|
11
|
+
`),onChange:K=>z({commonCues:K.target.value.split(`
|
|
12
|
+
`).map(je=>je.trim()).filter(Boolean)}),placeholder:`One line per cue
|
|
13
|
+
Late-night ambiguity
|
|
14
|
+
Feedback after a hard week`})}),e.jsx(Y,{label:"What inner push or story shows up?",children:e.jsx(Ce,{value:E.urgeStory,onChange:K=>z({urgeStory:K.target.value}),placeholder:"What inner push or justification tends to appear?"})}),e.jsx(Y,{label:"What do you get right away from this move?",children:e.jsx(Ce,{value:E.shortTermPayoff,onChange:K=>z({shortTermPayoff:K.target.value}),placeholder:"What relief, certainty, distance, or control does it give in the short term?"})})]})},{id:"classification",eyebrow:"Classification",title:"Now classify the move and define the return path",description:"Once the move is clear, decide whether it is an away move, a committed action, or a recovery path.",render:(E,z)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Move type",children:e.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:["away","committed","recovery"].map(K=>e.jsx("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${E.kind===K?"border-white/20 bg-white/[0.12] text-white":"border-white/8 bg-white/[0.04] text-white/62 hover:bg-white/[0.07]"}`,onClick:()=>z({kind:K}),children:po[K]},K))})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Y,{label:"What does it cost over time?",children:e.jsx(Ce,{value:E.longTermCost,onChange:K=>z({longTermCost:K.target.value}),placeholder:"What does this move cost over time?"})}),e.jsx(Y,{label:"What move should replace or steady it?",children:e.jsx(Ce,{value:E.replacementMove,onChange:K=>z({replacementMove:K.target.value}),placeholder:"What move should replace this one when possible?"})})]}),e.jsx(Y,{label:"If the slip happens, how do you repair and return?",children:e.jsx(Ce,{value:E.repairPlan,onChange:K=>z({repairPlan:K.target.value}),placeholder:"Describe the repair path without shame or collapse."})})]})},{id:"links",eyebrow:"Links",title:"Attach the move to patterns, values, schemas, and modes",description:"This turns the move into part of the full graphical psyche system.",render:(E,z)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Linked patterns",children:e.jsx(st,{options:F,selectedValues:E.linkedPatternIds,onChange:K=>z({linkedPatternIds:K}),placeholder:"Search or create a pattern…",emptyMessage:"No patterns match yet.",createLabel:"Create pattern",onCreate:q})}),e.jsx(Y,{label:"Linked values",children:e.jsx(st,{options:u,selectedValues:E.linkedValueIds,onChange:K=>z({linkedValueIds:K}),placeholder:"Search or create a value…",emptyMessage:"No values match yet.",createLabel:"Create value",onCreate:G})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Y,{label:"Linked schemas",children:e.jsx(st,{options:j,selectedValues:E.linkedSchemaIds,onChange:K=>z({linkedSchemaIds:K}),placeholder:"Search schema themes…",emptyMessage:"No schema themes match."})}),e.jsx(Y,{label:"Linked modes",children:e.jsx(st,{options:L,selectedValues:E.linkedModeIds,onChange:K=>z({linkedModeIds:K}),placeholder:"Search or create a mode…",emptyMessage:"No modes match yet.",createLabel:"Create mode",onCreate:Q})})]})]})}];if(m.isLoading||h.isLoading||p.isLoading||w.isLoading||v.isLoading)return e.jsx(xt,{eyebrow:"Behaviors",title:"Loading behaviors",description:"Getting behaviors, patterns, values, schemas, and modes ready."});const H=m.error??h.error??p.error??w.error??v.error;if(H)return e.jsx(Oe,{eyebrow:"Psyche behaviors",error:H,onRetry:()=>void Promise.all([m.refetch(),h.refetch(),p.refetch(),w.refetch(),v.refetch()])});const _={away:I.filter(E=>E.kind==="away"),committed:I.filter(E=>E.kind==="committed"),recovery:I.filter(E=>E.kind==="recovery")};return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{entityKind:"behavior",title:e.jsx(_e,{kind:"behavior",label:"Behaviors",variant:"heading",size:"lg"}),description:"Group behaviors by what pulls you away, what moves you toward your values, and what helps you recover after a slip.",badge:`${I.length} mapped`,actions:e.jsx(W,{onClick:()=>{d(null),x({...Oi,userId:y}),r(!0)},children:"Add behavior"})}),e.jsx(Ht,{}),e.jsx(xs,{eyebrow:"Overview",title:"Behavior summary",description:"This summary keeps the three behavior types visible together: away, committed, and recovery.",tone:"amber",children:e.jsx(mf,{entries:[{id:"away",title:((le=_.away[0])==null?void 0:le.title)??"No away move mapped yet",summary:((oe=_.away[0])==null?void 0:oe.replacementMove)||"Map the move that tends to pull you away first.",href:"#behavior-columns",tone:"away"},{id:"committed",title:((ue=_.committed[0])==null?void 0:ue.title)??"No committed action mapped yet",summary:((me=_.committed[0])==null?void 0:me.replacementMove)||"Map the move you want to practice instead.",href:"#behavior-columns",tone:"committed"},{id:"recovery",title:(($=_.recovery[0])==null?void 0:$.title)??"No recovery move mapped yet",summary:((ce=_.recovery[0])==null?void 0:ce.repairPlan)||"Map how you return after a slip without turning it into collapse.",href:"#behavior-columns",tone:"recovery"}]})}),e.jsx(xs,{eyebrow:"Behaviors",title:"Behaviors by type",description:"Use these columns to separate what pulls you off course, what helps you move toward your values, and what helps you recover.",tone:"default",children:e.jsx("div",{id:"behavior-columns",className:"grid gap-4 xl:grid-cols-3",children:["away","committed","recovery"].map(E=>e.jsxs("div",{className:"grid gap-3 rounded-[24px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:po[E]}),e.jsx(O,{children:_[E].length})]}),_[E].length===0?e.jsx("div",{className:"flex",children:e.jsxs(W,{variant:"secondary",onClick:()=>{d(null),x({...Oi,userId:y}),r(!0)},children:["Add ",E==="away"?"away move":E==="committed"?"committed action":"recovery move"]})}):_[E].map(z=>e.jsxs("div",{"data-psyche-focus-id":z.id,className:`rounded-[22px] border border-white/8 bg-white/[0.04] p-4 text-left transition hover:bg-white/[0.08] ${Zi(N===z.id)}`,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"font-medium text-white",children:z.title}),z.user?e.jsx($e,{user:z.user,compact:!0}):null]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(yt,{entityType:"behavior",entityId:z.id,count:Tt(A,"behavior",z.id).count}),e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>{d(z),x(jf(z)),r(!0)},children:"Edit"})]})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:z.description}),e.jsx("div",{className:"mt-3 text-sm text-white/46",children:z.replacementMove||z.repairPlan||"No recovery step recorded yet."})]},z.id))]},E))})}),e.jsx(it,{open:a,onOpenChange:r,eyebrow:"Behavior",title:l?"Refine behavior path":"Create behavior",description:"Use this guided flow to describe the behavior, when it shows up, what it gives you, and what kind of move it is.",value:o,onChange:x,steps:ne,submitLabel:l?"Save behavior":"Create behavior",pending:T.isPending,error:f,onSubmit:async()=>{b(null);const E=mo.safeParse(o);if(!E.success){b("This behavior still needs a kind and a title before it can be saved.");return}try{await T.mutateAsync(E.data)}catch(z){b(z instanceof Error?z.message:"Unable to save this behavior right now.")}}})]})}function kf(){var o;const t=Ye(),[s,i]=c.useState(null),n=pe({queryKey:["forge-psyche-overview"],queryFn:Ba}),a=(o=n.data)==null?void 0:o.overview,r=c.useMemo(()=>a?t.snapshot.goals.map(x=>{const f=a.values.filter(v=>v.linkedGoalIds.includes(x.id)),b=t.snapshot.dashboard.projects.filter(v=>v.goalId===x.id),m=t.snapshot.habits.filter(v=>v.linkedGoalIds.includes(x.id)||v.linkedValueIds.some(I=>f.some(k=>k.id===I))),h=a.reports.filter(v=>v.linkedGoalIds.includes(x.id)),p=a.behaviors.filter(v=>v.linkedValueIds.some(I=>f.some(k=>k.id===I))),w=a.beliefs.filter(v=>v.linkedValueIds.some(I=>f.some(k=>k.id===I)));return{goal:x,linkedValues:f,linkedProjects:b,linkedHabits:m,linkedReports:h,linkedBehaviors:p,linkedBeliefs:w}}):[],[a,t.snapshot.dashboard.projects,t.snapshot.goals,t.snapshot.habits]),l=c.useMemo(()=>Cc(r),[r]);if(c.useEffect(()=>{i(l.defaultSelectedId)},[l.defaultSelectedId]),n.isLoading)return e.jsx(xt,{eyebrow:"Goal map",title:"Loading the gravity well",description:"Linking goals, values, reports, beliefs, behaviors, and projects back into execution."});if(n.isError||!a)return e.jsx(Oe,{eyebrow:"Goal map",error:n.error??new Error("Forge returned an empty Psyche overview payload."),onRetry:()=>void n.refetch()});const d=l.inspectors[s??l.defaultSelectedId]??l.inspectors[l.defaultSelectedId];return e.jsxs("div",{className:"grid min-w-0 gap-4",children:[e.jsx(Ke,{title:"Goal Map",titleText:"Goal Map",description:"Values orbit each goal. Habits, reports, beliefs, behaviors, and projects reveal where the orbit gets disrupted and how execution reconnects.",badge:`${r.length} goal${r.length===1?"":"s"}`,actions:e.jsxs(e.Fragment,{children:[e.jsx(Le,{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-2 text-sm whitespace-nowrap text-white transition hover:bg-white/[0.12]",children:"Open goals"}),e.jsx(Le,{to:"/psyche/reports?create=1",className:"inline-flex min-h-10 min-w-max shrink-0 items-center justify-center rounded-full bg-[rgba(125,211,252,0.16)] px-4 py-2 text-sm whitespace-nowrap text-white transition hover:bg-[rgba(125,211,252,0.22)]",children:"Reflect"})]})}),e.jsx(Ht,{}),e.jsxs("section",{className:"grid min-w-0 gap-4 xl:grid-cols-[minmax(0,1fr)_20rem]",children:[e.jsx(Tc,{testId:"goal-gravity-graph",title:"Life direction, value orbit, and execution field",hint:"Drag to inspect the whole field. Select any goal, value, belief, behavior, project, or report to see what it means and where to act next.",nodes:l.nodes,edges:l.edges,fields:l.fields,selectedNodeId:s,onSelectNode:i,minHeightClassName:"min-h-[25rem] sm:min-h-[34rem] lg:min-h-[56rem]",legend:[{label:"Goals",kind:"goal"},{label:"Values",kind:"value"},{label:"Beliefs",kind:"belief"},{label:"Behaviors",kind:"behavior"},{label:"Habits",kind:"habit"},{label:"Projects",kind:"project"},{label:"Reports",kind:"report"}],action:r.length===0?e.jsx(Le,{to:"/goals",className:"inline-flex min-h-10 min-w-max shrink-0 items-center justify-center rounded-[var(--radius-control)] bg-[linear-gradient(135deg,rgba(192,193,255,0.36),rgba(192,193,255,0.22))] px-4 py-2 text-sm font-medium whitespace-nowrap text-white",children:"Add first goal"}):e.jsx(Le,{to:"/goals",className:"inline-flex min-h-10 min-w-max shrink-0 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 goals"})}),e.jsxs(se,{className:"min-w-0 h-fit xl:sticky xl:top-24",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:d.entityKind?e.jsx(ke,{kind:d.entityKind,compact:!0,gradient:!1,iconOnly:!0}):e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:d.eyebrow})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[d.entityKind?e.jsx(_e,{kind:d.entityKind,label:d.title,variant:"heading",size:"lg",showKind:!1}):e.jsx("h2",{className:"font-display text-[clamp(1.35rem,2.2vw,2rem)] leading-none text-white",children:d.title}),d.entityKind?null:e.jsx(O,{className:"bg-white/[0.08]",style:{color:"white"},children:d.tone})]}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/60",children:d.summary}),d.stats.length>0?e.jsx("div",{className:"mt-4 grid gap-2",children:d.stats.map(x=>e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/68",children:x},x))}):null,d.chips.length>0?e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:d.chips.map(x=>e.jsx(O,{className:"bg-white/[0.08] text-white/74",children:x},x))}):null,e.jsx("div",{className:"mt-5",children:e.jsx(Le,{to:d.href,className:re("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)]",d.entityKind?Ki(d.entityKind,!0):"bg-[linear-gradient(135deg,rgba(192,193,255,0.36),rgba(192,193,255,0.22))] text-white"),children:d.ctaLabel})})]})]})]})}function Sf(t){return t instanceof Error?t:typeof t=="string"&&t.trim().length>0?new Error(t):new Error("Forge could not complete the requested query collection.")}function Cf(t){const s=t.find(i=>i.isError);return{isLoading:t.some(i=>i.isPending||i.isLoading),error:s?Sf(s.error):null}}async function If(t){await Promise.all(t.map(s=>s.refetch()))}const ga={copingResponse:[{value:"fight",label:"Fight"},{value:"flight",label:"Flight"},{value:"freeze",label:"Freeze"},{value:"detach",label:"Detach"},{value:"comply",label:"Comply"},{value:"overcompensate",label:"Overcompensate"},{value:"none",label:"Mixed / unsure"}],childState:[{value:"vulnerable",label:"Vulnerable"},{value:"angry",label:"Angry"},{value:"impulsive",label:"Impulsive"},{value:"lonely",label:"Lonely"},{value:"ashamed",label:"Ashamed"},{value:"none",label:"Mixed / unsure"}],criticStyle:[{value:"demanding",label:"Demanding"},{value:"punitive",label:"Punitive"},{value:"none",label:"Neither / unclear"}],healthyContact:[{value:"healthy_adult",label:"Healthy adult"},{value:"happy_child",label:"Happy child"},{value:"none",label:"Hard to access right now"}]};function Tf(){var d,o,x,f,b,m;const t=We(),s=pe({queryKey:["forge-psyche-mode-guide-sessions"],queryFn:Ku}),i=Ca({defaultValues:{summary:"What mode was most present in this moment?",copingResponse:"none",childState:"none",criticStyle:"none",healthyContact:"none"}}),n=ge({mutationFn:async h=>{const p=bf.parse({summary:h.summary,answers:[{questionKey:"coping_response",value:h.copingResponse},{questionKey:"child_state",value:h.childState},{questionKey:"critic_style",value:h.criticStyle},{questionKey:"healthy_contact",value:h.healthyContact}]});return Uu(p)},onSuccess:async()=>{await t.invalidateQueries({queryKey:["forge-psyche-mode-guide-sessions"]})}}),a=[s],r=Cf(a),l=((d=n.data)==null?void 0:d.session)??((x=(o=s.data)==null?void 0:o.sessions)==null?void 0:x[0]);return r.isLoading?e.jsx(xt,{eyebrow:"Mode guide",title:"Loading guided sessions",description:"Hydrating previous mode-guide runs and the latest stored readings."}):r.error?e.jsx(Oe,{eyebrow:"Mode guide",error:r.error,onRetry:()=>void If(a)}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{eyebrow:"Mode guide",title:"Guided Mode Identification",description:"A short guided pass can help separate coping responses, child states, critic pressure, and whatever healthy contact is still available.",badge:`${((f=s.data)==null?void 0:f.sessions.length)??0} sessions`,actions:e.jsx(Le,{to:"/psyche/modes",children:e.jsx(W,{variant:"secondary",children:"Back to mode map"})})}),e.jsx(Ht,{}),e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]",children:[e.jsxs(se,{className:"bg-[linear-gradient(180deg,rgba(16,20,30,0.96),rgba(11,15,24,0.94))]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Guided questionnaire"}),e.jsxs("form",{className:"mt-4 grid gap-5",onSubmit:i.handleSubmit(async h=>n.mutateAsync(h)),children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Prompt"}),e.jsx("input",{className:"w-full rounded-2xl border border-white/8 bg-white/6 px-4 py-3 text-sm text-white outline-none placeholder:text-white/35",...i.register("summary")})]}),e.jsxs(se,{className:"rounded-[24px] bg-[rgba(248,113,113,0.08)] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-rose-100/80",children:"When the pressure rose, what coping move dominated?"}),e.jsx("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:ga.copingResponse.map(h=>e.jsxs("label",{className:"flex items-center gap-3 rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("input",{type:"radio",value:h.value,...i.register("copingResponse")}),e.jsx("span",{className:"text-white/74",children:h.label})]},h.value))})]}),e.jsxs(se,{className:"rounded-[24px] bg-[rgba(196,181,253,0.08)] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-violet-100/80",children:"Which child state felt closest?"}),e.jsx("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:ga.childState.map(h=>e.jsxs("label",{className:"flex items-center gap-3 rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("input",{type:"radio",value:h.value,...i.register("childState")}),e.jsx("span",{className:"text-white/74",children:h.label})]},h.value))})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(se,{className:"rounded-[24px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/48",children:"What was the critic like?"}),e.jsx("div",{className:"mt-3 grid gap-2",children:ga.criticStyle.map(h=>e.jsxs("label",{className:"flex items-center gap-3 rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("input",{type:"radio",value:h.value,...i.register("criticStyle")}),e.jsx("span",{className:"text-white/74",children:h.label})]},h.value))})]}),e.jsxs(se,{className:"rounded-[24px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/48",children:"What healthy contact was still reachable?"}),e.jsx("div",{className:"mt-3 grid gap-2",children:ga.healthyContact.map(h=>e.jsxs("label",{className:"flex items-center gap-3 rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("input",{type:"radio",value:h.value,...i.register("healthyContact")}),e.jsx("span",{className:"text-white/74",children:h.label})]},h.value))})]})]}),e.jsx(W,{type:"submit",children:"Run guide"})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(se,{className:"bg-[linear-gradient(180deg,rgba(15,21,34,0.96),rgba(10,15,23,0.94))]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Latest reading"}),l?e.jsxs("div",{className:"mt-4 grid gap-3",children:[l.results.map(h=>e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:h.label}),e.jsxs(O,{className:"text-white/70",children:[Math.round(h.confidence*100),"%"]})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:h.family.replaceAll("_"," ")}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/66",children:h.reasoning})]},`${h.family}:${h.label}`)),e.jsx(Le,{to:"/psyche/modes",children:e.jsx(W,{variant:"secondary",children:"Use this in the mode map"})})]}):e.jsx("div",{className:"mt-4",children:e.jsx(gt,{eyebrow:"Guided reading",title:"No guided sessions yet",description:"Run the guide once to separate coping response, child state, critic pressure, and reachable healthy contact."})})]}),e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Session history"}),e.jsx("div",{className:"mt-4 grid gap-3",children:(((b=s.data)==null?void 0:b.sessions)??[]).length===0?e.jsx(gt,{eyebrow:"Session history",title:"No stored guide history",description:"Completed guide sessions will accumulate here so later mode-map work can build from real prior readings."}):(((m=s.data)==null?void 0:m.sessions)??[]).map(h=>e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:h.summary}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:h.results.map(p=>e.jsx(O,{className:"text-white/72",children:p.label},`${h.id}:${p.label}`))})]},h.id))})]})]})]})]})}const Pf={coping:"bg-[rgba(251,113,133,0.16)] text-rose-100",child:"bg-[rgba(125,211,252,0.16)] text-sky-100",critic_parent:"bg-[rgba(196,181,253,0.16)] text-violet-100",healthy_adult:"bg-[rgba(110,231,183,0.16)] text-emerald-100",happy_child:"bg-[rgba(251,191,36,0.16)] text-amber-100"};function Mf({family:t,label:s,className:i}){return e.jsx("span",{className:re("inline-flex items-center rounded-full px-3 py-1.5 text-xs",Pf[t],i),children:s})}const ei={family:"coping",archetype:"",title:"",persona:"",imagery:"",symbolicForm:"",facialExpression:"",fear:"",burden:"",protectiveJob:"",originContext:"",firstAppearanceAt:null,linkedPatternIds:[],linkedBehaviorIds:[],linkedValueIds:[],userId:null};function Ef(t){return{family:t.family,archetype:t.archetype,title:t.title,persona:t.persona,imagery:t.imagery,symbolicForm:t.symbolicForm,facialExpression:t.facialExpression,fear:t.fear,burden:t.burden,protectiveJob:t.protectiveJob,originContext:t.originContext,firstAppearanceAt:t.firstAppearanceAt,linkedPatternIds:t.linkedPatternIds,linkedBehaviorIds:t.linkedBehaviorIds,linkedValueIds:t.linkedValueIds,userId:t.userId??null}}const vn={coping:"Coping",child:"Child",critic_parent:"Critic / parent",healthy_adult:"Healthy adult",happy_child:"Happy child"};function Af(){var ne,H,_,U;const t=Ye(),s=We(),[i,n]=ft(),[a,r]=c.useState(!1),[l,d]=c.useState(null),[o,x]=c.useState(ei),[f,b]=c.useState(null),m=pe({queryKey:["forge-psyche-modes"],queryFn:Ls}),h=pe({queryKey:["forge-psyche-patterns"],queryFn:Xs}),p=pe({queryKey:["forge-psyche-behaviors"],queryFn:os}),w=pe({queryKey:["forge-psyche-values"],queryFn:ls}),v=((ne=m.data)==null?void 0:ne.modes)??[],I=((H=h.data)==null?void 0:H.patterns)??[],k=((_=p.data)==null?void 0:_.behaviors)??[],S=((U=w.data)==null?void 0:U.values)??[],M=Nt(t.selectedUserIds),P=i.get("focus"),y=t.snapshot.dashboard.notesSummaryByEntity;Vi(P),c.useEffect(()=>{if(i.get("create")==="1"){r(!0),d(null),x({...ei,userId:M});const R=new URLSearchParams(i);R.delete("create"),n(R,{replace:!0})}},[M,i,n]);const N=ge({mutationFn:async R=>{const C=uo.parse(R);return l?Bu(l.id,C):Ji(C)},onSuccess:async()=>{r(!1),d(null),x({...ei,userId:M}),b(null),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-modes"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]})])}}),A=I.map(R=>({value:R.id,label:Je(R.title,R.user),description:Be(R.preferredResponse||R.targetBehavior,R.user),searchText:qe([R.title,R.preferredResponse,R.targetBehavior,R.description],R),kind:"pattern"})),T=k.map(R=>({value:R.id,label:Je(R.title,R.user),description:Be(R.kind,R.user),searchText:qe([R.title,R.kind,R.description],R),kind:"behavior"})),F=S.map(R=>({value:R.id,label:Je(R.title,R.user),description:Be(R.valuedDirection,R.user),searchText:qe([R.title,R.valuedDirection,R.description],R),kind:"value"})),u=async R=>{const{pattern:C}=await dr({title:R,description:"",targetBehavior:R,cueContexts:[],shortTermPayoff:"",longTermCost:"",preferredResponse:"",linkedValueIds:[],linkedSchemaLabels:[],linkedModeIds:[],linkedBeliefIds:[],userId:o.userId});return jt(s,["forge-psyche-patterns"],"patterns",C),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:C.id,label:C.title,description:C.preferredResponse||C.targetBehavior,kind:"pattern"}},j=async R=>{const{behavior:C}=await Ka({kind:"away",title:R,description:"",commonCues:[],urgeStory:"",shortTermPayoff:"",longTermCost:"",replacementMove:"",repairPlan:"",linkedPatternIds:[],linkedValueIds:[],linkedSchemaIds:[],linkedModeIds:[],userId:o.userId});return jt(s,["forge-psyche-behaviors"],"behaviors",C),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:C.id,label:C.title,description:C.kind,kind:"behavior"}},L=async R=>{const{value:C}=await Ii({title:R,description:"",valuedDirection:R,whyItMatters:"",linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],committedActions:[],userId:o.userId});return jt(s,["forge-psyche-values"],"values",C),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:C.id,label:C.title,description:C.valuedDirection,kind:"value"}},q=[{id:"identity",eyebrow:"Identity",title:"Name the cast member and place it in the right family",description:"Start with the mode itself: who it feels like, what family it belongs to, and the recognizable role it plays.",render:(R,C)=>e.jsxs(e.Fragment,{children:[e.jsx(is,{value:R.userId??null,users:t.snapshot.users,onChange:J=>C({userId:J}),defaultLabel:ss(t.snapshot.users.find(J=>J.id===M)??null,"Choose mode owner"),help:"Modes can belong to a human or bot user while still linking across shared patterns, behaviors, and values."}),e.jsx(Y,{label:"Mode family",description:"Choose the broader inner family this mode belongs to.",labelHelp:"A mode family is the bigger cluster this state belongs to, like a coping part, a vulnerable child state, or a healthy adult response.",children:e.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:["coping","child","critic_parent","healthy_adult","happy_child"].map(J=>e.jsx("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${R.family===J?"border-white/20 bg-white/[0.12] text-white":"border-white/8 bg-white/[0.04] text-white/62 hover:bg-white/[0.07]"}`,onClick:()=>C({family:J}),children:vn[J]},J))})}),e.jsx(Y,{label:"Mode name",description:"Give it a memorable name you would instantly recognize later.",labelHelp:"This is the user-facing name of the mode. It should read like a cast member title, not a clinical record.",children:e.jsx(ie,{value:R.title,onChange:J=>C({title:J.target.value}),placeholder:"The Friday Vigil, The Scanner, The Good Son"})}),e.jsx(Y,{label:"Archetype",description:"Name the recognizable inner role or pattern this mode most resembles.",labelHelp:"An archetype is the role this mode tends to play, like a protector, a critic, a frightened child, or a calm adult anchor.",children:e.jsx(ie,{value:R.archetype,onChange:J=>C({archetype:J.target.value}),placeholder:"Detached protector, vulnerable child, demanding critic"})})]})},{id:"texture",eyebrow:"Texture",title:"Give the mode a recognizable presence",description:"Imagery, facial expression, and persona should make the mode instantly memorable.",render:(R,C)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Y,{label:"Persona",description:"Describe how this mode sounds, moves, and carries itself.",labelHelp:"Persona is the tone, posture, and voice of the mode. Imagine how it enters the room and how it speaks.",children:e.jsx(Ce,{value:R.persona,onChange:J=>C({persona:J.target.value}),placeholder:"Quiet, hyper-alert, always scanning for threat and trying to stay one step ahead."})}),e.jsx(Y,{label:"Imagery",description:"Capture the mental image or scene that helps this mode feel vivid.",labelHelp:"Imagery is the picture that makes the mode easy to remember, like a scene, posture, weather pattern, or atmosphere.",children:e.jsx(Ce,{value:R.imagery,onChange:J=>C({imagery:J.target.value}),placeholder:"A night watchman under cold fluorescent light, pacing and checking every door twice."})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Y,{label:"Symbolic form",description:"Pick the object, creature, or shape that best symbolizes this mode.",labelHelp:"Symbolic form is the metaphor for the mode, like armor, a fox, a storm front, or a glass wall.",children:e.jsx(ie,{value:R.symbolicForm,onChange:J=>C({symbolicForm:J.target.value}),placeholder:"A locked visor, a fox, a steel shield"})}),e.jsx(Y,{label:"Facial expression",description:"Describe what you would see on the mode's face if it took over.",labelHelp:"This is the visible emotional expression of the mode: tight jaw, blank stare, pleading eyes, or calm grounded attention.",children:e.jsx(ie,{value:R.facialExpression,onChange:J=>C({facialExpression:J.target.value}),placeholder:"Tight jaw, narrowed eyes, forced calm"})})]})]})},{id:"burden",eyebrow:"Burden",title:"Map fear, burden, job, and origin",description:"This is what turns a named mode into a readable inner-state profile.",render:(R,C)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Y,{label:"Fear",description:"Name the threat this mode is trying hard to prevent.",labelHelp:"Fear is the danger the mode believes it must protect you from, such as rejection, shame, collapse, failure, or being trapped.",children:e.jsx(Ce,{value:R.fear,onChange:J=>C({fear:J.target.value}),placeholder:"If I relax, I will miss the threat and get hurt."})}),e.jsx(Y,{label:"Burden",description:"Describe the emotional weight or exhausting role this mode keeps carrying.",labelHelp:"Burden is the heavy job or emotional load the mode feels stuck holding, even when it costs a lot.",children:e.jsx(Ce,{value:R.burden,onChange:J=>C({burden:J.target.value}),placeholder:"It believes it must never let the guard down, even when that means constant tension."})}),e.jsx(Y,{label:"Protective job",description:"Describe the job this mode thinks it is performing for you.",labelHelp:"Protective job is the function the mode is trying to serve, like preventing rejection, keeping control, stopping humiliation, or preserving closeness.",children:e.jsx(Ce,{value:R.protectiveJob,onChange:J=>C({protectiveJob:J.target.value}),placeholder:"Keeps me prepared so I never get blindsided or look naive."})})]}),e.jsx(Y,{label:"Origin context",description:"Describe when this mode first became useful or understandable.",labelHelp:"Origin context is the stretch of life where this mode likely learned its job or became especially necessary.",children:e.jsx(Ce,{value:R.originContext,onChange:J=>C({originContext:J.target.value}),placeholder:"Started getting stronger during adolescence when mistakes were met with criticism and unpredictability."})})]})},{id:"links",eyebrow:"Links",title:"Attach the mode to the rest of the psyche system",description:"Modes should connect to patterns, behaviors, and values, not sit in isolation.",render:(R,C)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Linked patterns",description:"Choose the loops this mode tends to activate or maintain.",children:e.jsx(st,{options:A,selectedValues:R.linkedPatternIds,onChange:J=>C({linkedPatternIds:J}),placeholder:"Search or create a pattern…",emptyMessage:"No patterns match yet.",createLabel:"Create pattern",onCreate:u})}),e.jsx(Y,{label:"Linked behaviors",description:"Choose the moves this mode tends to trigger, justify, or amplify.",children:e.jsx(st,{options:T,selectedValues:R.linkedBehaviorIds,onChange:J=>C({linkedBehaviorIds:J}),placeholder:"Search or create a behavior…",emptyMessage:"No behaviors match yet.",createLabel:"Create behavior",onCreate:j})}),e.jsx(Y,{label:"Colliding values",description:"Choose the valued directions this mode most often interrupts.",labelHelp:"These are the values that get obscured, sidelined, or distorted when this mode takes over.",children:e.jsx(st,{options:F,selectedValues:R.linkedValueIds,onChange:J=>C({linkedValueIds:J}),placeholder:"Search or create a value…",emptyMessage:"No values match yet.",createLabel:"Create value",onCreate:L})})]})}];if(m.isLoading||h.isLoading||p.isLoading||w.isLoading)return e.jsx(xt,{eyebrow:"Modes",title:"Loading modes",description:"Getting modes, linked patterns, behaviors, and values ready."});const G=m.error??h.error??p.error??w.error;if(G)return e.jsx(Oe,{eyebrow:"Modes",error:G,onRetry:()=>void Promise.all([m.refetch(),h.refetch(),p.refetch(),w.refetch()])});const Q={coping:v.filter(R=>R.family==="coping"),child:v.filter(R=>R.family==="child"),critic_parent:v.filter(R=>R.family==="critic_parent"),healthy_adult:v.filter(R=>R.family==="healthy_adult"),happy_child:v.filter(R=>R.family==="happy_child")};return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{entityKind:"mode",title:e.jsx(_e,{kind:"mode",label:"Modes",variant:"heading",size:"lg"}),description:"Modes should look and feel like a cast of inner states with identity, burden, and relational links, not a flat list of records.",badge:`${v.length} modes`,actions:e.jsx(W,{onClick:()=>{d(null),x({...ei,userId:M}),r(!0)},children:"Add mode"})}),e.jsx(Ht,{}),e.jsx(xs,{eyebrow:"Mode families",title:"Modes by family",description:"Use these groups to see which modes show up most often, what role they play, and what they are connected to.",tone:"violet",children:v.length===0?e.jsx("div",{className:"flex justify-start",children:e.jsx(W,{onClick:()=>{d(null),x({...ei,userId:M}),r(!0)},children:"Add mode"})}):e.jsx("div",{className:"grid gap-4 xl:grid-cols-2",children:Object.keys(Q).map(R=>e.jsxs("div",{className:"grid gap-3 rounded-[26px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(Mf,{family:R,label:vn[R]}),e.jsx(O,{children:Q[R].length})]}),Q[R].length===0?e.jsx("div",{className:"flex",children:e.jsxs(W,{variant:"secondary",onClick:()=>{d(null),x({...ei,userId:M}),r(!0)},children:["Add ",vn[R].toLowerCase()]})}):Q[R].map(C=>e.jsxs("div",{"data-psyche-focus-id":C.id,className:`rounded-[22px] bg-white/[0.04] p-4 text-left transition hover:bg-white/[0.08] ${Zi(P===C.id)}`,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(ke,{kind:"mode",compact:!0,gradient:!1}),e.jsx(_e,{kind:"mode",label:C.title,variant:"heading",size:"lg"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(yt,{entityType:"mode_profile",entityId:C.id,count:Tt(y,"mode_profile",C.id).count}),e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>{d(C),x(Ef(C)),r(!0)},children:"Edit"})]})]}),e.jsx("div",{className:"mt-2 text-sm text-white/52",children:C.archetype}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/62",children:C.persona||C.protectiveJob||"Open the mode to add persona and protective details."})]},C.id))]},R))})}),e.jsx(it,{open:a,onOpenChange:r,eyebrow:"Mode",title:l?"Refine cast member":"Create mode",description:"Use this guided flow to define the mode, how it shows up, what it is protecting, and where it comes from.",value:o,onChange:x,steps:q,submitLabel:l?"Save mode":"Create mode",pending:N.isPending,error:f,onSubmit:async()=>{b(null);const R=uo.safeParse(o);if(!R.success){b("This mode still needs a family and a name before it can be saved.");return}try{await N.mutateAsync(R.data)}catch(C){b(C instanceof Error?C.message:"Unable to save this mode right now.")}}})]})}const Lf={mint:"border-emerald-300/24 bg-[rgba(16,185,129,0.12)] text-emerald-100",sky:"border-sky-300/24 bg-[rgba(56,189,248,0.12)] text-sky-100",violet:"border-violet-300/24 bg-[rgba(167,139,250,0.12)] text-violet-100",rose:"border-rose-300/24 bg-[rgba(251,113,133,0.12)] text-rose-100"};function yn(t,s,i){return Math.min(Math.max(t,s),i)}function Df(t){const s=t.detail.trim().length;return s>84?130:s>44?118:106}function $f(t,s,i){const n=s/2,a=i/2,r=yn(Math.min(s/620,i/430),.64,1.06),l=t.map(m=>{const h=m.angle*Math.PI/180,p=m.radius*r,w=Math.min(184,Math.max(154,s-48)),v=Df(m),I=n+Math.cos(h)*p,k=a+Math.sin(h)*p;return{...m,x:I,y:k,width:w,height:v,homeX:I,homeY:k}}),d=s<720?16:22,o=20,x=s-20,f=18,b=i-18;for(let m=0;m<220;m+=1){for(const h of l)h.x+=(h.homeX-h.x)*.065,h.y+=(h.homeY-h.y)*.065;for(let h=0;h<l.length;h+=1)for(let p=h+1;p<l.length;p+=1){const w=l[h],v=l[p],I=v.x-w.x,k=v.y-w.y,S=w.width/2+v.width/2+d-Math.abs(I),M=w.height/2+v.height/2+d-Math.abs(k);if(S<=0||M<=0)continue;const P=S<M?"x":"y",y=Math.sign(P==="x"?I||p-h||1:k||p-h||1),N=(P==="x"?S:M)/2;P==="x"?(w.x-=y*N,v.x+=y*N):(w.y-=y*N,v.y+=y*N)}for(const h of l)h.x=yn(h.x,o+h.width/2,x-h.width/2),h.y=yn(h.y,f+h.height/2,b-h.height/2)}return l}function Ec({title:t,description:s,centerLabel:i,centerValue:n,nodes:a,action:r}){const l=c.useRef(null),[d,o]=c.useState({width:0,height:0});c.useEffect(()=>{if(!l.current||typeof ResizeObserver>"u")return;const b=new ResizeObserver(m=>{const h=m[0];o({width:h.contentRect.width,height:h.contentRect.height})});return b.observe(l.current),()=>b.disconnect()},[]);const x=a.length>0?a:[{id:"values",label:"Values",title:"Add value",detail:"Name what matters",href:"/psyche/values?create=1",angle:-86,radius:112,tone:"mint"},{id:"patterns",label:"Patterns",title:"Add pattern",detail:"Map a loop",href:"/psyche/patterns?create=1",angle:-14,radius:122,tone:"rose"},{id:"beliefs",label:"Beliefs",title:"Add belief",detail:"Capture a script",href:"/psyche/schemas-beliefs?create=1",angle:72,radius:118,tone:"violet"},{id:"reports",label:"Reports",title:"Reflect",detail:"Open the chain",href:"/psyche/reports?create=1",angle:160,radius:124,tone:"sky"}],f=c.useMemo(()=>$f(x,Math.max(d.width,320),Math.max(d.height,320)),[x,d.height,d.width]);return e.jsxs("section",{className:"overflow-hidden rounded-[32px] border border-white/8 bg-[radial-gradient(circle_at_top,rgba(110,231,183,0.14),transparent_42%),linear-gradient(180deg,rgba(15,30,34,0.98),rgba(10,21,25,0.98))] px-4 py-4 shadow-[0_24px_70px_rgba(4,8,18,0.28)] lg:px-5",children:[e.jsxs("div",{className:"mb-4 flex flex-wrap items-end 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-[rgba(110,231,183,0.8)]",children:"Reflective map"}),e.jsx("h2",{className:"mt-2 font-display text-[clamp(1.35rem,2.3vw,2rem)] leading-none text-white",children:t}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-white/60",children:s})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"inline-flex items-center gap-3 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2",children:[e.jsx("span",{className:"text-xs uppercase tracking-[0.18em] text-white/38",children:i}),e.jsx("span",{className:"text-sm font-medium text-white",children:n})]}),r?e.jsx("div",{className:"shrink-0",children:r}):null]})]}),e.jsxs("div",{ref:l,className:"relative min-h-[20rem] overflow-hidden rounded-[30px] border border-white/6 bg-[radial-gradient(circle_at_center,rgba(255,255,255,0.05),transparent_42%)] lg:min-h-[22rem]",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_center,rgba(110,231,183,0.08),transparent_32%),linear-gradient(180deg,transparent,rgba(8,13,24,0.24))]"}),[112,168,224].map(b=>e.jsx("div",{className:"absolute left-1/2 top-1/2 rounded-full border border-white/[0.05]",style:{width:`${b*2}px`,height:`${b*2}px`,transform:"translate(-50%, -50%)"}},b)),e.jsx("div",{className:"absolute inset-1/2 size-32 -translate-x-1/2 -translate-y-1/2 rounded-full border border-white/10 bg-[radial-gradient(circle,rgba(255,255,255,0.08),rgba(255,255,255,0.02))] shadow-[0_0_0_18px_rgba(255,255,255,0.02),0_0_0_56px_rgba(255,255,255,0.015)]",children:e.jsxs("div",{className:"flex h-full flex-col items-center justify-center text-center",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:i}),e.jsx("div",{className:"mt-2 font-display text-2xl text-white",children:n})]})}),f.map((b,m)=>e.jsx(wt.div,{initial:{opacity:0,scale:.96},animate:{opacity:1,scale:1},transition:{duration:.35,delay:m*.05,ease:"easeOut"},className:"absolute w-[min(11.5rem,calc(100vw-4rem))] max-w-[11.5rem] -translate-x-1/2 -translate-y-1/2",style:{left:`${b.x}px`,top:`${b.y}px`},whileHover:{y:-6,scale:1.03},children:e.jsxs(Le,{to:b.href,className:re("block rounded-[22px] border px-3.5 py-3 shadow-[0_18px_38px_rgba(4,8,18,0.28)] backdrop-blur-sm transition hover:-translate-y-0.5 hover:bg-white/[0.1] hover:shadow-[0_24px_44px_rgba(4,8,18,0.34)]",Lf[b.tone??"mint"]),children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/45",children:b.label}),e.jsx("div",{className:"mt-1.5 font-medium text-white",children:b.title}),e.jsx("div",{className:"mt-1.5 text-sm leading-5 text-white/62",children:b.detail})]})},b.id))]})]})}const ti={title:"",description:"",targetBehavior:"",cueContexts:[],shortTermPayoff:"",longTermCost:"",preferredResponse:"",linkedValueIds:[],linkedSchemaLabels:[],linkedModeIds:[],linkedBeliefIds:[],userId:null};function Of(t){return{title:t.title,description:t.description,targetBehavior:t.targetBehavior,cueContexts:t.cueContexts,shortTermPayoff:t.shortTermPayoff,longTermCost:t.longTermCost,preferredResponse:t.preferredResponse,linkedValueIds:t.linkedValueIds,linkedSchemaLabels:t.linkedSchemaLabels,linkedModeIds:t.linkedModeIds,linkedBeliefIds:t.linkedBeliefIds,userId:t.userId??null}}function Ff(){var J,ee,le,oe,ue,me;const t=Ye(),s=We(),[i,n]=ft(),[a,r]=c.useState(!1),[l,d]=c.useState(null),[o,x]=c.useState(ti),[f,b]=c.useState(null),m=pe({queryKey:["forge-psyche-patterns"],queryFn:Xs}),h=pe({queryKey:["forge-psyche-values"],queryFn:ls}),p=pe({queryKey:["forge-psyche-schema-catalog"],queryFn:Xi}),w=pe({queryKey:["forge-psyche-modes"],queryFn:Ls}),v=pe({queryKey:["forge-psyche-beliefs"],queryFn:As}),I=pe({queryKey:["forge-psyche-behaviors"],queryFn:os}),k=((J=m.data)==null?void 0:J.patterns)??[],S=((ee=h.data)==null?void 0:ee.values)??[],M=((le=p.data)==null?void 0:le.schemas)??[],P=((oe=w.data)==null?void 0:oe.modes)??[],y=((ue=v.data)==null?void 0:ue.beliefs)??[],N=((me=I.data)==null?void 0:me.behaviors)??[],A=Nt(t.selectedUserIds),T=i.get("focus"),F=t.snapshot.dashboard.notesSummaryByEntity;Vi(T),c.useEffect(()=>{if(i.get("create")==="1"){r(!0),d(null),x({...ti,userId:A});const $=new URLSearchParams(i);$.delete("create"),n($,{replace:!0})}},[A,i,n]);const u=ge({mutationFn:async $=>{const ce=co.parse($);return l?Ru(l.id,ce):dr(ce)},onSuccess:async()=>{r(!1),d(null),x({...ti,userId:A}),b(null),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-patterns"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]})])}}),j=S.map($=>({value:$.id,label:Je($.title,$.user),description:Be($.valuedDirection,$.user),searchText:qe([$.title,$.valuedDirection,$.description],$),kind:"value"})),L=M.map($=>({value:$.title,label:$.title,description:`${$.description} ${Sr($.family)}`,searchText:`${$.slug} ${$.family} ${$.schemaType}`,badge:e.jsx(Is,{label:$.title,schemaType:$.schemaType,compact:!0}),menuBadge:e.jsx(Is,{label:$.title,schemaType:$.schemaType,compact:!0})})),q=P.map($=>({value:$.id,label:Je($.title,$.user),description:Be($.archetype||$.family,$.user),searchText:qe([$.title,$.archetype,$.family,$.persona],$),kind:"mode"})),G=y.map($=>({value:$.id,label:Je($.statement,$.user),description:Be($.flexibleAlternative||$.originNote,$.user),searchText:qe([$.statement,$.flexibleAlternative,$.originNote,$.beliefType],$),kind:"belief"})),Q=async $=>{const{mode:ce}=await Ji({family:"coping",archetype:"",title:$,persona:"",imagery:"",symbolicForm:"",facialExpression:"",fear:"",burden:"",protectiveJob:"",originContext:"",firstAppearanceAt:null,linkedPatternIds:[],linkedBehaviorIds:[],linkedValueIds:[],userId:o.userId});return jt(s,["forge-psyche-modes"],"modes",ce),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:ce.id,label:ce.title,description:ce.archetype||ce.family,kind:"mode"}},ne=async $=>{const{value:ce}=await Ii({title:$,description:"",valuedDirection:$,whyItMatters:"",linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],committedActions:[],userId:o.userId});return jt(s,["forge-psyche-values"],"values",ce),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:ce.id,label:ce.title,description:ce.valuedDirection,kind:"value"}},H=async $=>{const{belief:ce}=await cr({schemaId:null,statement:$,beliefType:"absolute",originNote:"",confidence:60,evidenceFor:[],evidenceAgainst:[],flexibleAlternative:"",linkedValueIds:[],linkedBehaviorIds:[],linkedModeIds:[],linkedReportIds:[],userId:o.userId});return jt(s,["forge-psyche-beliefs"],"beliefs",ce),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:ce.id,label:ce.statement,description:ce.flexibleAlternative||ce.originNote,kind:"belief"}},_=c.useMemo(()=>k.filter($=>!N.some(ce=>ce.kind==="away"&&ce.linkedPatternIds.includes($.id))),[k,N]),U=k.slice(0,5).map(($,ce)=>({id:$.id,label:`${$.linkedValueIds.length} values`,title:$.title,detail:$.preferredResponse,href:`/psyche/patterns?focus=${$.id}#pattern-lanes`,angle:-92+ce*70,radius:150+ce%2*14,tone:["rose","sky","violet","mint"][ce%4]})),R=[{id:"loop",eyebrow:"Loop",title:"Name the pattern and the behavior it keeps producing",description:"This should feel like a recognizable loop, not a diagnostic label.",render:($,ce)=>e.jsxs(e.Fragment,{children:[e.jsx(is,{value:$.userId??null,users:t.snapshot.users,onChange:E=>ce({userId:E}),defaultLabel:ss(t.snapshot.users.find(E=>E.id===A)??null,"Choose pattern owner"),help:"Patterns can belong to a human or bot user even when linked values, modes, or beliefs cross owners."}),e.jsx(Y,{label:"Pattern name",description:"Give the loop a name you will recognize quickly later.",children:e.jsx(ie,{value:$.title,onChange:E=>ce({title:E.target.value}),placeholder:"Anxious reassurance loop"})}),e.jsx(Y,{label:"What happens in the loop",description:"Describe the actual sequence of behavior, not the diagnosis.",children:e.jsx(Ce,{value:$.targetBehavior,onChange:E=>ce({targetBehavior:E.target.value}),placeholder:"What do you actually do when the trigger hits?"})}),e.jsx(Y,{label:"Description",description:"Write the loop in plain language so it stays usable in the future.",children:e.jsx(Ce,{value:$.description,onChange:E=>ce({description:E.target.value}),placeholder:"Describe the loop in plain human language so it stays recognizable later."})})]})},{id:"dynamics",eyebrow:"Dynamics",title:"Capture cues, payoff, cost, and the desired response",description:"The goal is to make the action map obvious at a glance.",render:($,ce)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Common cues",description:"Add one cue per line so the trigger pattern stays easy to scan.",children:e.jsx(Ce,{value:$.cueContexts.join(`
|
|
15
|
+
`),onChange:E=>ce({cueContexts:E.target.value.split(`
|
|
16
|
+
`).map(z=>z.trim()).filter(Boolean)}),placeholder:`One line per cue
|
|
17
|
+
Silence after vulnerability
|
|
18
|
+
Late-night social comparison`})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Y,{label:"Short-term payoff",description:"What relief, certainty, control, or distance do you get right away?",children:e.jsx(Ce,{value:$.shortTermPayoff,onChange:E=>ce({shortTermPayoff:E.target.value}),placeholder:"What relief do you get right away?"})}),e.jsx(Y,{label:"Long-term cost",description:"What does the loop cost you later in closeness, energy, values, or progress?",children:e.jsx(Ce,{value:$.longTermCost,onChange:E=>ce({longTermCost:E.target.value}),placeholder:"What does this cost over time?"})})]}),e.jsx(Y,{label:"Preferred response",description:"Name the return-path response you want to practice instead.",children:e.jsx(Ce,{value:$.preferredResponse,onChange:E=>ce({preferredResponse:E.target.value}),placeholder:"What do you want to practice instead?"})})]})},{id:"links",eyebrow:"Links",title:"Attach the loop to values, schemas, modes, and beliefs",description:"This is what turns a private note into a navigable graphical system.",render:($,ce)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Linked values",description:"Choose the values this loop pulls against or tries to protect badly.",children:e.jsx(st,{options:j,selectedValues:$.linkedValueIds,onChange:E=>ce({linkedValueIds:E}),placeholder:"Search or create a value…",emptyMessage:"No values match yet.",createLabel:"Create value",onCreate:ne})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Y,{label:"Schema labels",description:"Attach the schema themes that define the pressure in this loop.",children:e.jsx(st,{options:L,selectedValues:$.linkedSchemaLabels,onChange:E=>ce({linkedSchemaLabels:E}),placeholder:"Search schema themes…",emptyMessage:"No schema themes match."})}),e.jsx(Y,{label:"Linked modes",description:"Search for an existing mode or press Enter to create and link one immediately.",children:e.jsx(st,{options:q,selectedValues:$.linkedModeIds,onChange:E=>ce({linkedModeIds:E}),placeholder:"Search or create a mode…",emptyMessage:"No modes match yet.",createLabel:"Create mode",onCreate:Q})})]}),e.jsx(Y,{label:"Linked beliefs",description:"Search for a belief, or type a new one and press Enter to create it inline.",children:e.jsx(st,{options:G,selectedValues:$.linkedBeliefIds,onChange:E=>ce({linkedBeliefIds:E}),placeholder:"Search or create a belief…",emptyMessage:"No beliefs match yet.",createLabel:"Create belief",onCreate:H})})]})}];if(m.isLoading||h.isLoading||p.isLoading||w.isLoading||v.isLoading||I.isLoading)return e.jsx(xt,{eyebrow:"Patterns",title:"Loading patterns",description:"Getting patterns, values, schemas, beliefs, modes, and linked behaviors ready."});const C=m.error??h.error??p.error??w.error??v.error??I.error;return C?e.jsx(Oe,{eyebrow:"Psyche patterns",error:C,onRetry:()=>void Promise.all([m.refetch(),h.refetch(),p.refetch(),w.refetch(),v.refetch(),I.refetch()])}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{entityKind:"pattern",title:e.jsx(_e,{kind:"pattern",label:"Patterns",variant:"heading",size:"lg"}),description:"See each pattern as a loop: what starts it, what payoff it gives, what it costs, and what you want to do instead.",badge:`${k.length} patterns`,actions:e.jsx(W,{onClick:()=>{d(null),x({...ti,userId:A}),r(!0)},children:"Add pattern"})}),e.jsx(Ht,{}),e.jsx(Ec,{title:"See the loops that keep pulling against your values",description:"This map shows which patterns are hot, what they are connected to, and which response wants to replace them.",centerLabel:"Pattern field",centerValue:`${k.length} tracked`,nodes:U,action:e.jsx(W,{onClick:()=>{d(null),x({...ti,userId:A}),r(!0)},children:"Add pattern"})}),_.length>0?e.jsx(xs,{eyebrow:"Seed behavior drafts",title:"Some patterns still do not have an explicit away-move draft",description:"These are the best candidates to push into the Behaviors page next.",tone:"rose",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:_.slice(0,8).map($=>e.jsx(ke,{kind:"pattern",label:$.title,compact:!0},$.id))})}):null,e.jsx(xs,{eyebrow:"Pattern action map",title:"Read each loop from cue to return path",description:"Each lane turns a raw pattern into a visible behavior map: cues, short-term relief, long-term cost, and the move you actually want.",tone:"sky",className:"scroll-mt-24",children:e.jsx("div",{id:"pattern-lanes",className:"grid gap-4",children:k.length===0?e.jsx("div",{className:"flex justify-start",children:e.jsx(W,{onClick:()=>{d(null),x({...ti,userId:A}),r(!0)},children:"Add pattern"})}):k.map($=>{const ce=S.filter(V=>$.linkedValueIds.includes(V.id)),E=P.filter(V=>$.linkedModeIds.includes(V.id)),z=y.filter(V=>$.linkedBeliefIds.includes(V.id)),K=T===$.id,je=Tt(F,"behavior_pattern",$.id).count;return e.jsxs("div",{"data-psyche-focus-id":$.id,className:`rounded-[28px] border border-white/8 bg-white/[0.04] p-5 transition ${Zi(K)}`,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(_e,{kind:"pattern",label:$.title,variant:"heading",size:"xl"}),e.jsx("div",{className:"mt-2 text-sm leading-7 text-white/58",children:$.description})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[$.user?e.jsx($e,{user:$.user,compact:!0}):null,e.jsx(yt,{entityType:"behavior_pattern",entityId:$.id,count:je}),e.jsx(W,{variant:"secondary",onClick:()=>{d($),x(Of($)),r(!0)},children:"Edit"})]})]}),e.jsxs("div",{className:"mt-5 grid gap-3 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Cue"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/68",children:$.cueContexts[0]??"No cue captured yet."})]}),e.jsxs("div",{className:"rounded-[22px] bg-[rgba(251,113,133,0.08)] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Loop"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/68",children:$.targetBehavior})]}),e.jsxs("div",{className:"rounded-[22px] bg-[rgba(251,191,36,0.08)] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Short-term relief / long-term cost"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/68",children:$.shortTermPayoff||"No payoff note yet."}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/52",children:$.longTermCost||"No long-term cost note yet."})]}),e.jsxs("div",{className:"rounded-[22px] bg-[rgba(110,231,183,0.08)] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Return path"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/68",children:$.preferredResponse})]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[ce.map(V=>e.jsx(ke,{kind:"value",label:V.title,compact:!0},V.id)),E.map(V=>e.jsx(ke,{kind:"mode",label:V.title,compact:!0},V.id)),$.linkedModeLabels.map(V=>e.jsx(O,{className:"text-violet-100",children:V},`legacy-${V}`)),$.linkedSchemaLabels.map(V=>{var D,X;return e.jsx(Is,{label:((D=vi(V,M))==null?void 0:D.title)??V,schemaType:((X=vi(V,M))==null?void 0:X.schemaType)??"maladaptive",compact:!0},V)}),z.map(V=>e.jsx(ke,{kind:"belief",label:V.statement,compact:!0},V.id))]})]},$.id)})})}),e.jsx(it,{open:a,onOpenChange:r,eyebrow:"Behavior pattern",title:l?"Refine pattern lane":"Create pattern",description:"Pattern capture should feel like mapping a loop, not filling an admin form.",value:o,onChange:x,steps:R,submitLabel:l?"Save pattern":"Create pattern",pending:u.isPending,error:f,onSubmit:async()=>{b(null);const $=co.safeParse(o);if(!$.success){b("This pattern still needs a title, a loop description, and a preferred response.");return}try{await u.mutateAsync($.data)}catch(ce){b(ce instanceof Error?ce.message:"Unable to save this pattern right now.")}}})]})}const xo="(max-width: 1023px)";function _f(){const[t,s]=c.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(xo).matches);return c.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const i=window.matchMedia(xo),n=a=>s(a.matches);return s(i.matches),typeof i.addEventListener=="function"?(i.addEventListener("change",n),()=>i.removeEventListener("change",n)):(i.addListener(n),()=>i.removeListener(n))},[]),t}function Rf({stages:t,activeStageId:s,onStageChange:i,stageContent:n,inspector:a}){const r=_f(),[l,d]=c.useState(!1),o=t.find(x=>x.id===s);return c.useEffect(()=>{d(!r)},[r]),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1fr)_18rem]",children:[e.jsxs("div",{className:"rounded-[30px] border border-white/8 bg-[radial-gradient(circle_at_top,rgba(196,181,253,0.12),transparent_38%),linear-gradient(180deg,rgba(21,20,38,0.98),rgba(10,12,22,0.96))] p-4",children:[e.jsxs("div",{className:"mb-4 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/38",children:"Tracing the chain"}),e.jsx("div",{className:"mt-1 text-sm text-white/58",children:o==null?void 0:o.summary})]}),a?e.jsxs(W,{variant:"secondary",size:"sm",onClick:()=>d(x=>!x),children:[l?e.jsx(Xm,{className:"size-4"}):e.jsx(Jm,{className:"size-4"}),"Inspector"]}):null]}),e.jsx("div",{className:"mb-4 overflow-x-auto pb-1",children:e.jsx("div",{className:"flex min-w-max items-center gap-3",children:t.map((x,f)=>e.jsxs("button",{type:"button",className:re("rounded-[22px] px-4 py-3 text-left transition",x.id===s?"bg-[rgba(196,181,253,0.18)] text-white shadow-[0_18px_40px_rgba(15,12,28,0.28)]":"bg-white/[0.04] text-white/58 hover:bg-white/[0.07] hover:text-white"),onClick:()=>i(x.id),children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/34",children:[f+1,". ",x.label]}),r?null:e.jsx("div",{className:"mt-1.5 text-sm leading-5",children:x.summary})]},x.id))})}),e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(255,255,255,0.04),rgba(255,255,255,0.02))] p-4 md:p-5",children:[e.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"rounded-full bg-white/[0.07] px-3 py-1.5 text-[11px] uppercase tracking-[0.18em] text-white/42",children:o==null?void 0:o.label}),e.jsx("span",{className:"text-sm text-white/54",children:o==null?void 0:o.summary})]}),e.jsx(Ta,{mode:"wait",children:e.jsx(wt.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},exit:{opacity:0,y:-14},transition:{duration:.26,ease:"easeOut"},children:n},s)})]})]}),a?e.jsx(Ta,{initial:!1,children:l?e.jsxs(wt.div,{initial:{opacity:0,x:16},animate:{opacity:1,x:0},exit:{opacity:0,x:16},transition:{duration:.22,ease:"easeOut"},className:"rounded-[26px] border border-white/8 bg-[linear-gradient(180deg,rgba(17,24,35,0.96),rgba(11,16,24,0.94))] p-3.5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Linked inspectors"}),e.jsx("div",{className:"mt-3 grid gap-3",children:a})]}):null}):null]})}function Va(t){return`${t}_${Math.random().toString(36).slice(2,10)}`}function zf(){return{id:Va("emotion"),emotionDefinitionId:null,label:"",intensity:55,note:""}}function qf(){return{id:Va("thought"),text:"",parentMode:"",criticMode:"",beliefId:null}}function Bf(){return{id:Va("behavior"),text:"",mode:"",behaviorId:null}}function Kf(){return{id:Va("timeline"),stage:"",modeId:null,label:"",note:""}}function ea({title:t,description:s,onAdd:i,addLabel:n}){return e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-base font-medium text-white",children:t}),e.jsx("div",{className:"mt-1 text-sm leading-6 text-white/56",children:s})]}),e.jsxs(W,{type:"button",variant:"secondary",size:"sm",onClick:i,children:[e.jsx(Wt,{className:"size-4"}),n]})]})}function ta({onClick:t}){return e.jsx("button",{type:"button",className:"rounded-full bg-white/[0.06] p-2 text-white/55 transition hover:bg-white/[0.12] hover:text-white",onClick:t,"aria-label":"Remove row",children:e.jsx(mt,{className:"size-4"})})}function as({title:t,description:s,addLabel:i,items:n,onChange:a,placeholder:r}){return e.jsxs("div",{className:"grid gap-3",children:[e.jsx(ea,{title:t,description:s,addLabel:i,onAdd:()=>a([...n,""])}),e.jsx("div",{className:"grid gap-3",children:n.map((l,d)=>e.jsxs("div",{className:"flex items-start gap-3 rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx(ie,{value:l,onChange:o=>a(n.map((x,f)=>f===d?o.target.value:x)),placeholder:r}),e.jsx(ta,{onClick:()=>a(n.filter((o,x)=>x!==d))})]},`${t}-${d}`))})]})}function Ac({items:t,onChange:s,definitions:i}){return e.jsxs("div",{className:"grid gap-3",children:[e.jsx(ea,{title:"What emotions were present?",description:"Add one emotion at a time, set the intensity, and note what stood out.",addLabel:"Add emotion",onAdd:()=>s([...t,zf()])}),e.jsx("div",{className:"grid gap-3",children:t.map(n=>e.jsxs("div",{className:"grid gap-4 rounded-[24px] border 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",{className:"grid flex-1 gap-4 md:grid-cols-[minmax(0,1fr)_9rem]",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"Emotion"}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:n.emotionDefinitionId??"",onChange:a=>{const r=i.find(l=>l.id===a.target.value);s(t.map(l=>l.id===n.id?{...l,emotionDefinitionId:a.target.value||null,label:(r==null?void 0:r.label)??l.label}:l))},children:[e.jsx("option",{value:"",children:"Choose or type your own"}),i.map(a=>e.jsx("option",{value:a.id,children:a.label},a.id))]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"Intensity"}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("input",{type:"range",min:0,max:100,value:n.intensity,onChange:a=>s(t.map(r=>r.id===n.id?{...r,intensity:Number(a.target.value)}:r))}),e.jsxs("div",{className:"mt-2 text-sm text-white/52",children:[n.intensity,"%"]})]})]})]}),e.jsx(ta,{onClick:()=>s(t.filter(a=>a.id!==n.id))})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"If the preset is not right, how would you name it?"}),e.jsx(ie,{value:n.label,onChange:a=>s(t.map(r=>r.id===n.id?{...r,label:a.target.value}:r)),placeholder:"Tight sadness, panic, shame, relief..."})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"What was notable about this emotion?"}),e.jsx(Ce,{value:n.note,onChange:a=>s(t.map(r=>r.id===n.id?{...r,note:a.target.value}:r)),placeholder:"Short note about what made this emotion stand out."})]})]},n.id))})]})}function Lc({items:t,onChange:s,beliefs:i,modes:n}){return e.jsxs("div",{className:"grid gap-3",children:[e.jsx(ea,{title:"What did your mind start saying?",description:"Capture the thought itself first, then optionally link a belief or mode influence.",addLabel:"Add thought",onAdd:()=>s([...t,qf()])}),e.jsx("div",{className:"grid gap-3",children:t.map(a=>e.jsxs("div",{className:"grid gap-4 rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("label",{className:"grid flex-1 gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"Thought"}),e.jsx(Ce,{value:a.text,onChange:r=>s(t.map(l=>l.id===a.id?{...l,text:r.target.value}:l)),placeholder:"What sentence, image, or conclusion showed up?"})]}),e.jsx(ta,{onClick:()=>s(t.filter(r=>r.id!==a.id))})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"Parent mode influence"}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:a.parentMode,onChange:r=>s(t.map(l=>l.id===a.id?{...l,parentMode:r.target.value}:l)),children:[e.jsx("option",{value:"",children:"None"}),n.map(r=>e.jsx("option",{value:r.title,children:r.title},r.id))]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"Critic mode influence"}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:a.criticMode,onChange:r=>s(t.map(l=>l.id===a.id?{...l,criticMode:r.target.value}:l)),children:[e.jsx("option",{value:"",children:"None"}),n.map(r=>e.jsx("option",{value:r.title,children:r.title},r.id))]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"Linked belief"}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:a.beliefId??"",onChange:r=>s(t.map(l=>l.id===a.id?{...l,beliefId:r.target.value||null}:l)),children:[e.jsx("option",{value:"",children:"None"}),i.map(r=>e.jsx("option",{value:r.id,children:r.statement},r.id))]})]})]})]},a.id))})]})}function Dc({items:t,onChange:s,behaviors:i,modes:n}){return e.jsxs("div",{className:"grid gap-3",children:[e.jsx(ea,{title:"What did you do, or want to do?",description:"Capture the move itself, then optionally link an existing behavior and the mode context around it.",addLabel:"Add behavior",onAdd:()=>s([...t,Bf()])}),e.jsx("div",{className:"grid gap-3",children:t.map(a=>e.jsxs("div",{className:"grid gap-4 rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("label",{className:"grid flex-1 gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"Behavior or urge"}),e.jsx(Ce,{value:a.text,onChange:r=>s(t.map(l=>l.id===a.id?{...l,text:r.target.value}:l)),placeholder:"What did you do, or what move did you feel pulled toward?"})]}),e.jsx(ta,{onClick:()=>s(t.filter(r=>r.id!==a.id))})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"Linked existing behavior"}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:a.behaviorId??"",onChange:r=>{const l=i.find(d=>d.id===r.target.value);s(t.map(d=>d.id===a.id?{...d,behaviorId:r.target.value||null,text:l&&!d.text?l.title:d.text}:d))},children:[e.jsx("option",{value:"",children:"None"}),i.map(r=>e.jsx("option",{value:r.id,children:r.title},r.id))]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"Mode or urge context"}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:a.mode,onChange:r=>s(t.map(l=>l.id===a.id?{...l,mode:r.target.value}:l)),children:[e.jsx("option",{value:"",children:"None"}),n.map(r=>e.jsx("option",{value:r.title,children:r.title},r.id))]})]})]})]},a.id))})]})}function $c({items:t,onChange:s,modes:i,stages:n}){return e.jsxs("div",{className:"grid gap-3",children:[e.jsx(ea,{title:"How did your state shift through the chain?",description:"Build the mode timeline one moment at a time instead of typing parser syntax.",addLabel:"Add timeline moment",onAdd:()=>s([...t,Kf()])}),e.jsx("div",{className:"grid gap-3",children:t.map(a=>e.jsxs("div",{className:"grid gap-4 rounded-[24px] border 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",{className:"grid flex-1 gap-4 md:grid-cols-3",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"Stage"}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:a.stage,onChange:r=>s(t.map(l=>l.id===a.id?{...l,stage:r.target.value}:l)),children:[e.jsx("option",{value:"",children:"Choose stage"}),n.map(r=>e.jsx("option",{value:r,children:r},r))]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"Mode"}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:a.modeId??"",onChange:r=>{const l=i.find(d=>d.id===r.target.value);s(t.map(d=>d.id===a.id?{...d,modeId:r.target.value||null,label:l&&!d.label?l.title:d.label}:d))},children:[e.jsx("option",{value:"",children:"Choose mode"}),i.map(r=>e.jsx("option",{value:r.id,children:r.title},r.id))]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"Moment label"}),e.jsx(ie,{value:a.label,onChange:r=>s(t.map(l=>l.id===a.id?{...l,label:r.target.value}:l)),placeholder:"What was happening in this moment?"})]})]}),e.jsx(ta,{onClick:()=>s(t.filter(r=>r.id!==a.id))})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"What was important about this shift?"}),e.jsx(Ce,{value:a.note,onChange:r=>s(t.map(l=>l.id===a.id?{...l,note:r.target.value}:l)),placeholder:"Short note about how the mode showed up or what it was protecting."})]})]},a.id))})]})}function Uf(t){return t.join(`
|
|
19
|
+
`)}function jn(t,s){return t.includes(s)?t.filter(i=>i!==s):[...t,s]}function Qf(t){return{title:t.title,status:t.status,eventTypeId:t.eventTypeId??"",customEventType:t.customEventType,eventSituation:t.eventSituation,occurredAt:t.occurredAt?t.occurredAt.slice(0,16):"",emotions:t.emotions,thoughts:t.thoughts,behaviors:t.behaviors,selfShortTerm:t.consequences.selfShortTerm,selfLongTerm:t.consequences.selfLongTerm,othersShortTerm:t.consequences.othersShortTerm,othersLongTerm:t.consequences.othersLongTerm,modeOverlaysText:Uf(t.modeOverlays),schemaLinks:t.schemaLinks,modeTimeline:t.modeTimeline,nextMoves:t.nextMoves,linkedBehaviorIds:t.linkedBehaviorIds,linkedBeliefIds:t.linkedBeliefIds,linkedModeIds:t.linkedModeIds}}function Wf(){var L,q,G,Q,ne,H;const{reportId:t}=Hs(),s=We(),[i,n]=c.useState("spark"),[a,r]=c.useState(null),[l,d]=c.useState(!1),o=pe({queryKey:["forge-psyche-report",t],queryFn:()=>Qu(t),enabled:!!t}),x=pe({queryKey:["forge-psyche-behaviors"],queryFn:os}),f=pe({queryKey:["forge-psyche-beliefs"],queryFn:As}),b=pe({queryKey:["forge-psyche-modes"],queryFn:Ls}),m=pe({queryKey:["forge-psyche-schema-catalog"],queryFn:Xi}),h=pe({queryKey:["forge-psyche-event-types"],queryFn:jd}),p=pe({queryKey:["forge-psyche-emotions"],queryFn:Nd});c.useEffect(()=>{var _;(_=o.data)!=null&&_.report&&r(Qf(o.data.report))},[o.data]);const w=ge({mutationFn:async _=>{var C;const U=(C=o.data)==null?void 0:C.report,R=Bn.parse({title:_.title,status:_.status,eventTypeId:_.eventTypeId||null,customEventType:_.customEventType,eventSituation:_.eventSituation,occurredAt:_.occurredAt?new Date(_.occurredAt).toISOString():null,emotions:_.emotions.filter(J=>J.label.trim().length>0),thoughts:_.thoughts.filter(J=>J.text.trim().length>0),behaviors:_.behaviors.filter(J=>J.text.trim().length>0),consequences:{selfShortTerm:_.selfShortTerm,selfLongTerm:_.selfLongTerm,othersShortTerm:_.othersShortTerm,othersLongTerm:_.othersLongTerm},linkedPatternIds:(U==null?void 0:U.linkedPatternIds)??[],linkedValueIds:(U==null?void 0:U.linkedValueIds)??[],linkedGoalIds:(U==null?void 0:U.linkedGoalIds)??[],linkedProjectIds:(U==null?void 0:U.linkedProjectIds)??[],linkedTaskIds:(U==null?void 0:U.linkedTaskIds)??[],linkedBehaviorIds:_.linkedBehaviorIds,linkedBeliefIds:_.linkedBeliefIds,linkedModeIds:_.linkedModeIds,modeOverlays:_.modeOverlaysText.split(`
|
|
20
|
+
`).map(J=>J.trim()).filter(Boolean),schemaLinks:_.schemaLinks.filter(Boolean),modeTimeline:_.modeTimeline.filter(J=>J.stage.trim().length>0&&J.label.trim().length>0),nextMoves:_.nextMoves.filter(Boolean)});return Wu(t,R)},onSuccess:async()=>{await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-report",t]}),s.invalidateQueries({queryKey:["forge-psyche-reports"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]}),s.invalidateQueries({queryKey:["forge-reward-ledger"]})])}}),v=ge({mutationFn:Md,onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-psyche-report",t]}),await s.invalidateQueries({queryKey:["forge-insights"]})}}),I=o.error??x.error??f.error??b.error??m.error??h.error??p.error??null;if(o.isLoading||!a)return e.jsx(It,{});if(I)return e.jsx(Oe,{eyebrow:"Trigger report",error:I,onRetry:()=>void Promise.all([o.refetch(),x.refetch(),f.refetch(),b.refetch(),m.refetch(),h.refetch(),p.refetch()])});if(!o.data)return e.jsx(Oe,{eyebrow:"Trigger report",error:new Error("Forge returned an empty trigger report payload."),onRetry:()=>void o.refetch()});const k=o.data,S=k.report,M=((L=x.data)==null?void 0:L.behaviors)??[],P=((q=f.data)==null?void 0:q.beliefs)??[],y=((G=b.data)==null?void 0:G.modes)??[],N=((Q=m.data)==null?void 0:Q.schemas)??[],A=((ne=h.data)==null?void 0:ne.eventTypes)??[],T=((H=p.data)==null?void 0:H.emotions)??[],F=[{id:"spark",label:"Spark",summary:"What happened concretely?"},{id:"wave",label:"Wave",summary:"What emotional wave moved through you?"},{id:"script",label:"Script",summary:"What did the mind start saying?"},{id:"lens",label:"Lens",summary:"Which schemas and beliefs got activated?"},{id:"state",label:"State",summary:"Which modes took the wheel?"},{id:"move",label:"Move",summary:"What did you do or want to do?"},{id:"horizon",label:"Horizon",summary:"What were the consequences?"},{id:"pivot",label:"Pivot",summary:"What is the next move now?"}],u={spark:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-[minmax(0,1fr)_13rem]",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Title"}),e.jsx(ie,{value:a.title,onChange:_=>r({...a,title:_.target.value})})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Status"}),e.jsxs("select",{className:"rounded-[22px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:a.status,onChange:_=>r({...a,status:_.target.value}),children:[e.jsx("option",{value:"draft",children:"draft"}),e.jsx("option",{value:"reviewed",children:"reviewed"}),e.jsx("option",{value:"integrated",children:"integrated"})]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Event type"}),e.jsxs("select",{className:"rounded-[22px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:a.eventTypeId,onChange:_=>r({...a,eventTypeId:_.target.value}),children:[e.jsx("option",{value:"",children:"Custom or uncategorized"}),A.map(_=>e.jsx("option",{value:_.id,children:_.label},_.id))]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Occurred at"}),e.jsx(ie,{type:"datetime-local",value:a.occurredAt,onChange:_=>r({...a,occurredAt:_.target.value})})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Custom event label"}),e.jsx(ie,{value:a.customEventType,onChange:_=>r({...a,customEventType:_.target.value})})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Situation"}),e.jsx(Ce,{value:a.eventSituation,onChange:_=>r({...a,eventSituation:_.target.value})})]})]}),wave:e.jsx(Ac,{items:a.emotions,onChange:_=>r({...a,emotions:_}),definitions:T}),script:e.jsx(Lc,{items:a.thoughts,onChange:_=>r({...a,thoughts:_}),beliefs:P,modes:y}),lens:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"grid gap-4 rounded-[24px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Schema links"}),e.jsx(Xe,{content:"Use maladaptive schemas for recurring old patterns that were active here. Use adaptive schemas for healthier patterns you want this response to build on.",label:"Explain schema links"})]}),e.jsx(Ps,{children:"Choose the schemas that were active here or that you want the repair move to strengthen."}),[{title:"Maladaptive schemas",schemas:N.filter(_=>_.schemaType==="maladaptive"),schemaType:"maladaptive",description:"Recurring old patterns that felt active in this moment."},{title:"Adaptive schemas",schemas:N.filter(_=>_.schemaType==="adaptive"),schemaType:"adaptive",description:"Healthier stable themes you want this chain to strengthen."}].map(_=>{const U=wi(_.schemaType);return e.jsxs("div",{className:`rounded-[22px] border p-4 ${U.cardTone}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:_.title}),e.jsx(Xe,{content:Wi(_.schemaType),label:`Explain ${Ya(_.schemaType)}`})]}),e.jsx(Ps,{className:"mt-2",children:_.description}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:_.schemas.map(R=>{const C=a.schemaLinks.some(J=>{var ee;return((ee=vi(J,[R]))==null?void 0:ee.id)===R.id});return e.jsx("button",{type:"button",className:`rounded-full border px-3 py-2 text-sm transition ${C?`${U.badgeTone} ring-1 ring-white/18`:"border-white/8 bg-white/[0.04] text-white/58 hover:bg-white/[0.08] hover:text-white"}`,onClick:()=>r({...a,schemaLinks:Mc(a.schemaLinks,R)}),children:R.title},R.id)})})]},_.schemaType)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-white/58",children:"Linked beliefs"}),e.jsx("div",{className:"mt-3 flex max-h-56 flex-wrap gap-2 overflow-y-auto",children:P.map(_=>{const U=a.linkedBeliefIds.includes(_.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${U?"bg-[rgba(196,181,253,0.18)] text-violet-100":"bg-white/[0.05] text-white/58 hover:bg-white/[0.08] hover:text-white"}`,onClick:()=>r({...a,linkedBeliefIds:jn(a.linkedBeliefIds,_.id)}),children:_.statement},_.id)})})]})]}),state:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Mode overlays"}),e.jsx(Ce,{value:a.modeOverlaysText,onChange:_=>r({...a,modeOverlaysText:_.target.value})})]}),e.jsx($c,{items:a.modeTimeline,onChange:_=>r({...a,modeTimeline:_}),modes:y,stages:F.map(_=>_.label)}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-white/58",children:"Linked modes"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:y.map(_=>{const U=a.linkedModeIds.includes(_.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${U?"bg-[rgba(251,191,36,0.18)] text-amber-100":"bg-white/[0.05] text-white/58 hover:bg-white/[0.08] hover:text-white"}`,onClick:()=>r({...a,linkedModeIds:jn(a.linkedModeIds,_.id)}),children:_.title},_.id)})})]})]}),move:e.jsxs("div",{className:"grid gap-4",children:[e.jsx(Dc,{items:a.behaviors,onChange:_=>r({...a,behaviors:_}),behaviors:M,modes:y}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-white/58",children:"Linked behaviors"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:M.map(_=>{const U=a.linkedBehaviorIds.includes(_.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${U?"bg-[rgba(251,113,133,0.16)] text-rose-100":"bg-white/[0.05] text-white/58 hover:bg-white/[0.08] hover:text-white"}`,onClick:()=>r({...a,linkedBehaviorIds:jn(a.linkedBehaviorIds,_.id)}),children:_.title},_.id)})})]})]}),horizon:e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(as,{title:"Short-term impact on you",description:"What happened to you right away?",addLabel:"Add self effect",items:a.selfShortTerm,onChange:_=>r({...a,selfShortTerm:_}),placeholder:"I shut down and lost the evening."}),e.jsx(as,{title:"Long-term impact on you",description:"What does this cost if it keeps repeating?",addLabel:"Add self cost",items:a.selfLongTerm,onChange:_=>r({...a,selfLongTerm:_}),placeholder:"It keeps training the same abandonment script."}),e.jsx(as,{title:"Short-term impact on others",description:"What happened to other people right away?",addLabel:"Add other effect",items:a.othersShortTerm,onChange:_=>r({...a,othersShortTerm:_}),placeholder:"They felt shut out."}),e.jsx(as,{title:"Long-term impact on others",description:"What pattern does this create over time?",addLabel:"Add other cost",items:a.othersLongTerm,onChange:_=>r({...a,othersLongTerm:_}),placeholder:"Trust gets thinner each time."})]}),pivot:e.jsxs("div",{className:"grid gap-4",children:[e.jsx(as,{title:"What is the next move now?",description:"Finish with concrete repairs, boundaries, or committed actions.",addLabel:"Add next move",items:a.nextMoves,onChange:_=>r({...a,nextMoves:_}),placeholder:"Send one honest repair message tomorrow morning."}),e.jsx("div",{className:"flex justify-end",children:e.jsx(W,{pending:w.isPending,onClick:()=>void w.mutateAsync(a),children:"Save chain"})})]})},j=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Linked modes"}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[y.filter(_=>a.linkedModeIds.includes(_.id)).map(_=>e.jsx(ke,{kind:"mode",label:_.title,compact:!0},_.id)),a.linkedModeIds.length===0?e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>n("state"),children:"Link mode"}):null]})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Linked beliefs"}),e.jsxs("div",{className:"mt-3 grid gap-2",children:[P.filter(_=>a.linkedBeliefIds.includes(_.id)).map(_=>e.jsx("div",{className:"rounded-[16px] bg-white/[0.04] px-3 py-3",children:e.jsx(ke,{kind:"belief",label:_.statement,compact:!0})},_.id)),a.linkedBeliefIds.length===0?e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>n("lens"),children:"Link belief"}):null]})]}),e.jsx(Ga,{entityType:"trigger_report",entityId:S.id,anchorKey:i,includeAnchorlessWhenAnchored:!0,compact:!0,title:`Stage notes on ${i}`,description:"Use anchored Markdown notes to capture what became clear at this stage of the chain.",invalidateQueryKeys:[["forge-psyche-report",t],["forge-psyche-reports"],["forge-psyche-overview"]]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Insights"}),e.jsxs("div",{className:"mt-3 grid gap-2",children:[k.insights.map(_=>e.jsxs("div",{className:"rounded-[16px] bg-white/[0.04] px-3 py-3 text-sm text-white/72",children:[e.jsx("div",{className:"font-medium text-white",children:_.title}),e.jsx("div",{className:"mt-2 text-white/62",children:_.summary})]},_.id)),e.jsx(W,{variant:"secondary",pending:v.isPending,onClick:()=>d(!0),children:"Store insight"})]})]})]});return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{eyebrow:"Trigger report",title:S.title,description:"Move through Spark to Pivot in one chain canvas.",badge:S.status}),e.jsx(Ht,{}),e.jsx(Rf,{stages:F,activeStageId:i,onStageChange:n,stageContent:u[i],inspector:j}),e.jsx(dc,{open:l,onOpenChange:d,eyebrow:"Report insight",title:"Store report insight",description:"Capture the insight from this report as a guided recommendation instead of a raw side-panel form.",submitLabel:"Store insight",pending:v.isPending,lockedEntity:{entityType:"trigger_report",entityId:S.id,kind:"report",label:S.title,description:`Anchored to the ${i} stage of this reflective chain.`},initialValue:{originType:"user",originLabel:"Forge Psyche",timeframeLabel:"Current trigger report",rationale:`Captured from the ${i} stage of the Psyche chain canvas.`},onSubmit:async _=>{await v.mutateAsync(_)}})]})}const ba={title:"",status:"draft",eventTypeId:"",customEventType:"",eventSituation:"",occurredAt:"",emotions:[],thoughts:[],behaviors:[],selfShortTerm:[],selfLongTerm:[],othersShortTerm:[],othersLongTerm:[],linkedValueIds:[],linkedBehaviorIds:[],linkedBeliefIds:[],linkedModeIds:[],linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],schemaLinks:[],modeTimeline:[],nextMoves:[],userId:null};function Gf(){var J,ee,le,oe,ue,me,$,ce;const t=Ye(),s=We(),[i,n]=ft(),[a,r]=c.useState(!1),[l,d]=c.useState(ba),[o,x]=c.useState(null),f=pe({queryKey:["forge-psyche-reports"],queryFn:Ti}),b=pe({queryKey:["forge-psyche-values"],queryFn:ls}),m=pe({queryKey:["forge-psyche-behaviors"],queryFn:os}),h=pe({queryKey:["forge-psyche-beliefs"],queryFn:As}),p=pe({queryKey:["forge-psyche-modes"],queryFn:Ls}),w=pe({queryKey:["forge-psyche-schema-catalog"],queryFn:Xi}),v=pe({queryKey:["forge-psyche-event-types"],queryFn:jd}),I=pe({queryKey:["forge-psyche-emotions"],queryFn:Nd}),k=((J=f.data)==null?void 0:J.reports)??[],S=((ee=b.data)==null?void 0:ee.values)??[],M=((le=m.data)==null?void 0:le.behaviors)??[],P=((oe=h.data)==null?void 0:oe.beliefs)??[],y=((ue=p.data)==null?void 0:ue.modes)??[],N=((me=w.data)==null?void 0:me.schemas)??[],A=(($=v.data)==null?void 0:$.eventTypes)??[],T=((ce=I.data)==null?void 0:ce.emotions)??[],F=Nt(t.selectedUserIds),u=t.snapshot.dashboard.notesSummaryByEntity;c.useEffect(()=>{if(i.get("create")==="1"){r(!0),d({...ba,userId:F,customEventType:i.get("intent")==="execution_tension"?"Execution tension":i.get("intent")==="belief"?"Belief script activation":i.get("intent")==="behavior"?"Behavior spike":i.get("intent")==="pattern"?"Recurring pattern":i.get("intent")==="value"?"Blocked value":"",linkedValueIds:i.get("valueId")?[i.get("valueId")]:[],linkedBehaviorIds:i.get("behaviorId")?[i.get("behaviorId")]:[],linkedBeliefIds:i.get("beliefId")?[i.get("beliefId")]:[],linkedGoalIds:i.get("goalId")?[i.get("goalId")]:[],linkedProjectIds:i.get("projectId")?[i.get("projectId")]:[],linkedTaskIds:i.get("taskId")?[i.get("taskId")]:[]});const E=new URLSearchParams(i);E.delete("create"),E.delete("intent"),E.delete("valueId"),E.delete("behaviorId"),E.delete("beliefId"),E.delete("goalId"),E.delete("projectId"),E.delete("taskId"),n(E,{replace:!0})}},[i,n]);const j=ge({mutationFn:async E=>{const z=Bn.parse({title:E.title,status:E.status,eventTypeId:E.eventTypeId||null,customEventType:E.customEventType,eventSituation:E.eventSituation,occurredAt:E.occurredAt?new Date(E.occurredAt).toISOString():null,emotions:E.emotions.filter(K=>K.label.trim().length>0),thoughts:E.thoughts.filter(K=>K.text.trim().length>0),behaviors:E.behaviors.filter(K=>K.text.trim().length>0),consequences:{selfShortTerm:E.selfShortTerm,selfLongTerm:E.selfLongTerm,othersShortTerm:E.othersShortTerm,othersLongTerm:E.othersLongTerm},linkedPatternIds:[],linkedValueIds:E.linkedValueIds,linkedGoalIds:E.linkedGoalIds,linkedProjectIds:E.linkedProjectIds,linkedTaskIds:E.linkedTaskIds,linkedBehaviorIds:E.linkedBehaviorIds,linkedBeliefIds:E.linkedBeliefIds,linkedModeIds:E.linkedModeIds,modeOverlays:[],schemaLinks:E.schemaLinks.filter(Boolean),modeTimeline:E.modeTimeline.filter(K=>K.stage.trim().length>0&&K.label.trim().length>0),nextMoves:E.nextMoves.filter(Boolean),userId:E.userId});return kd(z)},onSuccess:async()=>{r(!1),d({...ba,userId:F}),x(null),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-reports"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]}),s.invalidateQueries({queryKey:["forge-xp-metrics"]})])}}),L=S.map(E=>({value:E.id,label:Je(E.title,E.user),description:Be(E.valuedDirection,E.user),searchText:qe([E.title,E.valuedDirection,E.description],E),kind:"value"})),q=M.map(E=>({value:E.id,label:Je(E.title,E.user),description:Be(E.kind,E.user),searchText:qe([E.title,E.kind,E.description],E),kind:"behavior"})),G=P.map(E=>({value:E.id,label:Je(E.statement,E.user),description:Be(E.flexibleAlternative||E.originNote,E.user),searchText:qe([E.statement,E.flexibleAlternative,E.originNote,E.beliefType],E),kind:"belief"})),Q=y.map(E=>({value:E.id,label:Je(E.title,E.user),description:Be(E.archetype||E.family,E.user),searchText:qe([E.title,E.archetype,E.family,E.persona],E),kind:"mode"})),ne=async E=>{const{value:z}=await Ii({title:E,description:"",valuedDirection:E,whyItMatters:"",linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],committedActions:[],userId:l.userId});return jt(s,["forge-psyche-values"],"values",z),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:z.id,label:z.title,description:z.valuedDirection,kind:"value"}},H=async E=>{const{behavior:z}=await Ka({kind:"away",title:E,description:"",commonCues:[],urgeStory:"",shortTermPayoff:"",longTermCost:"",replacementMove:"",repairPlan:"",linkedPatternIds:[],linkedValueIds:[],linkedSchemaIds:[],linkedModeIds:[],userId:l.userId});return jt(s,["forge-psyche-behaviors"],"behaviors",z),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:z.id,label:z.title,description:z.kind,kind:"behavior"}},_=async E=>{const{belief:z}=await cr({schemaId:null,statement:E,beliefType:"absolute",originNote:"",confidence:60,evidenceFor:[],evidenceAgainst:[],flexibleAlternative:"",linkedValueIds:[],linkedBehaviorIds:[],linkedModeIds:[],linkedReportIds:[],userId:l.userId});return jt(s,["forge-psyche-beliefs"],"beliefs",z),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:z.id,label:z.statement,description:z.flexibleAlternative||z.originNote,kind:"belief"}},U=async E=>{const{mode:z}=await Ji({family:"coping",archetype:"",title:E,persona:"",imagery:"",symbolicForm:"",facialExpression:"",fear:"",burden:"",protectiveJob:"",originContext:"",firstAppearanceAt:null,linkedPatternIds:[],linkedBehaviorIds:[],linkedValueIds:[],userId:l.userId});return jt(s,["forge-psyche-modes"],"modes",z),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:z.id,label:z.title,description:z.archetype||z.family,kind:"mode"}},R=[{id:"spark",eyebrow:"Spark",title:"Capture the trigger and the situation",description:"Start with what happened concretely before interpretation takes over.",render:(E,z)=>e.jsxs(e.Fragment,{children:[e.jsx(is,{value:E.userId,users:t.snapshot.users,onChange:K=>z({userId:K}),defaultLabel:ss(t.snapshot.users.find(K=>K.id===F)??null,"Choose report owner"),help:"Trigger reports can belong to a human or bot user while still linking to shared values, behaviors, beliefs, and modes."}),e.jsx(Y,{label:"Report title",children:e.jsx(ie,{value:E.title,onChange:K=>z({title:K.target.value}),placeholder:"Friday silence spiral"})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Y,{label:"Event type",children:e.jsxs("select",{className:"rounded-[22px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:E.eventTypeId,onChange:K=>z({eventTypeId:K.target.value}),children:[e.jsx("option",{value:"",children:"Custom or uncategorized"}),A.map(K=>e.jsx("option",{value:K.id,children:K.label},K.id))]})}),e.jsx(Y,{label:"Occurred at",children:e.jsx(ie,{type:"datetime-local",value:E.occurredAt,onChange:K=>z({occurredAt:K.target.value})})})]}),e.jsx(Y,{label:"Custom event label",children:e.jsx(ie,{value:E.customEventType,onChange:K=>z({customEventType:K.target.value}),placeholder:"Unexpected distance after vulnerability"})}),e.jsx(Y,{label:"Situation",children:e.jsx(Ce,{value:E.eventSituation,onChange:K=>z({eventSituation:K.target.value}),placeholder:"Describe what happened concretely, without explaining it away yet."})})]})},{id:"wave-script-move",eyebrow:"Wave, script, move",title:"Capture the emotional wave, thought script, and behavior",description:"These stay structured, but the flow keeps them staged instead of dumping everything into one giant form.",render:(E,z)=>e.jsxs(e.Fragment,{children:[e.jsx(Ac,{items:E.emotions,onChange:K=>z({emotions:K}),definitions:T}),e.jsx(Lc,{items:E.thoughts,onChange:K=>z({thoughts:K}),beliefs:P,modes:y}),e.jsx(Dc,{items:E.behaviors,onChange:K=>z({behaviors:K}),behaviors:M,modes:y})]})},{id:"lens-state",eyebrow:"Lens and state",title:"Link the report to beliefs, modes, values, and behavior history",description:"This is where the report becomes part of the larger graphical psyche system.",render:(E,z)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Linked values",children:e.jsx(st,{options:L,selectedValues:E.linkedValueIds,onChange:K=>z({linkedValueIds:K}),placeholder:"Search or create a value…",emptyMessage:"No values match yet.",createLabel:"Create value",onCreate:ne})}),e.jsx(Y,{label:"Linked behaviors",children:e.jsx(st,{options:q,selectedValues:E.linkedBehaviorIds,onChange:K=>z({linkedBehaviorIds:K}),placeholder:"Search or create a behavior…",emptyMessage:"No behaviors match yet.",createLabel:"Create behavior",onCreate:H})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Y,{label:"Linked beliefs",children:e.jsx(st,{options:G,selectedValues:E.linkedBeliefIds,onChange:K=>z({linkedBeliefIds:K}),placeholder:"Search or create a belief…",emptyMessage:"No beliefs match yet.",createLabel:"Create belief",onCreate:_})}),e.jsx(Y,{label:"Linked modes",children:e.jsx(st,{options:Q,selectedValues:E.linkedModeIds,onChange:K=>z({linkedModeIds:K}),placeholder:"Search or create a mode…",emptyMessage:"No modes match yet.",createLabel:"Create mode",onCreate:U})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[E.linkedGoalIds.length>0?e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm text-white/62",children:["Linked to ",E.linkedGoalIds.length," goal tension"]}):null,E.linkedProjectIds.length>0?e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm text-white/62",children:["Linked to ",E.linkedProjectIds.length," project tension"]}):null,E.linkedTaskIds.length>0?e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm text-white/62",children:["Linked to ",E.linkedTaskIds.length," task tension"]}):null]})]})},{id:"horizon-pivot",eyebrow:"Horizon and pivot",title:"Record consequences, schema pressure, and the next move",description:"Use this step to record what happened next, which schemas were involved, and what you want to do after this moment.",render:(E,z)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(as,{title:"Short-term impact on you",description:"Add the immediate effects on your body, mood, or direction.",addLabel:"Add self effect",items:E.selfShortTerm,onChange:K=>z({selfShortTerm:K}),placeholder:"I shut down and lost the rest of the evening."}),e.jsx(as,{title:"Long-term impact on you",description:"Capture what this pattern costs when it keeps repeating.",addLabel:"Add self cost",items:E.selfLongTerm,onChange:K=>z({selfLongTerm:K}),placeholder:"It keeps reinforcing the same abandonment story."}),e.jsx(as,{title:"Short-term impact on others",description:"Note what happened to the people around you right away.",addLabel:"Add other effect",items:E.othersShortTerm,onChange:K=>z({othersShortTerm:K}),placeholder:"They felt pushed away and confused."}),e.jsx(as,{title:"Long-term impact on others",description:"Capture the longer pattern this creates in relationships.",addLabel:"Add other cost",items:E.othersLongTerm,onChange:K=>z({othersLongTerm:K}),placeholder:"Trust gets thinner every time this loop takes over."})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsx(Y,{label:"Schema links",description:"Choose the schemas that were active or that you want to strengthen in this moment.",labelHelp:"Use maladaptive schemas for recurring old patterns that felt active here. Use adaptive schemas for healthier patterns you want to rely on more.",children:e.jsx("div",{className:"grid gap-4",children:[{title:"Maladaptive schemas",schemas:N.filter(K=>K.schemaType==="maladaptive"),schemaType:"maladaptive",description:"Recurring old patterns that felt active in this moment."},{title:"Adaptive schemas",schemas:N.filter(K=>K.schemaType==="adaptive"),schemaType:"adaptive",description:"Healthier stable themes you want this repair move to strengthen."}].map(K=>{const je=wi(K.schemaType);return e.jsxs("div",{className:`rounded-[24px] border p-4 ${je.cardTone}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:K.title}),e.jsx(Xe,{content:Wi(K.schemaType),label:`Explain ${Ya(K.schemaType)}`})]}),e.jsx(Ps,{className:"mt-2",children:K.description}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:K.schemas.map(V=>{const D=E.schemaLinks.some(X=>{var he;return((he=vi(X,[V]))==null?void 0:he.id)===V.id});return e.jsx("button",{type:"button",className:`rounded-full border px-3 py-2 text-sm transition ${D?`${je.badgeTone} ring-1 ring-white/18`:"border-white/8 bg-white/[0.04] text-white/58 hover:bg-white/[0.08] hover:text-white"}`,onClick:()=>z({schemaLinks:Mc(E.schemaLinks,V)}),children:V.title},V.id)})})]},K.schemaType)})})}),e.jsx($c,{items:E.modeTimeline,onChange:K=>z({modeTimeline:K}),modes:y,stages:["Spark","Wave","Script","Lens","State","Move","Horizon","Pivot"]}),e.jsx(as,{title:"Next moves",description:"Finish with concrete next moves that protect the value or repair the situation.",addLabel:"Add next move",items:E.nextMoves,onChange:K=>z({nextMoves:K}),placeholder:"Send one honest repair message tomorrow morning."})]})]})}];if(f.isLoading||b.isLoading||m.isLoading||h.isLoading||p.isLoading||w.isLoading||v.isLoading||I.isLoading)return e.jsx(xt,{eyebrow:"Reports",title:"Loading reports",description:"Getting reports, values, behaviors, beliefs, modes, event labels, and emotions ready."});const C=f.error??b.error??m.error??h.error??p.error??w.error??v.error??I.error;return C?e.jsx(Oe,{eyebrow:"Trigger reports",error:C,onRetry:()=>void Promise.all([f.refetch(),b.refetch(),m.refetch(),h.refetch(),p.refetch(),w.refetch(),v.refetch(),I.refetch()])}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{entityKind:"report",title:e.jsx(_e,{kind:"report",label:"Reports",variant:"heading",size:"lg"}),description:"Capture the trigger, emotional wave, script, state, and next pivot in one guided reflective chain instead of a single massive worksheet.",badge:`${k.length} reports`,actions:e.jsx(W,{onClick:()=>{d({...ba,userId:F}),r(!0)},children:"Reflect"})}),e.jsx(Ht,{}),e.jsx(xs,{eyebrow:"Reports",title:"Recent reports",description:"Open any report to review what happened, which beliefs and schemas were involved, and what you want to do next.",tone:"violet",children:e.jsx("div",{className:"grid gap-4",children:k.length===0?e.jsx(gt,{eyebrow:"Trigger reports",title:"No reports yet",description:"Start a first Spark-to-Pivot chain so Forge can track the full reflective arc instead of isolated notes."}):k.map(E=>{var z;return e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-white/[0.04] p-5 transition hover:bg-white/[0.07]",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(_e,{kind:"report",label:E.title,variant:"heading",size:"xl"}),e.jsx("div",{className:"mt-2 text-sm text-white/54",children:E.customEventType||E.eventSituation})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[E.user?e.jsx($e,{user:E.user,compact:!0}):null,e.jsx(yt,{entityType:"trigger_report",entityId:E.id,count:Tt(u,"trigger_report",E.id).count}),e.jsx(O,{children:E.status}),e.jsx(Le,{to:`/psyche/reports/${E.id}`,className:"inline-flex min-h-10 items-center rounded-full bg-white/[0.08] px-3 py-2 text-sm text-white transition hover:bg-white/[0.12]",children:"Open report"})]})]}),e.jsxs("div",{className:"mt-5 grid gap-3 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Spark"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/66",children:E.eventSituation})]}),e.jsxs("div",{className:"rounded-[20px] bg-[rgba(110,231,183,0.08)] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Wave"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/66",children:((z=E.emotions[0])==null?void 0:z.label)??"No emotion captured yet"})]}),e.jsxs("div",{className:"rounded-[20px] bg-[rgba(196,181,253,0.08)] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Lens"}),e.jsx("div",{className:"mt-3",children:E.schemaLinks[0]?(()=>{const K=vi(E.schemaLinks[0],N);return K?e.jsx(Is,{label:K.title,schemaType:K.schemaType,compact:!0}):e.jsx("div",{className:"text-sm leading-6 text-white/66",children:E.schemaLinks[0]})})():e.jsx("div",{className:"text-sm leading-6 text-white/66",children:"No schema link yet"})})]}),e.jsxs("div",{className:"rounded-[20px] bg-[rgba(251,191,36,0.08)] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Pivot"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/66",children:E.nextMoves[0]??"No next move yet"})]})]})]},E.id)})})}),e.jsx(it,{open:a,onOpenChange:r,eyebrow:"Trigger report",title:"Build a reflective chain",description:"This guided flow replaces the old open worksheet with a staged Spark-to-Pivot capture.",value:l,onChange:d,steps:R,submitLabel:"Create report",pending:j.isPending,error:o,onSubmit:async()=>{if(x(null),!Bn.safeParse({title:l.title,status:l.status,eventTypeId:l.eventTypeId||null,customEventType:l.customEventType,eventSituation:l.eventSituation,occurredAt:l.occurredAt?new Date(l.occurredAt).toISOString():null,emotions:l.emotions.filter(z=>z.label.trim().length>0),thoughts:l.thoughts.filter(z=>z.text.trim().length>0),behaviors:l.behaviors.filter(z=>z.text.trim().length>0),consequences:{selfShortTerm:l.selfShortTerm,selfLongTerm:l.selfLongTerm,othersShortTerm:l.othersShortTerm,othersLongTerm:l.othersLongTerm},linkedPatternIds:[],linkedValueIds:l.linkedValueIds,linkedGoalIds:l.linkedGoalIds,linkedProjectIds:l.linkedProjectIds,linkedTaskIds:l.linkedTaskIds,linkedBehaviorIds:l.linkedBehaviorIds,linkedBeliefIds:l.linkedBeliefIds,linkedModeIds:l.linkedModeIds,modeOverlays:[],schemaLinks:l.schemaLinks.filter(Boolean),modeTimeline:l.modeTimeline.filter(z=>z.stage.trim().length>0&&z.label.trim().length>0),nextMoves:l.nextMoves.filter(Boolean)}).success){x("This report still needs a title and concrete triggering situation.");return}try{await j.mutateAsync(l)}catch(z){x(z instanceof Error?z.message:"Unable to create this report right now.")}}})]})}const Fi={schemaId:null,statement:"",beliefType:"absolute",originNote:"",confidence:60,evidenceFor:[],evidenceAgainst:[],flexibleAlternative:"",linkedValueIds:[],linkedBehaviorIds:[],linkedModeIds:[],linkedReportIds:[],userId:null};function Nn(t){return{schemaId:t.schemaId,statement:t.statement,beliefType:t.beliefType,originNote:t.originNote,confidence:t.confidence,evidenceFor:t.evidenceFor,evidenceAgainst:t.evidenceAgainst,flexibleAlternative:t.flexibleAlternative,linkedValueIds:t.linkedValueIds,linkedBehaviorIds:t.linkedBehaviorIds,linkedModeIds:t.linkedModeIds,linkedReportIds:t.linkedReportIds,userId:t.userId??null}}function Hf({schema:t,beliefs:s,behaviors:i,reports:n}){const a=s.filter(d=>d.schemaId===t.id).length,r=i.filter(d=>d.linkedSchemaIds.includes(t.id)).length,l=n.filter(d=>d.schemaLinks.some(o=>{const x=vi(o,[t]);return(x==null?void 0:x.id)===t.id})).length;return{beliefCount:a,behaviorCount:r,reportCount:l,total:a+r+l}}function go({title:t,description:s,titleHelp:i,schemas:n,beliefs:a,behaviors:r,reports:l,onOpenBelief:d}){if(n.length===0)return null;const o=wi(n[0].schemaType);return e.jsxs("section",{className:`min-w-0 grid gap-4 rounded-[30px] border p-4 md:p-5 ${o.sectionTone}`,children:[e.jsxs("div",{className:"flex min-w-0 flex-col items-start gap-3 sm:flex-row sm:flex-wrap sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"grid min-w-0 gap-2",children:[e.jsxs("div",{className:`flex items-center gap-2 text-[11px] uppercase tracking-[0.18em] ${o.sectionEyebrow}`,children:[e.jsx("span",{children:t}),i?e.jsx(Xe,{content:i,label:`Explain ${t.toLowerCase()}`}):null]}),e.jsx("div",{className:"max-w-3xl text-sm leading-6 text-white/60",children:s})]}),e.jsxs(O,{children:[n.length," schemas"]})]}),e.jsx("div",{className:"grid gap-4 xl:grid-cols-2",children:n.map(x=>{const f=Hf({schema:x,beliefs:a,behaviors:r,reports:l}),b=a.filter(h=>h.schemaId===x.id),m=wi(x.schemaType);return e.jsxs("div",{className:`min-w-0 rounded-[26px] border p-5 ${m.cardTone}`,children:[e.jsxs("div",{className:"flex min-w-0 flex-col items-start gap-3 sm:flex-row sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(Is,{label:x.title,schemaType:x.schemaType}),e.jsx("div",{className:"mt-3 text-sm text-white/46",children:Sr(x.family)}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/62",children:x.description})]}),e.jsxs(O,{children:[f.total," ",m.countLabel]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsxs(O,{className:"bg-white/[0.06] text-white/68",children:[f.beliefCount," beliefs"]}),e.jsxs(O,{className:"bg-white/[0.06] text-white/68",children:[f.behaviorCount," behaviors"]}),e.jsxs(O,{className:"bg-white/[0.06] text-white/68",children:[f.reportCount," reports"]})]}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[b.length>0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] p-4 text-sm text-white/58",children:`${b.length} ${m.linkSummary}${b.length===1?"":"s"} live here.`}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.03] p-4 text-sm leading-6 text-white/46",children:m.emptyCopy}),b.slice(0,2).map(h=>e.jsxs("button",{type:"button",className:"rounded-[20px] bg-white/[0.04] p-4 text-left transition hover:bg-white/[0.08]",onClick:()=>d(h),children:[e.jsx("div",{className:"font-medium text-white",children:h.statement}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:h.flexibleAlternative||"No flexible alternative recorded yet."})]},h.id))]})]},x.id)})})]})}function Xf(){var le,oe,ue,me,$,ce;const t=Ye(),s=We(),[i,n]=ft(),[a,r]=c.useState(!1),[l,d]=c.useState(null),[o,x]=c.useState(Fi),[f,b]=c.useState(null),m=pe({queryKey:["forge-psyche-schema-catalog"],queryFn:Xi}),h=pe({queryKey:["forge-psyche-beliefs"],queryFn:As}),p=pe({queryKey:["forge-psyche-behaviors"],queryFn:os}),w=pe({queryKey:["forge-psyche-modes"],queryFn:Ls}),v=pe({queryKey:["forge-psyche-values"],queryFn:ls}),I=pe({queryKey:["forge-psyche-reports"],queryFn:Ti}),k=((le=m.data)==null?void 0:le.schemas)??[],S=((oe=h.data)==null?void 0:oe.beliefs)??[],M=((ue=p.data)==null?void 0:ue.behaviors)??[],P=((me=w.data)==null?void 0:me.modes)??[],y=(($=v.data)==null?void 0:$.values)??[],N=((ce=I.data)==null?void 0:ce.reports)??[],A=Nt(t.selectedUserIds),T=i.get("focus"),F=t.snapshot.dashboard.notesSummaryByEntity;Vi(T),c.useEffect(()=>{if(i.get("create")==="1"){r(!0),d(null),x({...Fi,userId:A});const E=new URLSearchParams(i);E.delete("create"),n(E,{replace:!0})}},[A,i,n]);const u=ge({mutationFn:async E=>{const z=ho.parse(E);return l?qu(l.id,z):cr(z)},onSuccess:async()=>{r(!1),d(null),x({...Fi,userId:A}),b(null),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-beliefs"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]})])}}),j=y.map(E=>({value:E.id,label:Je(E.title,E.user),description:Be(E.valuedDirection,E.user),searchText:qe([E.title,E.valuedDirection,E.description],E),kind:"value"})),L=M.map(E=>({value:E.id,label:Je(E.title,E.user),description:Be(E.kind,E.user),searchText:qe([E.title,E.kind,E.description],E),kind:"behavior"})),q=P.map(E=>({value:E.id,label:Je(E.title,E.user),description:Be(E.archetype||E.family,E.user),searchText:qe([E.title,E.archetype,E.family,E.persona],E),kind:"mode"})),G=N.map(E=>({value:E.id,label:Je(E.title,E.user),description:Be(E.customEventType||E.eventSituation,E.user),searchText:qe([E.title,E.customEventType,E.eventSituation],E),kind:"report"})),Q=c.useMemo(()=>new Map(k.map(E=>[E.id,E])),[k]),ne=c.useMemo(()=>k.filter(E=>E.schemaType==="maladaptive"),[k]),H=c.useMemo(()=>k.filter(E=>E.schemaType==="adaptive"),[k]),_=async E=>{const{value:z}=await Ii({title:E,description:"",valuedDirection:E,whyItMatters:"",linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],committedActions:[],userId:o.userId});return jt(s,["forge-psyche-values"],"values",z),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:z.id,label:z.title,description:z.valuedDirection,kind:"value"}},U=async E=>{const{behavior:z}=await Ka({kind:"away",title:E,description:"",commonCues:[],urgeStory:"",shortTermPayoff:"",longTermCost:"",replacementMove:"",repairPlan:"",linkedPatternIds:[],linkedValueIds:[],linkedSchemaIds:[],linkedModeIds:[],userId:o.userId});return jt(s,["forge-psyche-behaviors"],"behaviors",z),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:z.id,label:z.title,description:z.kind,kind:"behavior"}},R=async E=>{const{mode:z}=await Ji({family:"coping",archetype:"",title:E,persona:"",imagery:"",symbolicForm:"",facialExpression:"",fear:"",burden:"",protectiveJob:"",originContext:"",firstAppearanceAt:null,linkedPatternIds:[],linkedBehaviorIds:[],linkedValueIds:[],userId:o.userId});return jt(s,["forge-psyche-modes"],"modes",z),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:z.id,label:z.title,description:z.archetype||z.family,kind:"mode"}},C=async E=>{const{report:z}=await kd({title:E,status:"draft",eventTypeId:null,customEventType:"",eventSituation:E,occurredAt:null,emotions:[],thoughts:[],behaviors:[],consequences:{selfShortTerm:[],selfLongTerm:[],othersShortTerm:[],othersLongTerm:[]},linkedPatternIds:[],linkedValueIds:[],linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],linkedBehaviorIds:[],linkedBeliefIds:[],linkedModeIds:[],modeOverlays:[],schemaLinks:[],modeTimeline:[],nextMoves:[],userId:o.userId});return jt(s,["forge-psyche-reports"],"reports",z),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:z.id,label:z.title,description:z.customEventType||z.eventSituation,kind:"report"}};c.useEffect(()=>{a&&b(null)},[a]);const J=[{id:"lens",eyebrow:"Lens",title:"Choose the schema and belief script",description:"Place the belief inside the right schema system, then write the actual inner line that tends to fire there.",render:(E,z)=>e.jsxs(e.Fragment,{children:[e.jsx(is,{value:E.userId??null,users:t.snapshot.users,onChange:K=>z({userId:K}),defaultLabel:ss(t.snapshot.users.find(K=>K.id===A)??null,"Choose belief owner"),help:"Beliefs can belong to a human or bot user even when they connect to shared behaviors, modes, and reports."}),e.jsx(Y,{label:"Schema",description:"Choose the schema this belief belongs to, whether it is a recurring old pattern or a healthier pattern you want to strengthen.",labelHelp:"Schemas are the broader repeating themes. Beliefs are the personal scripts that fire inside those themes.",children:e.jsx("div",{className:"grid gap-4",children:[{title:"Maladaptive schemas",schemas:ne,description:"Recurring old patterns that tend to get activated and distort how the situation feels.",schemaType:"maladaptive"},{title:"Adaptive schemas",schemas:H,description:"Healthier stable themes you want to strengthen, trust, and live from more often.",schemaType:"adaptive"}].map(K=>{const je=wi(K.schemaType);return e.jsxs("div",{className:`rounded-[24px] border p-4 ${je.cardTone}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:K.title}),e.jsx(Xe,{content:Wi(K.schemaType),label:`Explain ${Ya(K.schemaType)}`})]}),e.jsx(Ps,{className:"mt-2",children:K.description}),e.jsx("div",{className:"mt-4 grid gap-2 sm:flex sm:flex-wrap",children:K.schemas.map(V=>{const D=E.schemaId===V.id;return e.jsx("button",{type:"button",className:`w-full rounded-[18px] border px-3 py-2 text-left text-sm leading-5 transition sm:w-auto sm:rounded-full ${D?`${je.badgeTone} ring-1 ring-white/18`:"border-white/8 bg-white/[0.04] text-white/58 hover:bg-white/[0.08] hover:text-white"}`,onClick:()=>z({schemaId:V.id}),children:V.title},V.id)})})]},K.schemaType)})})}),e.jsx(Y,{label:"Belief statement",description:"Write the sentence the mind tends to say in the moment.",labelHelp:"A belief script should sound like the actual inner line that shows up under pressure, not a formal summary.",children:e.jsx(ie,{value:E.statement,onChange:K=>z({statement:K.target.value}),placeholder:"If they go quiet, I am already being left."})}),e.jsx(Y,{label:"Belief type",description:"Choose whether the script sounds absolute or conditional.",labelHelp:"Absolute beliefs sound fixed and global. Conditional beliefs sound more like if-then rules about safety, worth, or closeness.",children:e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:["absolute","conditional"].map(K=>e.jsx("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${E.beliefType===K?"border-white/20 bg-white/[0.12] text-white":"border-white/8 bg-white/[0.04] text-white/62 hover:bg-white/[0.07]"}`,onClick:()=>z({beliefType:K}),children:K==="absolute"?"Absolute: this is simply true":"Conditional: if this happens, then..."},K))})})]})},{id:"origin",eyebrow:"Origin",title:"Capture the origin and confidence of the script",description:"This keeps the belief from turning into a generic note divorced from actual history.",render:(E,z)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Origin context",description:"Capture where this script learned its force or usefulness.",children:e.jsx(Ce,{value:E.originNote,onChange:K=>z({originNote:K.target.value}),placeholder:"It got stronger in periods where silence usually meant anger, distance, or punishment."})}),e.jsxs(Y,{label:"Grip right now",description:"How strongly does this belief feel true when it gets activated?",labelHelp:"Grip is the felt strength of the script in the moment, not whether it is objectively true.",children:[e.jsx("input",{type:"range",min:0,max:100,value:E.confidence,onChange:K=>z({confidence:Number(K.target.value)})}),e.jsxs("div",{className:"text-sm text-white/48",children:[E.confidence,"% grip"]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Y,{label:"Evidence for",description:"Add one supporting memory, sign, or interpretation per line.",children:e.jsx(Ce,{value:E.evidenceFor.join(`
|
|
21
|
+
`),onChange:K=>z({evidenceFor:K.target.value.split(`
|
|
22
|
+
`).map(je=>je.trim()).filter(Boolean)}),placeholder:`One line per sign
|
|
23
|
+
They stopped replying for days
|
|
24
|
+
I was ignored when I asked directly`})}),e.jsx(Y,{label:"Evidence against",description:"Add one counterexample, nuance, or disconfirming sign per line.",children:e.jsx(Ce,{value:E.evidenceAgainst.join(`
|
|
25
|
+
`),onChange:K=>z({evidenceAgainst:K.target.value.split(`
|
|
26
|
+
`).map(je=>je.trim()).filter(Boolean)}),placeholder:`One line per counterpoint
|
|
27
|
+
They later explained they were overwhelmed
|
|
28
|
+
Other people stay close without constant contact`})})]})]})},{id:"repair",eyebrow:"Repair",title:"Define the flexible alternative and attach the wider system",description:"The flexible alternative is the repair move; the links keep it attached to behaviors, values, modes, and reports.",render:(E,z)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Flexible alternative",description:"Write the steadier line you want available when the old script activates.",labelHelp:"A flexible alternative is not fake positivity. It is a truer, more workable belief that leaves room for uncertainty.",children:e.jsx(Ce,{value:E.flexibleAlternative,onChange:K=>z({flexibleAlternative:K.target.value}),placeholder:"Silence can mean many things. I can check the facts before deciding I am being left."})}),e.jsx(Y,{label:"Linked values",description:"Choose the valued directions this belief interferes with most.",children:e.jsx(st,{options:j,selectedValues:E.linkedValueIds,onChange:K=>z({linkedValueIds:K}),placeholder:"Search or create a value…",emptyMessage:"No values match yet.",createLabel:"Create value",onCreate:_})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Y,{label:"Linked behaviors",description:"Choose the moves this belief tends to trigger or justify.",children:e.jsx(st,{options:L,selectedValues:E.linkedBehaviorIds,onChange:K=>z({linkedBehaviorIds:K}),placeholder:"Search or create a behavior…",emptyMessage:"No behaviors match yet.",createLabel:"Create behavior",onCreate:U})}),e.jsx(Y,{label:"Linked modes",description:"Choose the inner states that most often carry this script.",children:e.jsx(st,{options:q,selectedValues:E.linkedModeIds,onChange:K=>z({linkedModeIds:K}),placeholder:"Search or create a mode…",emptyMessage:"No modes match yet.",createLabel:"Create mode",onCreate:R})}),e.jsx(Y,{label:"Linked reports",description:"Choose the reflective chains where this script has already shown up.",children:e.jsx(st,{options:G,selectedValues:E.linkedReportIds,onChange:K=>z({linkedReportIds:K}),placeholder:"Search or create a report…",emptyMessage:"No reports match yet.",createLabel:"Create report",onCreate:C})})]})]})}];if(m.isLoading||h.isLoading||p.isLoading||w.isLoading||v.isLoading||I.isLoading)return e.jsx(xt,{eyebrow:"Schemas & beliefs",title:"Loading schemas and beliefs",description:"Getting schemas, beliefs, behaviors, modes, values, and linked reports ready."});const ee=m.error??h.error??p.error??w.error??v.error??I.error;return ee?e.jsx(Oe,{eyebrow:"Schemas & beliefs",error:ee,onRetry:()=>void Promise.all([m.refetch(),h.refetch(),p.refetch(),w.refetch(),v.refetch(),I.refetch()])}):e.jsxs("div",{className:"grid min-w-0 gap-5",children:[e.jsx(Ke,{title:"Schemas & Beliefs",description:"Review your schemas and beliefs together. See which beliefs are tied to each schema, then open any belief to edit it in context.",badge:`${S.length} beliefs`,actions:e.jsx(W,{onClick:()=>{d(null),x({...Fi,userId:A}),r(!0)},children:"Add belief"})}),e.jsx(Ht,{}),e.jsxs("section",{className:"grid min-w-0 gap-5 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]",children:[e.jsx(xs,{eyebrow:"Schemas",title:"Schemas",description:"Use these groups to notice recurring old patterns and to reinforce healthier patterns you want to rely on more often.",titleHelp:"Schemas are broad recurring patterns that shape how situations feel and how you respond. Use them to organize beliefs, behaviors, and reports around patterns that repeat.",tone:"violet",children:k.length===0?e.jsx("div",{className:"text-sm text-white/56",children:"Schema data is unavailable right now."}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(go,{title:"Maladaptive schemas",titleHelp:Wi("maladaptive"),description:"These schemas describe recurring old patterns that can change how you read situations and react.",schemas:ne,beliefs:S,behaviors:M,reports:N,onOpenBelief:E=>{d(E),x(Nn(E)),r(!0)}}),e.jsx(go,{title:"Adaptive schemas",titleHelp:Wi("adaptive"),description:"These schemas describe healthier patterns you want to trust, practice, and strengthen over time.",schemas:H,beliefs:S,behaviors:M,reports:N,onOpenBelief:E=>{d(E),x(Nn(E)),r(!0)}})]})}),e.jsx(xs,{eyebrow:"Beliefs",title:"Beliefs",description:"Use this list to review and edit the stories you tell yourself. Open any belief to update the wording, evidence, or a more flexible alternative.",titleHelp:"Beliefs are the specific scripts or rules that show up in your mind, such as what you expect from yourself, from other people, or from a situation.",tone:"sky",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx(W,{onClick:()=>{d(null),x({...Fi,userId:A}),r(!0)},children:"Add belief"}),S.length===0?e.jsx("div",{className:"text-sm text-white/56",children:"Your beliefs will appear here after you add the first one."}):S.map(E=>{const z=E.schemaId?Q.get(E.schemaId)??null:null,K=T===E.id;return e.jsxs("div",{"data-psyche-focus-id":E.id,className:`rounded-[24px] border border-white/8 bg-white/[0.04] p-4 text-left transition hover:bg-white/[0.08] ${Zi(K)}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:E.statement}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[E.user?e.jsx($e,{user:E.user,compact:!0}):null,e.jsx(yt,{entityType:"belief_entry",entityId:E.id,count:Tt(F,"belief_entry",E.id).count}),e.jsxs(O,{children:[E.confidence,"% grip"]}),e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>{d(E),x(Nn(E)),r(!0)},children:"Edit"})]})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:E.flexibleAlternative||"No flexible alternative recorded yet."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[z?e.jsx(Is,{label:z.title,schemaType:z.schemaType,compact:!0,showType:!0}):null,P.filter(je=>E.linkedModeIds.includes(je.id)).slice(0,2).map(je=>e.jsx(ke,{kind:"mode",label:je.title,compact:!0},je.id))]})]},E.id)})]})})]}),e.jsx(it,{open:a,onOpenChange:r,eyebrow:"Belief",title:l?"Refine belief":"Create belief",description:"Use this guided flow to capture the belief, what seems to support it, and a more flexible alternative.",value:o,onChange:x,steps:J,submitLabel:l?"Save belief":"Create belief",pending:u.isPending,error:f,onSubmit:async()=>{b(null);const E=ho.safeParse(o);if(!E.success){b("This belief still needs a statement before it can be saved.");return}try{await u.mutateAsync(E.data)}catch(z){b(z instanceof Error?z.message:"Unable to save this belief right now.")}}})]})}const si={title:"",description:"",valuedDirection:"",whyItMatters:"",linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],committedActions:[],userId:null};function kn(t,s){return t.includes(s)?t.filter(i=>i!==s):[...t,s]}function Jf(t){return{title:t.title,description:t.description,valuedDirection:t.valuedDirection,whyItMatters:t.whyItMatters,linkedGoalIds:t.linkedGoalIds,linkedProjectIds:t.linkedProjectIds,linkedTaskIds:t.linkedTaskIds,committedActions:t.committedActions,userId:t.userId??null}}function Yf(){var M;const t=Ye(),s=We(),[i,n]=ft(),[a,r]=c.useState(!1),[l,d]=c.useState(null),[o,x]=c.useState(si),[f,b]=c.useState(null),m=pe({queryKey:["forge-psyche-values"],queryFn:ls}),h=((M=m.data)==null?void 0:M.values)??[],p=Nt(t.selectedUserIds),w=i.get("focus"),v=t.snapshot.dashboard.notesSummaryByEntity;Vi(w),c.useEffect(()=>{if(i.get("create")==="1"){r(!0),d(null),x({...si,userId:p});const P=new URLSearchParams(i);P.delete("create"),n(P,{replace:!0})}},[p,i,n]);const I=ge({mutationFn:async P=>{const y=oo.parse(P);return l?_u(l.id,y):Ii(y)},onSuccess:async()=>{r(!1),d(null),x({...si,userId:p}),b(null),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-values"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]})])}}),k=c.useMemo(()=>h.slice(0,5).map((P,y)=>({id:P.id,label:`${P.linkedGoalIds.length} goals`,title:P.title,detail:P.valuedDirection,href:`/psyche/values?focus=${P.id}#values-atlas`,angle:-90+y*68,radius:150+y%2*20,tone:["mint","sky","violet","rose"][y%4]})),[h]),S=[{id:"direction",eyebrow:"Compass",title:"Name the direction you want to protect",description:"Start with the value itself and the life-direction it points toward.",render:(P,y)=>e.jsxs(e.Fragment,{children:[e.jsx(is,{value:P.userId??null,users:t.snapshot.users,onChange:N=>y({userId:N}),defaultLabel:ss(t.snapshot.users.find(N=>N.id===p)??null,"Choose value owner"),help:"Values can belong to a human or bot user while still linking to goals, projects, and tasks across Forge."}),e.jsx(Y,{label:"Value name",children:e.jsx(ie,{value:P.title,onChange:N=>y({title:N.target.value}),placeholder:"Repair with steadiness"})}),e.jsx(Y,{label:"Valued direction",children:e.jsx(ie,{value:P.valuedDirection,onChange:N=>y({valuedDirection:N.target.value}),placeholder:"Warm, brave, and honest connection"})}),e.jsx(Y,{label:"Why it matters",children:e.jsx(Ce,{value:P.whyItMatters,onChange:N=>y({whyItMatters:N.target.value}),placeholder:"Why is this direction important enough to protect when pressure rises?"})})]})},{id:"shape",eyebrow:"Texture",title:"Describe how the value should feel in lived form",description:"Keep this concrete enough that later reports and behaviors can map back to it.",render:(P,y)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Description",children:e.jsx(Ce,{value:P.description,onChange:N=>y({description:N.target.value}),placeholder:"Describe what this value looks like in daily behavior, not just in theory."})}),e.jsx(Y,{label:"Committed action ideas",children:e.jsx(Ce,{value:P.committedActions.join(`
|
|
29
|
+
`),onChange:N=>y({committedActions:N.target.value.split(`
|
|
30
|
+
`).map(A=>A.trim()).filter(Boolean)}),placeholder:`One line per action
|
|
31
|
+
Text your sister before Friday
|
|
32
|
+
Take a ten-minute reset walk`})})]})},{id:"links",eyebrow:"Placement",title:"Place the value into the real system of work",description:"This is where values become graphical anchors across goals, projects, and tasks instead of standalone notes.",render:(P,y)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Linked goals",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:t.snapshot.goals.map(N=>{const A=P.linkedGoalIds.includes(N.id);return e.jsx("button",{type:"button",className:`rounded-full px-2.5 py-2 text-sm transition ${Ki("goal",A)}`,onClick:()=>y({linkedGoalIds:kn(P.linkedGoalIds,N.id)}),children:e.jsx(ke,{kind:"goal",label:N.title,compact:!0,gradient:!1})},N.id)})})}),e.jsx(Y,{label:"Linked projects",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:t.snapshot.dashboard.projects.map(N=>{const A=P.linkedProjectIds.includes(N.id);return e.jsx("button",{type:"button",className:`rounded-full px-2.5 py-2 text-sm transition ${Ki("project",A)}`,onClick:()=>y({linkedProjectIds:kn(P.linkedProjectIds,N.id)}),children:e.jsx(ke,{kind:"project",label:N.title,compact:!0,gradient:!1})},N.id)})})}),e.jsx(Y,{label:"Linked tasks",children:e.jsx("div",{className:"flex max-h-48 flex-wrap gap-2 overflow-y-auto",children:t.snapshot.tasks.slice(0,24).map(N=>{const A=P.linkedTaskIds.includes(N.id);return e.jsx("button",{type:"button",className:`rounded-full px-2.5 py-2 text-sm transition ${Ki("task",A)}`,onClick:()=>y({linkedTaskIds:kn(P.linkedTaskIds,N.id)}),children:e.jsx(ke,{kind:"task",label:N.title,compact:!0,gradient:!1})},N.id)})})})]})}];return m.isLoading?e.jsx(xt,{eyebrow:"Psyche values",title:"Loading value constellation",description:"Hydrating values, linked goals, projects, and tasks."}):m.isError?e.jsx(Oe,{eyebrow:"Psyche values",error:m.error,onRetry:()=>void m.refetch()}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{entityKind:"value",title:e.jsx(_e,{kind:"value",label:"Values",variant:"heading",size:"lg"}),description:"Map values as living anchors. Each one should visibly relate to goals, projects, and tasks so reflection stops feeling separate from the rest of life.",badge:`${h.length} values`,actions:e.jsx(W,{onClick:()=>{d(null),x({...si,userId:p}),r(!0)},children:"Add value"})}),e.jsx(Ht,{}),e.jsx(Ec,{title:"Place values inside the wider life system",description:"Values are not just notes. This constellation shows which directions are already attached to real goals, projects, and concrete tasks.",centerLabel:"Value field",centerValue:`${h.length} mapped`,nodes:k,action:e.jsx(W,{onClick:()=>{d(null),x({...si,userId:p}),r(!0)},children:"Add value"})}),e.jsx(xs,{eyebrow:"Values in context",title:"See why each value matters and where it lives",description:"Each card combines the value narrative with its linked goals, projects, tasks, and committed actions so you can understand the shape immediately.",tone:"mint",className:"scroll-mt-24",children:e.jsx("div",{id:"values-atlas",className:"grid gap-4",children:h.length===0?e.jsx("div",{className:"flex justify-start",children:e.jsx(W,{onClick:()=>{d(null),x({...si,userId:p}),r(!0)},children:"Add value"})}):h.map(P=>{const y=t.snapshot.goals.filter(u=>P.linkedGoalIds.includes(u.id)),N=t.snapshot.dashboard.projects.filter(u=>P.linkedProjectIds.includes(u.id)),A=t.snapshot.tasks.filter(u=>P.linkedTaskIds.includes(u.id)),T=w===P.id,F=Tt(v,"psyche_value",P.id).count;return e.jsxs("div",{"data-psyche-focus-id":P.id,className:`rounded-[26px] border border-white/8 bg-white/[0.04] p-5 transition ${Zi(T)}`,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(_e,{kind:"value",label:P.title,variant:"heading",size:"xl"}),e.jsx("div",{className:"mt-2 text-sm text-[var(--tertiary)]",children:P.valuedDirection})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[P.user?e.jsx($e,{user:P.user,compact:!0}):null,e.jsx(yt,{entityType:"psyche_value",entityId:P.id,count:F}),e.jsx(W,{variant:"secondary",onClick:()=>{d(P),x(Jf(P)),r(!0)},children:"Edit"})]})]}),e.jsx("p",{className:"mt-4 max-w-3xl text-sm leading-7 text-white/60",children:P.description}),e.jsxs("div",{className:"mt-5 grid gap-4 lg:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]",children:[e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Why it matters"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/64",children:P.whyItMatters})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Goals"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:y.length===0?e.jsx("span",{className:"text-sm text-white/44",children:"None linked"}):y.map(u=>e.jsx(ke,{kind:"goal",label:u.title,compact:!0},u.id))})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Projects"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:N.length===0?e.jsx("span",{className:"text-sm text-white/44",children:"None linked"}):N.map(u=>e.jsx(ke,{kind:"project",label:u.title,compact:!0},u.id))})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Tasks"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:A.length===0?e.jsx("span",{className:"text-sm text-white/44",children:"None linked"}):A.slice(0,4).map(u=>e.jsx(ke,{kind:"task",label:u.title,compact:!0},u.id))})]})]})]}),e.jsx("div",{className:"mt-4 grid gap-2 md:grid-cols-2",children:P.committedActions.map(u=>e.jsx("div",{className:"rounded-[18px] bg-[rgba(110,231,183,0.08)] px-4 py-3 text-sm text-white/72",children:u},u))})]},P.id)})})}),e.jsx(it,{open:a,onOpenChange:r,eyebrow:"Value",title:l?"Refine value placement":"Create value",description:"Forge should capture values through guided placement, not a raw admin form.",value:o,onChange:x,steps:S,submitLabel:l?"Save value":"Create value",pending:I.isPending,error:f,onSubmit:async()=>{b(null);const P=oo.safeParse(o);if(!P.success){b("This value still needs a title and valued direction before it can be saved.");return}try{await I.mutateAsync(P.data)}catch(y){b(y instanceof Error?y.message:"Unable to save this value right now.")}}})]})}function Vf(){var f,b;const{t}=at(),s=We(),i=pe({queryKey:["forge-operator-session"],queryFn:Ci}),n=i.isSuccess,a=pe({queryKey:["forge-settings"],queryFn:Wa,enabled:n}),r=Ca({defaultValues:{profile:{operatorName:"",operatorEmail:"",operatorTitle:""},notifications:{goalDriftAlerts:!0,dailyQuestReminders:!0,achievementCelebrations:!0},execution:{maxActiveTasks:2,timeAccountingMode:"split"},themePreference:"obsidian",localePreference:"en"}}),l=async()=>{await Promise.all([s.invalidateQueries({queryKey:["forge-operator-session"]}),s.invalidateQueries({queryKey:["forge-settings"]})])},d=ge({mutationFn:m=>Ld(m),onSuccess:l}),o=ge({mutationFn:yu,onSuccess:async()=>{await l(),await i.refetch()}});c.useEffect(()=>{var m;(m=a.data)!=null&&m.settings&&r.reset(Hh.parse(a.data.settings))},[a.data,r]);const x=(f=a.data)==null?void 0:f.settings;return i.isLoading||a.isLoading?e.jsx(It,{eyebrow:"Settings",title:"Loading settings",description:"Establishing the operator session and fetching current configuration.",columns:2,blocks:6}):i.isError?e.jsx(Oe,{eyebrow:"Settings",error:i.error,onRetry:()=>void i.refetch()}):a.isError||!x?e.jsx(Oe,{eyebrow:"Settings",error:a.error??new Error("Forge returned an empty settings payload."),onRetry:()=>void a.refetch()}):e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(Ke,{title:"Settings",description:"Tune execution policy, timer behaviour, and personal preferences.",badge:`${x.security.integrityScore}% integrity`}),e.jsx(gs,{}),(b=i.data)!=null&&b.session?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-[18px] border border-emerald-400/20 bg-emerald-500/[0.08] px-4 py-3 text-sm text-emerald-100/88",children:[e.jsxs("div",{children:["Operator session active as ",e.jsx("span",{className:"font-medium text-white",children:i.data.session.actorLabel}),"."]}),e.jsx(W,{variant:"secondary",size:"sm",pending:o.isPending,pendingLabel:"Resetting session",onClick:()=>void o.mutateAsync(),children:"Reset operator session"})]}):null,e.jsxs("div",{className:"grid gap-5",children:[e.jsx(se,{children:e.jsxs("form",{className:"grid gap-4",onSubmit:r.handleSubmit(async m=>{await d.mutateAsync(m)}),children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Operator profile"}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Name"}),e.jsx(ie,{...r.register("profile.operatorName")})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Email"}),e.jsx(ie,{...r.register("profile.operatorEmail")})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Title"}),e.jsx(ie,{...r.register("profile.operatorTitle")})]}),e.jsx("div",{className:"mt-2 font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Execution policy"}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,0.75fr)_minmax(0,1.25fr)]",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Maximum active tasks"}),e.jsx(ie,{type:"number",min:1,max:8,...r.register("execution.maxActiveTasks",{valueAsNumber:!0})})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Time accounting mode"}),e.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:[{value:"split",label:"Split",description:"Multitasking divides credited time across active tasks."},{value:"parallel",label:"Parallel",description:"Every active task receives full credited wall time."},{value:"primary_only",label:"Primary only",description:"Only the highlighted task earns credited time during overlap."}].map(m=>e.jsxs("label",{className:"grid gap-2 rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx("input",{type:"radio",value:m.value,...r.register("execution.timeAccountingMode")}),e.jsx("span",{className:"text-white/82",children:m.label})]}),e.jsx("span",{className:"text-sm leading-6 text-white/56",children:m.description})]},m.value))})]})]}),e.jsx("div",{className:"mt-2 font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Notification rules"}),e.jsxs("label",{className:"flex items-center justify-between rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-white/72",children:"Goal drift alerts"}),e.jsx("input",{type:"checkbox",...r.register("notifications.goalDriftAlerts")})]}),e.jsxs("label",{className:"flex items-center justify-between rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-white/72",children:"Daily quest reminders"}),e.jsx("input",{type:"checkbox",...r.register("notifications.dailyQuestReminders")})]}),e.jsxs("label",{className:"flex items-center justify-between rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-white/72",children:"Achievement celebrations"}),e.jsx("input",{type:"checkbox",...r.register("notifications.achievementCelebrations")})]}),e.jsx("div",{className:"mt-2 font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Theme calibration"}),e.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:["obsidian","solar","system"].map(m=>e.jsxs("label",{className:"flex items-center gap-3 rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsx("input",{type:"radio",value:m,...r.register("themePreference")}),e.jsx("span",{className:"text-white/72 capitalize",children:m})]},m))}),e.jsx("div",{className:"mt-2 font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.settings.localeLabel")}),e.jsx("p",{className:"text-sm text-white/58",children:t("common.settings.localeDescription")}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:[{value:"en",label:t("common.settings.localeEnglish")},{value:"fr",label:t("common.settings.localeFrench")}].map(m=>e.jsxs("label",{className:"flex items-center gap-3 rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsx("input",{type:"radio",value:m.value,...r.register("localePreference")}),e.jsx("span",{className:"text-white/72",children:m.label})]},m.value))}),e.jsx(W,{type:"submit",pending:d.isPending,pendingLabel:"Saving settings",children:"Save settings"})]})}),e.jsx(se,{children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Mobile companion"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Pair the native iPhone bridge for HealthKit, background sync, and future watch or location signals."})]}),e.jsx(Le,{to:"/settings/mobile",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 mobile settings"})]})}),e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Security posture"}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Storage mode"}),e.jsx("div",{className:"mt-2 font-display text-2xl text-white",children:x.security.storageMode})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Last audit"}),e.jsx("div",{className:"mt-2 text-white",children:new Date(x.security.lastAuditAt).toLocaleString()})]})]})]})]})]})}const Da=["read","write","insights","rewards.manage","psyche.read","psyche.write","psyche.note","psyche.insight","psyche.mode"],Zf=[{value:"read",label:"Read",description:"Inspect goals, projects, tasks, reviews, and metrics."},{value:"write",label:"Write",description:"Create and update work through the versioned API."},{value:"insights",label:"Insights",description:"Store structured findings, rationale, and feedback."},{value:"rewards.manage",label:"Rewards",description:"Tune reward rules and issue explainable bonus XP grants."},{value:"psyche.read",label:"Psyche read",description:"Read sensitive values, patterns, and trigger analyses."},{value:"psyche.write",label:"Psyche write",description:"Create and update sensitive therapeutic records."},{value:"psyche.note",label:"Psyche note",description:"Create and edit Markdown notes linked to reflective records."},{value:"psyche.insight",label:"Psyche insight",description:"Store therapeutic insights on Psyche entities."},{value:"psyche.mode",label:"Psyche mode",description:"Name, refine, and map mode profiles and guided mode results."}];function Oc(t,s,i){return s==="review"?{...t,preset:s,trustLevel:"trusted",autonomyMode:"approval_required",approvalMode:"approval_by_default",scopes:[...i]}:s==="operator"?{...t,preset:s,trustLevel:"trusted",autonomyMode:"scoped_write",approvalMode:"high_impact_only",scopes:[...Da]}:s==="autonomous"?{...t,preset:s,trustLevel:"autonomous",autonomyMode:"autonomous",approvalMode:"none",scopes:[...Da]}:{...t,preset:s}}function bo(t,s,i){const n={preset:t,label:"Forge Pilot Token",agentLabel:s,agentType:"assistant",description:"Collaborative planning agent.",trustLevel:"trusted",autonomyMode:"scoped_write",approvalMode:"high_impact_only",scopes:[...Da]};return Oc(n,t,i)}function ew({open:t,onOpenChange:s,pending:i=!1,initialPreset:n="operator",defaultAgentLabel:a="OpenClaw",recommendedScopes:r=[...Da],onSubmit:l}){const[d,o]=c.useState(()=>bo(n,a,r)),[x,f]=c.useState(null);c.useEffect(()=>{t&&(o(bo(n,a,r)),f(null))},[t,n,a,r]);const b=[{id:"preset",eyebrow:"Agent token",title:"Choose a starting point for this token",description:"Each preset locks in a sensible trust, autonomy, and approval policy. You can tune any setting in the next steps.",render:(m,h)=>e.jsx(tt,{columns:3,value:m.preset,onChange:p=>h(Oc(m,p,r)),options:[{value:"review",label:"Review-first",description:"Every action waits for your approval. Safe starting point for a new agent you have not yet trusted."},{value:"operator",label:"Full operator",description:"Trusted collaborator with full scopes. High-impact actions still ask for approval."},{value:"autonomous",label:"Autonomous pilot",description:"No approval gates. Use only for agents you have fully verified in a controlled setup."},{value:"custom",label:"Custom",description:"Start from a blank slate and configure every dimension yourself."}]})},{id:"identity",eyebrow:"Agent identity",title:"Name the agent and this token",description:"The agent name appears in logs, approval requests, and audit trails. The token label is for your reference.",render:(m,h)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Agent name",labelHelp:"This label identifies the agent in every log entry, approval notification, and XP attribution. Pick something memorable.",children:e.jsx(ie,{value:m.agentLabel,placeholder:"OpenClaw",onChange:p=>h({agentLabel:p.target.value})})}),e.jsx(Y,{label:"Token label",description:"A short name for this credential — mainly for your reference in the token list.",children:e.jsx(ie,{value:m.label,placeholder:"Forge Pilot Token",onChange:p=>h({label:p.target.value})})}),e.jsxs("div",{className:"grid gap-5 md:grid-cols-2",children:[e.jsx(Y,{label:"Agent type",labelHelp:"Use 'assistant' for interactive agents. Use 'automation' for scripts or scheduled jobs with no conversational layer.",children:e.jsxs("select",{className:"rounded-[14px] bg-white/[0.06] px-3 py-3 text-white",value:m.agentType,onChange:p=>h({agentType:p.target.value}),children:[e.jsx("option",{value:"assistant",children:"assistant"}),e.jsx("option",{value:"automation",children:"automation"}),e.jsx("option",{value:"observer",children:"observer"})]})}),e.jsx(Y,{label:"Description",description:"Optional note about what this agent does.",children:e.jsx(ie,{value:m.description,placeholder:"Collaborative planning agent.",onChange:p=>h({description:p.target.value})})})]})]})},{id:"policy",eyebrow:"Access policy",title:"Set trust level and approval behaviour",description:"These three settings control how much autonomy the agent has and when it needs your sign-off. The preset you chose filled sensible defaults — adjust only if needed.",render:(m,h)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Trust level",labelHelp:"Standard agents are sandboxed readers. Trusted agents can write with policy guardrails. Autonomous agents bypass all trust checks — use with care.",children:e.jsx(tt,{columns:3,value:m.trustLevel,onChange:p=>h({trustLevel:p}),options:[{value:"standard",label:"Standard",description:"Read-only by default, limited write surface."},{value:"trusted",label:"Trusted",description:"Full write surface with policy guardrails active."},{value:"autonomous",label:"Autonomous",description:"All checks bypassed — maximum capability."}]})}),e.jsx(Y,{label:"Autonomy mode",labelHelp:"Approval-required means every mutation is held for review. Scoped write lets the agent act within its scopes. Autonomous skips all gates.",children:e.jsx(tt,{columns:3,value:m.autonomyMode,onChange:p=>h({autonomyMode:p}),options:[{value:"approval_required",label:"Approval required",description:"Every write action queues for your review."},{value:"scoped_write",label:"Scoped write",description:"Acts freely within its assigned scopes."},{value:"autonomous",label:"Autonomous",description:"No gates — full freedom to write."}]})}),e.jsx(Y,{label:"Approval policy",labelHelp:"Controls which actions trigger the approval queue. High-impact-only is the balanced default: routine writes go through, large mutations get reviewed.",children:e.jsx(tt,{columns:3,value:m.approvalMode,onChange:p=>h({approvalMode:p}),options:[{value:"approval_by_default",label:"Approve by default",description:"Everything needs a sign-off unless explicitly exempt."},{value:"high_impact_only",label:"High impact only",description:"Routine writes pass through; high-stakes actions are held."},{value:"none",label:"None",description:"No approval gates — actions execute immediately."}]})})]})},{id:"scopes",eyebrow:"Scopes",title:"Select what this agent can access",description:"Scope selection follows the principle of least privilege — only grant what the agent actually needs. The full operator bundle covers every capability.",render:(m,h)=>e.jsxs(Y,{label:"Capabilities",labelHelp:"Read lets the agent inspect the system. Write lets it create and update work. Rewards and Psyche scopes unlock more sensitive subsystems.",children:[e.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:Zf.map(p=>{const w=m.scopes.includes(p.value);return e.jsxs("button",{type:"button",className:`rounded-[18px] border px-4 py-4 text-left transition ${w?"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/58 hover:bg-white/[0.08]"}`,onClick:()=>{if(w){if(m.scopes.length===1)return;h({scopes:m.scopes.filter(v=>v!==p.value)})}else h({scopes:[...m.scopes,p.value]})},children:[e.jsx("div",{className:"font-medium",children:p.label}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/58",children:p.description})]},p.value)})}),e.jsxs("div",{className:"mt-2 text-xs text-white/40",children:[m.scopes.length," scope",m.scopes.length!==1?"s":""," selected"]})]})}];return e.jsx(it,{open:t,onOpenChange:s,eyebrow:"Agent setup",title:"Issue an agent token",description:"Configure a new agent token step by step. The preset fills sensible defaults — adjust what you need.",value:d,onChange:o,steps:b,submitLabel:"Issue token",pending:i,pendingLabel:"Issuing token…",error:x,onSubmit:async()=>{f(null);const m=Xh.safeParse({label:d.label,agentLabel:d.agentLabel,agentType:d.agentType,description:d.description,trustLevel:d.trustLevel,autonomyMode:d.autonomyMode,approvalMode:d.approvalMode,scopes:d.scopes});if(!m.success){const h=m.error.issues[0];f((h==null?void 0:h.message)??"Check the agent name and at least one scope before issuing.");return}try{await l(m.data),s(!1)}catch(h){f(h instanceof Error?h.message:"Could not issue the token right now.")}}})}function fo(t){return{source:"new",taskId:"",title:"",description:"",owner:t,projectId:"",status:"done",points:40}}function tw({open:t,onOpenChange:s,pending:i=!1,defaultOwner:n="",availableTasks:a=[],availableProjects:r=[],onSubmit:l}){const[d,o]=c.useState(()=>fo(n)),[x,f]=c.useState(null);c.useEffect(()=>{t&&(o(fo(n)),f(null))},[t,n]);const b=[{id:"source",eyebrow:"Log work",title:"Is this work already tracked?",description:"If a task exists, link the work to it so Forge can update the record with the right status and XP. If not, a new task will be created from what you describe.",render:(m,h)=>e.jsxs(e.Fragment,{children:[e.jsx(tt,{columns:2,value:m.source,onChange:p=>h({source:p,taskId:""}),options:[{value:"new",label:"New task",description:"The work is not tracked yet — Forge will create a task and log the time against it."},{value:"existing",label:"Existing task",description:"Pick a task already in the board. The log will update its record and award XP."}]}),m.source==="existing"&&a.length>0?e.jsx(Y,{label:"Pick the task",description:"Select the task this work belongs to.",children:e.jsxs("select",{className:"rounded-[14px] bg-white/[0.06] px-3 py-3 text-white",value:m.taskId,onChange:p=>h({taskId:p.target.value}),children:[e.jsx("option",{value:"",children:"— choose a task —"}),a.map(p=>e.jsxs("option",{value:p.id,children:[p.title," · ",p.status.replaceAll("_"," ")]},p.id))]})}):m.source==="existing"&&a.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm text-white/58",children:'No tasks are loaded yet. Switch to "New task" to create one from scratch.'}):null]})},{id:"details",eyebrow:"Work details",title:"Describe what was done",description:"Give the work a clear title and enough context to understand it later. These become the task record if you are creating a new one.",render:(m,h)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Title",labelHelp:"Write the title like a short achievement: what was completed, not what was started.",children:e.jsx(ie,{value:m.title,placeholder:"Write postmortem draft",onChange:p=>h({title:p.target.value})})}),e.jsx(Y,{label:"Owner",description:"Who did this work? Defaults to the operator name.",children:e.jsx(ie,{value:m.owner,placeholder:"Your name",onChange:p=>h({owner:p.target.value})})}),e.jsx(Y,{label:"Description",description:"What moved forward? What should remain visible in the project history?",children:e.jsx(Ce,{className:"min-h-28",value:m.description,placeholder:"Wrote the full incident timeline and drafted the three key learnings for the team retrospective.",onChange:p=>h({description:p.target.value})})})]})},{id:"placement",eyebrow:"Placement",title:"Set the context and XP value",description:"Assign the work to a project and choose its final status. The XP value controls how much this work contributes to the operator's progress curve.",render:(m,h)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-5 md:grid-cols-2",children:[e.jsx(Y,{label:"Project",description:"Link this work to an active project if it belongs to one.",children:e.jsxs("select",{className:"rounded-[14px] bg-white/[0.06] px-3 py-3 text-white",value:m.projectId,onChange:p=>h({projectId:p.target.value}),children:[e.jsx("option",{value:"",children:"No project link"}),r.map(p=>e.jsx("option",{value:p.id,children:p.title},p.id))]})}),e.jsx(Y,{label:"Final status",labelHelp:"'Done' is the most common choice. Use 'In progress' if the work was real but the task is still open.",children:e.jsx(tt,{columns:2,value:m.status,onChange:p=>h({status:p}),options:[{value:"done",label:"Done",description:"Work is complete."},{value:"in_progress",label:"In progress",description:"Still active but already worth logging."},{value:"focus",label:"Focus",description:"Moved into focus."},{value:"blocked",label:"Blocked",description:"Work hit a wall."}]})})]}),e.jsx(Y,{label:"XP value",labelHelp:"Typical task XP ranges from 20 to 100. Use 40 for routine tasks, 80+ for complex deliverables.",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(ie,{type:"number",min:5,max:500,className:"w-36",value:m.points,onChange:p=>h({points:Number(p.target.value)})}),e.jsx("div",{className:"flex gap-2",children:[20,40,80,120].map(p=>e.jsxs("button",{type:"button",className:`rounded-full px-3 py-1.5 text-xs transition ${m.points===p?"bg-white/18 text-white":"bg-white/[0.06] text-white/55 hover:bg-white/[0.10]"}`,onClick:()=>h({points:p}),children:[p," xp"]},p))})]})})]})}];return e.jsx(it,{open:t,onOpenChange:s,eyebrow:"Log work",title:"Log retroactive work",description:"Capture work that happened outside the timer so it counts toward progress and XP.",value:d,onChange:o,steps:b,submitLabel:"Log work",pending:i,pendingLabel:"Logging work…",error:x,onSubmit:async()=>{if(f(null),d.source==="new"&&d.title.trim().length===0){f("Add a title so Forge knows what work to create.");return}if(d.source==="existing"&&!d.taskId){f("Pick an existing task or switch to New task.");return}try{await l({taskId:d.source==="existing"&&d.taskId?d.taskId:void 0,title:d.source==="new"&&d.title.trim()?d.title.trim():void 0,description:d.description.trim()||void 0,owner:d.owner.trim()||void 0,projectId:d.projectId||null,status:d.status,points:d.points}),s(!1)}catch(m){f(m instanceof Error?m.message:"Could not log the work right now.")}}})}function Fc({text:t}){const[s,i]=c.useState(!1),n=async()=>{try{await navigator.clipboard.writeText(t),i(!0),setTimeout(()=>i(!1),2200)}catch{}};return e.jsxs("button",{type:"button",onClick:()=>void n(),className:"flex items-center gap-1.5 rounded-full bg-white/[0.07] px-3 py-1.5 text-xs font-medium text-white/65 transition hover:bg-white/[0.12] hover:text-white",children:[s?e.jsx(ji,{className:"size-3 text-emerald-400"}):e.jsx(Wo,{className:"size-3"}),s?"Copied":"Copy"]})}function Sn({label:t,children:s,copyText:i}){return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:t}),e.jsx(Fc,{text:i??s})]}),e.jsx("pre",{className:"mt-3 overflow-x-auto rounded-[14px] bg-[rgba(8,13,28,0.78)] p-3 text-xs leading-6 text-white/78",children:e.jsx("code",{children:s})})]})}function sw({open:t,onOpenChange:s,state:i}){if(!i)return null;const{tokenString:n,agentLabel:a,onboarding:r}=i,l=JSON.stringify({baseUrl:r.forgeBaseUrl,apiToken:n,actorLabel:a,timeoutMs:r.defaultTimeoutMs},null,2),d=[`curl -s ${r.healthUrl} \\`,` -H "Authorization: Bearer ${n}" \\`,' -H "X-Forge-Source: agent" \\',` -H "X-Forge-Actor: ${a}"`].join(`
|
|
33
|
+
`),o=["openclaw gateway restart",'openclaw agent --message "forge_get_operator_overview"'].join(`
|
|
34
|
+
`);return e.jsx(Lt,{open:t,onOpenChange:s,children:e.jsxs(Dt,{children:[e.jsx($t,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.82)] backdrop-blur-xl"}),e.jsxs(Ot,{className:"fixed left-1/2 top-1/2 z-50 flex h-[min(52rem,calc(100vh-1rem))] w-[min(52rem,calc(100vw-1.5rem))] -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden rounded-[34px] border border-[rgba(192,193,255,0.14)] bg-[linear-gradient(180deg,rgba(21,28,44,0.99),rgba(12,17,30,0.99))] shadow-[0_30px_90px_rgba(3,8,18,0.55)]",children:[e.jsx(Rt,{className:"sr-only",children:"Token issued — setup instructions"}),e.jsx(Gt,{className:"sr-only",children:"Your new agent token has been issued. Copy it now and follow the setup guide."}),e.jsxs("div",{className:"flex shrink-0 items-start justify-between gap-4 border-b border-white/8 px-6 py-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex size-10 shrink-0 items-center justify-center rounded-full bg-[rgba(192,193,255,0.12)]",children:e.jsx(Qs,{className:"size-5 text-[rgba(192,193,255,0.85)]"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Token issued"}),e.jsx("div",{className:"mt-0.5 font-display text-xl text-white",children:"Save your token now"})]})]}),e.jsx(_t,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":"Close",className:"rounded-full bg-white/6 p-2 text-white/55 transition hover:bg-white/10 hover:text-white",children:e.jsx(mt,{className:"size-4"})})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-5",children:e.jsxs(wt.div,{initial:{opacity:0,y:16},animate:{opacity:1,y:0},transition:{duration:.3,ease:"easeOut"},className:"grid gap-5",children:[e.jsxs("div",{className:"rounded-[20px] border border-amber-400/18 bg-amber-400/[0.07] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{className:"text-amber-300",children:"One-time reveal"}),e.jsx("span",{className:"text-sm text-white/60",children:"This value will not be shown again."})]}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 rounded-[14px] bg-[rgba(8,13,28,0.78)] px-4 py-3",children:[e.jsx("code",{className:"min-w-0 flex-1 break-all text-xs text-white/90",children:n}),e.jsx(Fc,{text:n})]}),e.jsx("div",{className:"mt-2 text-xs text-white/45",children:"Forge stores only a hash — the raw token is unrecoverable after you close this dialog. If lost, rotate the token from the Agents settings page."})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx("div",{className:"flex size-5 items-center justify-center rounded-full bg-white/12 text-xs font-semibold text-white",children:"1"}),e.jsx("span",{className:"text-sm font-medium text-white",children:"Add the token to your OpenClaw plugin config"})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4 text-sm leading-6 text-white/62",children:["Open your ",e.jsx("code",{className:"rounded-md bg-white/[0.08] px-1.5 py-0.5 text-xs text-white/82",children:"openclaw.json"})," file and find the"," ",e.jsx("code",{className:"rounded-md bg-white/[0.08] px-1.5 py-0.5 text-xs text-white/82",children:"forge"})," plugin entry under"," ",e.jsx("code",{className:"rounded-md bg-white/[0.08] px-1.5 py-0.5 text-xs text-white/82",children:"plugins"}),". Add or replace its"," ",e.jsx("code",{className:"rounded-md bg-white/[0.08] px-1.5 py-0.5 text-xs text-white/82",children:"params"})," with the config block below."]}),e.jsx("div",{className:"mt-3",children:e.jsx(Sn,{label:"Plugin params — paste into openclaw.json → plugins → forge → params",copyText:l,children:l})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx("div",{className:"flex size-5 items-center justify-center rounded-full bg-white/12 text-xs font-semibold text-white",children:"2"}),e.jsx("span",{className:"text-sm font-medium text-white",children:"Restart the gateway and confirm the agent can connect"})]}),e.jsx(Sn,{label:"Run in terminal",copyText:o,children:o})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx("div",{className:"flex size-5 items-center justify-center rounded-full bg-white/12 text-xs font-semibold text-white",children:"3"}),e.jsx("span",{className:"text-sm font-medium text-white",children:"Verify the token is accepted by the API"})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4 text-sm leading-6 text-white/62",children:["Run the curl below. A"," ",e.jsx("code",{className:"rounded-md bg-white/[0.08] px-1.5 py-0.5 text-xs text-emerald-300",children:"200 OK"})," response means the token works and the agent"," ",e.jsx("strong",{className:"text-white/80",children:a})," is authenticated."]}),e.jsx("div",{className:"mt-3",children:e.jsx(Sn,{label:"Verify token — run in terminal",copyText:d,children:d})})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/6 bg-white/[0.03] px-4 py-3 text-sm leading-6 text-white/50",children:[e.jsx("strong",{className:"text-white/68",children:"Tip:"})," If you ever lose this token, go to ",e.jsx("strong",{className:"text-white/68",children:"Settings → Agents → Agent tokens"}),", find the entry, and click"," ",e.jsx("strong",{className:"text-white/68",children:"Rotate & reveal"})," to get a fresh value without creating a new agent identity."]})]})}),e.jsx("div",{className:"shrink-0 border-t border-white/8 px-6 py-4",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("div",{className:"text-sm text-white/45",children:"Token saved? Close this dialog when you are ready."}),e.jsxs(W,{onClick:()=>s(!1),children:[e.jsx(ji,{className:"size-4"}),"Done"]})]})})]})]})})}function fa(t,s){return s.every(i=>t.scopes.includes(i))}function iw(){var ee,le,oe,ue,me;const t=We(),[s,i]=c.useState(!1),[n,a]=c.useState("operator"),[r,l]=c.useState(null),[d,o]=c.useState(!1),[x,f]=c.useState(!1),[b,m]=c.useState(!1),h=pe({queryKey:["forge-operator-session"],queryFn:Ci}),p=h.isSuccess,w=pe({queryKey:["forge-settings"],queryFn:Wa,enabled:p}),v=pe({queryKey:["forge-approval-requests"],queryFn:rx,enabled:p}),I=pe({queryKey:["forge-agent-onboarding"],queryFn:nx}),k=pe({queryKey:["forge-operator-context"],queryFn:Kp,enabled:p}),S=async()=>{await Promise.all([t.invalidateQueries({queryKey:["forge-operator-session"]}),t.invalidateQueries({queryKey:["forge-settings"]}),t.invalidateQueries({queryKey:["forge-approval-requests"]}),t.invalidateQueries({queryKey:["forge-agent-onboarding"]}),t.invalidateQueries({queryKey:["forge-operator-context"]})])},M=ge({mutationFn:$=>px($),onSuccess:S}),P=ge({mutationFn:$=>xx($),onSuccess:async($,ce)=>{if(await S(),j){const E=$.token;l({tokenString:E.token,agentLabel:E.tokenSummary.agentLabel??"forge-agent",onboarding:j}),o(!0)}}}),y=ge({mutationFn:$=>gx($),onSuccess:S}),N=ge({mutationFn:$=>lx($),onSuccess:S}),A=ge({mutationFn:$=>ox($),onSuccess:S}),T=ge({mutationFn:Nx,onSuccess:S}),F=(ee=w.data)==null?void 0:ee.settings,u=((le=v.data)==null?void 0:le.approvalRequests)??[],j=(oe=I.data)==null?void 0:oe.onboarding,L=(ue=k.data)==null?void 0:ue.context,q=(F==null?void 0:F.agentTokens.filter($=>$.status==="active"))??[],G=(j==null?void 0:j.recommendedScopes)??[],Q=q.some($=>fa($,G)),ne=q.some($=>fa($,["rewards.manage"])),H=q.some($=>fa($,["psyche.write"])),_=q.some($=>$.autonomyMode!=="approval_required"&&fa($,["write"])),U=q.length>0,R=c.useMemo(()=>{if(!L)return[];const $=[...L.focusTasks,...L.currentBoard.backlog,...L.currentBoard.focus,...L.currentBoard.inProgress,...L.currentBoard.blocked,...L.currentBoard.done],ce=new Map;for(const E of $)ce.set(E.id,E);return[...ce.values()]},[L]),C=(F==null?void 0:F.profile.operatorName)??"",J=[{label:"Operator session",ok:!0,badge:"active",badgeTone:"emerald",detail:(me=h.data)!=null&&me.session?`Session open as ${h.data.session.actorLabel}. Works for localhost and Tailscale without a token.`:"Passwordless session is active for local and Tailscale access.",action:null},{label:"Agent token",ok:U,badge:U?`${q.length} active`:"none issued",badgeTone:U?"emerald":"amber",detail:U?`${q.length} active token${q.length===1?"":"s"} allow external agents and scripts to authenticate.`:"No token yet. Issue one to let external agents connect via the API.",action:U?null:{label:"Issue token",preset:"operator",onClick:()=>{a("operator"),i(!0)}}},{label:"Full operator bundle",ok:Q,badge:Q?"ready":"optional",badgeTone:Q?"emerald":"neutral",detail:Q?"A token covers all recommended scopes for full operator collaboration.":"No token covers the full recommended scope bundle. Issue one to unlock complete agent collaboration.",action:Q?null:{label:"Set up",preset:"operator",onClick:()=>{a("operator"),i(!0)}}},{label:"Reward control",ok:ne,badge:ne?"ready":"optional",badgeTone:ne?"emerald":"neutral",detail:ne?"An agent can tune reward rules and issue bonus XP grants.":"No token has rewards.manage — agents cannot adjust XP rules or issue bonuses.",action:ne?null:{label:"Add scope",preset:"operator",onClick:()=>{a("operator"),i(!0)}}},{label:"Psyche writes",ok:H,badge:H?"ready":"optional",badgeTone:H?"emerald":"neutral",detail:H?"Sensitive Psyche collaboration is enabled — agents can create and update therapeutic records.":"No token has psyche.write — agent collaboration on sensitive Psyche records is disabled.",action:H?null:{label:"Add scope",preset:"operator",onClick:()=>{a("operator"),i(!0)}}},{label:"Scoped writes",ok:_,badge:_?"ready":"optional",badgeTone:_?"emerald":"neutral",detail:_?"A trusted agent can write without constant approval prompts.":"All write tokens are approval-required. Agents must queue every mutation for your review.",action:_?null:{label:"Configure",preset:"operator",onClick:()=>{a("operator"),i(!0)}}}];return h.isLoading||w.isLoading?e.jsx(It,{eyebrow:"Settings · Agents",title:"Loading agent console",description:"Establishing the operator session and loading agent configuration.",columns:2,blocks:6}):h.isError?e.jsx(Oe,{eyebrow:"Settings · Agents",error:h.error,onRetry:()=>void h.refetch()}):w.isError||!F?e.jsx(Oe,{eyebrow:"Settings · Agents",error:w.error??new Error("Could not load settings."),onRetry:()=>void w.refetch()}):e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(Ke,{title:"Agents",description:"Connection status, capability access, tokens, approval queue, and work logging."}),e.jsx(gs,{}),e.jsx(ew,{open:s,onOpenChange:i,pending:M.isPending,initialPreset:n,defaultAgentLabel:(j==null?void 0:j.defaultActorLabel)??"OpenClaw",recommendedScopes:G,onSubmit:async $=>{const ce=await M.mutateAsync($);i(!1),j&&(l({tokenString:ce.token.token,agentLabel:$.agentLabel,onboarding:j}),o(!0))}}),e.jsx(sw,{open:d,onOpenChange:o,state:r}),e.jsx(tw,{open:x,onOpenChange:f,pending:T.isPending,defaultOwner:C,availableTasks:R,availableProjects:(L==null?void 0:L.activeProjects)??[],onSubmit:async $=>{await T.mutateAsync($)}}),e.jsxs("div",{className:"grid gap-5",children:[L?e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsx(ks,{label:"Active projects",value:L.activeProjects.length,tone:"core"}),e.jsx(ks,{label:"Focus tasks",value:L.focusTasks.length,tone:"core"}),e.jsx(ks,{label:"Pending approvals",value:u.filter($=>$.status==="pending").length,tone:"core"}),e.jsx(ks,{label:"Operator level",value:L.xp.profile.level,tone:"core",detail:`${L.xp.profile.totalXp} total XP`})]}):null,e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Capability status"}),e.jsx("div",{className:"mt-4 grid gap-3",children:J.map($=>e.jsxs("div",{className:"flex items-start justify-between gap-4 rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"font-medium text-white",children:$.label}),e.jsx(O,{className:$.badgeTone==="emerald"?"text-emerald-300":$.badgeTone==="amber"?"text-amber-300":"text-white/45",children:$.badge})]}),e.jsx("div",{className:"mt-1 text-sm leading-6 text-white/55",children:$.detail})]}),$.action?e.jsxs("button",{type:"button",onClick:$.action.onClick,className:"mt-0.5 flex shrink-0 items-center gap-1.5 rounded-full bg-white/[0.07] px-3 py-1.5 text-xs font-medium text-white/72 transition hover:bg-white/[0.12] hover:text-white",children:[$.action.label,e.jsx(Gs,{className:"size-3"})]}):null]},$.label))})]}),e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Agent tokens"}),e.jsxs(W,{size:"sm",variant:"secondary",onClick:()=>{a("operator"),i(!0)},children:[e.jsx(Wt,{className:"size-3.5"}),"Issue token"]})]}),e.jsx("div",{className:"mt-4 grid gap-3",children:F.agentTokens.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4 text-sm text-white/55",children:"No tokens yet. Issue one to let external agents or scripts authenticate with Forge."}):F.agentTokens.map($=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-white",children:$.label}),e.jsxs("div",{className:"mt-0.5 text-sm text-white/50",children:[$.agentLabel??"Unassigned agent"," ·"," ",e.jsx("span",{className:"font-mono text-xs",children:$.tokenPrefix})]})]}),e.jsx(O,{className:$.status==="active"?"text-emerald-300":"text-white/45",children:$.status})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-xs text-white/55",children:[e.jsx("span",{children:$.trustLevel}),e.jsx("span",{children:"·"}),e.jsx("span",{children:$.autonomyMode.replaceAll("_"," ")}),e.jsx("span",{children:"·"}),e.jsx("span",{children:$.approvalMode.replaceAll("_"," ")})]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-1.5",children:["write","rewards.manage","psyche.write"].map(ce=>e.jsx(O,{className:$.scopes.includes(ce)?"text-emerald-300":"text-white/30",children:ce},ce))}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(W,{variant:"secondary",size:"sm",pending:P.isPending,pendingLabel:"Rotating",onClick:()=>void P.mutateAsync($.id),children:"Rotate & reveal new token"}),e.jsx(W,{variant:"ghost",size:"sm",pending:y.isPending,pendingLabel:"Revoking",onClick:()=>void y.mutateAsync($.id),children:"Revoke"})]})]},$.id))}),e.jsx("div",{className:"mt-3 px-1 text-xs text-white/35",children:"Raw token values are shown once and are never recoverable. If a token is lost, rotate or issue a new one."})]}),F.agents.length>0?e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Connected agents"}),e.jsx("div",{className:"mt-4 grid gap-3",children:F.agents.map($=>e.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-[18px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-white",children:$.label}),$.description?e.jsx("div",{className:"mt-1 text-sm text-white/52",children:$.description}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap gap-x-4 gap-y-1 text-sm text-white/55",children:[e.jsx("span",{children:$.agentType}),e.jsx("span",{children:$.autonomyMode.replaceAll("_"," ")}),e.jsxs("span",{children:[$.activeTokenCount," active token",$.activeTokenCount!==1?"s":""]})]})]}),e.jsx(O,{className:"text-white/60",children:$.trustLevel})]},$.id))})]}):null,L?e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1.05fr)_minmax(0,0.95fr)]",children:[e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Recommended next move"}),L.recommendedNextTask?e.jsxs("div",{className:"mt-4 grid gap-2",children:[e.jsx(_e,{kind:"task",label:L.recommendedNextTask.title,variant:"heading",size:"lg"}),e.jsx("div",{className:"text-sm leading-6 text-white/58",children:L.recommendedNextTask.description||"No extra notes yet."}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-2",children:[e.jsx(O,{children:L.recommendedNextTask.status.replaceAll("_"," ")}),e.jsxs(O,{children:[L.recommendedNextTask.points," xp"]}),e.jsx(O,{children:L.recommendedNextTask.owner})]})]}):e.jsx("div",{className:"mt-4 text-sm text-white/55",children:"Board is clear. No recommended task right now."})]}),e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Board pulse"}),e.jsx("div",{className:"mt-4 grid grid-cols-2 gap-3",children:[{label:"Backlog",value:L.currentBoard.backlog.length},{label:"Focus",value:L.currentBoard.focus.length},{label:"In progress",value:L.currentBoard.inProgress.length},{label:"Blocked",value:L.currentBoard.blocked.length}].map($=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/38",children:$.label}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:$.value})]},$.label))})]})]}):null,L&&L.activeProjects.length>0?e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Active projects"}),e.jsx("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:L.activeProjects.slice(0,6).map($=>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.jsx(_e,{kind:"project",label:$.title}),e.jsxs(O,{children:[$.progress,"%"]})]}),e.jsx("div",{className:"mt-2",children:e.jsx(ke,{kind:"goal",label:$.goalTitle,compact:!0,gradient:!1})}),e.jsxs("div",{className:"mt-2 text-xs text-white/38",children:[$.activeTaskCount," active ·"," ",$.completedTaskCount," done"]})]},$.id))})]}):null,e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Approval queue"}),u.filter($=>$.status==="pending").length>0?e.jsxs(O,{className:"text-amber-300",children:[u.filter($=>$.status==="pending").length," pending"]}):null]}),e.jsx("div",{className:"mt-4 grid gap-3",children:u.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4 text-sm text-white/55",children:"No pending approvals. Agent actions are flowing through."}):u.map($=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-white",children:$.title}),e.jsx("div",{className:"mt-0.5 text-sm text-white/55",children:$.summary||$.actionType})]}),e.jsx(O,{className:$.status==="pending"?"text-amber-300":"text-white/45",children:$.status})]}),$.status==="pending"?e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(W,{variant:"secondary",size:"sm",pending:N.isPending,pendingLabel:"Approving",onClick:()=>void N.mutateAsync($.id),children:"Approve"}),e.jsx(W,{variant:"ghost",size:"sm",pending:A.isPending,pendingLabel:"Rejecting",onClick:()=>void A.mutateAsync($.id),children:"Reject"})]}):null]},$.id))})]}),e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Retroactive work log"}),e.jsx("div",{className:"mt-1 text-sm text-white/55",children:"Capture work done outside the timer so it counts toward progress and XP."})]}),e.jsxs(W,{variant:"secondary",size:"sm",onClick:()=>f(!0),children:[e.jsx(Ym,{className:"size-3.5"}),"Log work"]})]}),T.data?e.jsxs("div",{className:"mt-4 rounded-[18px] bg-[rgba(192,193,255,0.10)] px-4 py-3 text-sm text-white",children:["Logged"," ",e.jsx("span",{className:"inline-block align-middle",children:e.jsx(_e,{kind:"task",label:T.data.task.title,showKind:!1})}),". Operator XP updated to ",T.data.xp.profile.totalXp,"."]}):null]}),e.jsxs(se,{children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-4 text-left",onClick:()=>m($=>!$),children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Connection & onboarding"}),j?e.jsx("div",{className:"mt-1 text-sm text-white/55",children:j.forgeBaseUrl}):null]}),b?e.jsx(_a,{className:"size-4 shrink-0 text-white/38"}):e.jsx(Si,{className:"size-4 shrink-0 text-white/38"})]}),b&&j?e.jsxs("div",{className:"mt-5 grid gap-4",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Forge API"}),e.jsx("div",{className:"mt-2 break-all text-sm text-white",children:j.forgeBaseUrl})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Web app"}),e.jsx("div",{className:"mt-2 break-all text-sm text-white",children:j.webAppUrl})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"OpenAPI spec"}),e.jsx("div",{className:"mt-2 break-all text-sm text-white",children:j.openApiUrl})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Default policy"}),e.jsxs("div",{className:"mt-2 text-sm text-white",children:[j.recommendedTrustLevel," ·"," ",j.recommendedAutonomyMode.replaceAll("_"," ")," ·"," ",j.recommendedApprovalMode.replaceAll("_"," ")]})]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:j.authModes.operatorSession.label}),e.jsx(O,{className:"mt-1 text-emerald-300",children:j.defaultConnectionMode==="operator_session"?"default":"available"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:j.authModes.operatorSession.summary}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:j.authModes.operatorSession.trustedTargets.map($=>e.jsx(O,{className:"text-white/65",children:$},$))})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:j.authModes.managedToken.label}),e.jsx(O,{className:"mt-1 text-white/55",children:"optional"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:j.authModes.managedToken.summary}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/48",children:j.tokenRecovery.rotationSummary})]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Shared runtime"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:"Keep Forge, OpenClaw, Hermes, and the browser on the same runtime when they should see one shared user directory, one strategy graph, and one task history."}),e.jsxs("div",{className:"mt-3 text-xs leading-5 text-white/46",children:["Base URL: ",j.forgeBaseUrl]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Agent identity"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:"Create each agent as a bot user, then write with that user's `userId`. The relationship graph in Settings -> Users controls what each direction can see, message, share, plan, and affect."}),e.jsx("div",{className:"mt-3 text-xs leading-5 text-white/46",children:"Cross-owner links stay valid even when ownership differs."})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Contract timing"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:"Leave strategies editable while humans and bots refine the graph. Lock them only when the plan becomes the contract the alignment metrics should judge."}),e.jsx("div",{className:"mt-3 text-xs leading-5 text-white/46",children:"Coverage, sequencing, scope discipline, and quality all contribute to alignment now."})]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Fast onboarding checklist"}),e.jsxs("div",{className:"mt-3 grid gap-2 text-sm leading-6 text-white/60",children:[e.jsx("div",{children:"1. Create the human and bot users in Settings -> Users."}),e.jsx("div",{children:"2. Keep the default graph permissive until collaboration is flowing cleanly."}),e.jsx("div",{children:"3. Point OpenClaw and Hermes at the same Forge runtime and storage root when they should collaborate."}),e.jsx("div",{children:"4. Give each adapter a distinct actor label so activity stays readable."}),e.jsx("div",{children:"5. Build strategies as drafts first, then lock when the plan is ready to become the contract."})]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Rights language"}),e.jsxs("div",{className:"mt-3 grid gap-2 text-sm leading-6 text-white/60",children:[e.jsx("div",{children:"`See` means discover, search, and read another owner."}),e.jsx("div",{children:"`Message` means coordinate and hand off through Forge."}),e.jsx("div",{children:"`Plan` means draft or edit that owner's strategies."}),e.jsx("div",{children:"`Affect` means create or mutate that owner's work."})]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Strategy lifecycle"}),e.jsxs("div",{className:"mt-3 grid gap-2 text-sm leading-6 text-white/60",children:[e.jsx("div",{children:"1. Save an incomplete draft while the plan is still being negotiated."}),e.jsx("div",{children:"2. Let humans and bots refine targets, nodes, and sequence together."}),e.jsx("div",{children:"3. Lock only when the graph becomes the contract for alignment."}),e.jsx("div",{children:"4. Unlock only when the contract itself is being renegotiated."})]})]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Quick-connect verification"}),e.jsx("pre",{className:"mt-3 overflow-x-auto rounded-[16px] bg-[rgba(8,13,28,0.78)] p-4 text-xs leading-6 text-white/72",children:e.jsx("code",{children:[`curl -s ${j.healthUrl}`,"openclaw plugins install ./projects/forge","openclaw gateway restart"].join(`
|
|
35
|
+
`)})})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Required API headers"}),e.jsxs("div",{className:"mt-3 grid gap-1 text-sm text-white/60",children:[e.jsx("div",{children:j.requiredHeaders.authorization}),e.jsx("div",{children:j.requiredHeaders.source}),e.jsx("div",{children:j.requiredHeaders.actor})]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:[j.connectionGuides.openclaw,j.connectionGuides.hermes].map($=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:$.label}),e.jsx("div",{className:"mt-3 grid gap-2 text-sm leading-6 text-white/60",children:$.installSteps.map(ce=>e.jsx("div",{children:ce},ce))}),e.jsx("pre",{className:"mt-4 overflow-x-auto rounded-[16px] bg-[rgba(8,13,28,0.78)] p-4 text-xs leading-6 text-white/72",children:e.jsx("code",{children:$.verifyCommands.join(`
|
|
36
|
+
`)})}),e.jsx("div",{className:"mt-3 grid gap-1 text-sm leading-6 text-white/48",children:$.configNotes.map(ce=>e.jsx("div",{children:ce},ce))})]},$.label))}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Multi-user model"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:j.multiUserModel.summary}),e.jsx("div",{className:"mt-3 grid gap-1 text-sm leading-6 text-white/48",children:j.multiUserModel.routeScoping.map($=>e.jsx("div",{children:$},$))})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Strategy contracts"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:j.strategyContractModel.lockSummary}),e.jsx("div",{className:"mt-3 grid gap-1 text-sm leading-6 text-white/48",children:j.strategyContractModel.metricBreakdown.map($=>e.jsx("div",{children:$},$))})]})]})]}):b&&I.isError?e.jsx("div",{className:"mt-4 rounded-[18px] bg-[rgba(120,33,33,0.22)] px-4 py-3 text-sm text-rose-100/80",children:"Could not load the onboarding contract. Check the API bridge."}):b?e.jsx("div",{className:"mt-4 text-sm text-white/50",children:"Loading…"}):null]})]})]})}const Rs={goal:"Goals",project:"Projects",task:"Tasks",strategy:"Strategies",habit:"Habits",tag:"Tags",note:"Notes",insight:"Insights",psyche_value:"Values",behavior_pattern:"Patterns",behavior:"Behaviors",belief_entry:"Beliefs",mode_profile:"Modes",mode_guide_session:"Mode guides",event_type:"Event types",emotion_definition:"Emotions",trigger_report:"Reports",calendar_event:"Calendar events",work_block_template:"Work blocks",task_timebox:"Timeboxes"},aw={goal:"goal",project:"project",task:"task",strategy:"strategy",habit:"habit",tag:null,note:null,insight:"report",psyche_value:"value",behavior_pattern:"pattern",behavior:"behavior",belief_entry:"belief",mode_profile:"mode",mode_guide_session:"mode",event_type:null,emotion_definition:null,trigger_report:"report",calendar_event:null,work_block_template:null,task_timebox:null};function nw(t){return new Date(t).toLocaleString()}function rw(){var M,P;const t=We(),[s,i]=c.useState(""),[n,a]=c.useState([]),r=pe({queryKey:["forge-operator-session"],queryFn:Ci}),l=r.isSuccess,d=pe({queryKey:["forge-settings-bin"],queryFn:ax,enabled:l}),o=async()=>{await t.invalidateQueries({predicate:y=>Array.isArray(y.queryKey)&&typeof y.queryKey[0]=="string"&&y.queryKey[0].startsWith("forge-")})},x=ge({mutationFn:y=>gl({operations:[{entityType:y.entityType,id:y.entityId}]}),onSuccess:o}),f=ge({mutationFn:y=>xl({operations:[{entityType:y.entityType,id:y.entityId,mode:"hard"}]}),onSuccess:o}),b=ge({mutationFn:y=>gl({operations:y.map(N=>({entityType:N.entityType,id:N.entityId}))}),onSuccess:o}),m=ge({mutationFn:y=>xl({operations:y.map(N=>({entityType:N.entityType,id:N.entityId,mode:"hard"}))}),onSuccess:o}),h=((M=d.data)==null?void 0:M.bin.records)??[],p=s.trim().toLowerCase(),w=c.useMemo(()=>h.filter(y=>n.length===0||n.includes(y.entityType)?p?[y.title,y.subtitle??"",y.entityType,y.entityId,y.deletedByActor??"",y.deletedSource??"",y.deleteReason??""].join(" ").toLowerCase().includes(p):!0:!1),[p,h,n]),v=c.useMemo(()=>{const y=new Map;for(const N of w){const A=y.get(N.entityType)??[];A.push(N),y.set(N.entityType,A)}return[...y.entries()].sort((N,A)=>Rs[N[0]].localeCompare(Rs[A[0]]))},[w]),I=c.useMemo(()=>[...new Set(h.map(y=>y.entityType))].sort((y,N)=>Rs[y].localeCompare(Rs[N])),[h]);function k(y){a(N=>N.includes(y)?N.filter(A=>A!==y):[...N,y])}async function S(){w.length===0||!window.confirm(`Permanently delete ${w.length} item${w.length===1?"":"s"} from the bin? This cannot be undone.`)||await m.mutateAsync(w)}return r.isLoading||d.isLoading?e.jsx(It,{eyebrow:"Settings",title:"Loading bin",description:"Loading deleted items and restore controls.",columns:2,blocks:6}):r.isError?e.jsx(Oe,{eyebrow:"Settings",error:r.error,onRetry:()=>void r.refetch()}):d.isError?e.jsx(Oe,{eyebrow:"Settings",error:d.error,onRetry:()=>void d.refetch()}):e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(Ke,{title:"Bin",description:"Restore soft-deleted items or permanently remove them when you really mean it.",badge:`${((P=d.data)==null?void 0:P.bin.totalCount)??0} deleted items`}),e.jsx(gs,{}),e.jsxs(se,{className:"grid gap-4",children:[e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-start",children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Find deleted items"}),e.jsxs("div",{className:"relative",children:[e.jsx(dt,{className:"pointer-events-none absolute left-4 top-1/2 size-4 -translate-y-1/2 text-white/35"}),e.jsx(ie,{value:s,onChange:y=>i(y.target.value),placeholder:"Search title, id, reason, or source",className:"pl-11"})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:I.map(y=>{const N=n.includes(y);return e.jsx("button",{type:"button",onClick:()=>k(y),className:re("rounded-full border px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] transition",N?"border-[var(--primary)]/30 bg-[var(--primary)]/[0.16] text-[var(--primary)]":"border-white/10 bg-white/[0.04] text-white/58 hover:bg-white/[0.08] hover:text-white"),children:Rs[y]},y)})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 lg:max-w-[22rem] lg:justify-end",children:[e.jsxs(W,{variant:"secondary",size:"sm",disabled:w.length===0,pending:b.isPending,pendingLabel:"Restoring",onClick:()=>void b.mutateAsync(w),children:[e.jsx(En,{className:"size-4"}),e.jsx("span",{children:"Restore visible"})]}),e.jsxs(W,{variant:"secondary",size:"sm",disabled:w.length===0,pending:m.isPending,pendingLabel:"Deleting",onClick:()=>void S(),children:[e.jsx(bt,{className:"size-4"}),e.jsx("span",{children:"Delete visible forever"})]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-sm text-white/55",children:[e.jsxs("span",{children:[w.length," visible"]}),n.length>0?e.jsxs("span",{children:[n.length," type filters active"]}):null,p?e.jsxs("span",{children:["Search: “",s.trim(),"”"]}):null]})]}),h.length===0?e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Deleted items"}),e.jsx("div",{className:"mt-4 text-white/72",children:"Nothing is in the bin right now."})]}):v.length===0?e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Deleted items"}),e.jsx("div",{className:"mt-4 text-white/72",children:"No deleted items match the current search or filters."})]}):e.jsx("div",{className:"grid gap-5",children:v.map(([y,N])=>{const A=aw[y];return e.jsxs(se,{children:[e.jsx("div",{className:"flex flex-wrap items-center justify-between gap-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[A?e.jsx(ke,{kind:A,label:Rs[y],compact:!0}):null,A?null:e.jsx("div",{className:"rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] uppercase tracking-[0.16em] text-white/55",children:Rs[y]}),e.jsxs("div",{className:"text-sm text-white/55",children:[N.length," deleted"]})]})}),e.jsx("div",{className:"mt-4 grid gap-3",children:N.map(T=>e.jsxs("div",{className:"grid gap-3 rounded-[22px] border border-white/8 bg-white/[0.04] p-4 lg:grid-cols-[minmax(0,1fr)_auto]",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-lg font-medium text-white",children:T.title}),T.subtitle?e.jsx("div",{className:"mt-1 text-sm text-white/62",children:T.subtitle}):null,e.jsxs("div",{className:"mt-3 flex flex-wrap gap-3 text-xs text-white/45",children:[e.jsxs("span",{children:["Deleted ",nw(T.deletedAt)]}),T.deletedByActor?e.jsxs("span",{children:["By ",T.deletedByActor]}):null,T.deletedSource?e.jsxs("span",{children:["Source ",T.deletedSource]}):null,T.deleteReason?e.jsxs("span",{children:["Reason: ",T.deleteReason]}):null]})]}),e.jsxs("div",{className:"flex flex-wrap items-start justify-end gap-2",children:[e.jsxs(W,{variant:"secondary",size:"sm",pending:x.isPending,pendingLabel:"Restoring",onClick:()=>void x.mutateAsync(T),children:[e.jsx(En,{className:"size-4"}),e.jsx("span",{children:"Restore"})]}),e.jsxs(W,{variant:"secondary",size:"sm",pending:f.isPending,pendingLabel:"Deleting",onClick:()=>void f.mutateAsync(T),children:[e.jsx(bt,{className:"size-4"}),e.jsx("span",{children:"Delete forever"})]})]})]},`${T.entityType}:${T.entityId}`))})]},y)})})]})}const wo=[{title:"Before you connect anything",description:"Forge mirrors provider events into Forge. Writable providers can also publish work blocks plus owned timeboxes into a dedicated calendar named Forge, while Exchange Online stays read-only for now.",bullets:["Google uses OAuth client credentials plus a refresh token.","Apple Calendar starts from https://caldav.icloud.com and autodiscovers the real principal plus calendar collections for you.","Exchange Online uses Microsoft Graph with a guided local public-client Microsoft sign-in flow and mirrors the calendars you select into Forge.","Custom CalDAV uses one account-level base URL, then Forge discovers the writable calendars before you choose what to mirror.","Read-only .ics feeds are not enough for writable-provider flows because Forge needs write access for work blocks and task timeboxes."],icon:rs,links:[]},{title:"Google Calendar setup",description:"Use Google Cloud to enable Calendar access, mint a refresh token, then let Forge discover the calendars available to that account.",bullets:["Open Google Cloud credentials and create or reuse an OAuth client.","Enable the Calendar API for the same project.","Generate a refresh token with Google Calendar scopes.","Paste the email, client ID, client secret, and refresh token into Forge.","Forge will discover the calendars, let you choose which calendars to mirror, and create or reuse Forge as the write calendar."],icon:Qs,links:[{label:"Google Cloud credentials",href:"https://console.cloud.google.com/apis/credentials"},{label:"Calendar API quickstart",href:"https://developers.google.com/workspace/calendar/api/quickstart"},{label:"OAuth Playground",href:"https://developers.google.com/oauthplayground"}]},{title:"Apple Calendar setup",description:"Apple does not require you to paste raw calendar collection URLs into Forge. Start with your Apple ID email, an app-specific password, and the iCloud CalDAV base URL.",bullets:["Create an Apple app-specific password for third-party calendar access.","Open Forge settings and choose Apple Calendar.","Enter the Apple ID email and the app-specific password. Forge uses https://caldav.icloud.com for autodiscovery.","After discovery, choose which calendars Forge should mirror.","If a calendar named Forge already exists, Forge will preselect it as the write calendar. Otherwise you can ask Forge to create it for you."],icon:Kn,links:[{label:"Apple app-specific passwords",href:"https://support.apple.com/en-us/102654"},{label:"Use iCloud Calendar with third-party apps",href:"https://support.apple.com/guide/icloud/set-up-calendar-mmfc0f2442/icloud"}]},{title:"Exchange Online setup",description:"Use Microsoft Graph for Microsoft 365 or Exchange Online calendars. In self-hosted local Forge, the user first saves a Microsoft public client ID, tenant, and redirect URI in Settings -> Calendar, then completes a guided local sign-in flow with PKCE. The connection is still read-only in Forge today.",bullets:["Open Microsoft Entra App registrations and create or reuse an app for this local Forge instance.","Choose a supported account type that matches your self-hosted use case. Use a broad multi-account setup when Forge should work with normal personal or organizational Microsoft sign-ins.","Enable mobile and desktop or public client flow support for that app registration.","Add Forge's callback URI to the redirect URI list. The default local callback is http://127.0.0.1:4317/api/v1/calendar/oauth/microsoft/callback.","Add delegated Graph permissions for User.Read and Calendars.Read, then grant or request consent as required by the tenant.","Open Forge Settings -> Calendar and save the Microsoft client ID, tenant value, and redirect URI in the Exchange Online setup card.","Use Test Microsoft configuration to confirm Forge can launch the local sign-in flow.","Click Sign in with Microsoft, complete the popup flow, and then choose which Exchange Online calendars Forge should mirror."],icon:Qs,links:[{label:"Microsoft Graph permissions",href:"https://learn.microsoft.com/en-us/graph/permissions-reference"},{label:"Microsoft identity platform",href:"https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow"},{label:"Microsoft Graph calendar overview",href:"https://learn.microsoft.com/en-us/graph/api/resources/calendar?view=graph-rest-1.0"}]},{title:"Custom CalDAV setup",description:"Use this path for Nextcloud, Fastmail, Baikal, DAViCal, and other CalDAV-compatible providers that expose an account-level base URL.",bullets:["Confirm the provider supports CalDAV, not just an .ics export.","Gather the account-level CalDAV server URL, username, and password or app password.","Open Forge settings and choose Custom CalDAV.","Forge discovers the available calendars from that base URL before anything is saved.","Choose which calendars to mirror and either select an existing Forge calendar or let Forge create one automatically."],icon:rs,links:[]}];function lw(t){if(!t)return wo;const s=t==="google"?"Google Calendar setup":t==="apple"?"Apple Calendar setup":t==="microsoft"?"Exchange Online setup":"Custom CalDAV setup";return wo.filter(i=>i.title==="Before you connect anything"||i.title===s)}function ow({section:t,compact:s}){const i=t.icon;return e.jsxs(se,{className:s?"grid gap-3 rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))] p-4":"grid gap-4 rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-[18px] bg-[var(--primary)]/14 p-3 text-[var(--primary)]",children:e.jsx(i,{className:s?"size-4":"size-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:s?"font-medium text-white":"font-display text-[1.15rem] text-white",children:t.title}),e.jsx("p",{className:s?"mt-1.5 text-sm leading-6 text-white/62":"mt-2 max-w-3xl text-sm leading-6 text-white/62",children:t.description})]})]}),e.jsx("div",{className:s?"grid gap-1.5":"grid gap-2",children:t.bullets.map(n=>e.jsx("div",{className:s?"rounded-[16px] bg-white/[0.04] px-3 py-2.5 text-sm leading-6 text-white/70":"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/72",children:n},n))}),t.links.length>0?e.jsx("div",{className:"flex flex-wrap gap-2",children:t.links.map(n=>e.jsxs("a",{href:n.href,target:"_blank",rel:"noreferrer",className:"inline-flex min-h-10 items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white/74 transition hover:bg-white/[0.08] hover:text-white",children:[e.jsx(Ia,{className:"size-3.5"}),n.label]},n.href))}):null]})}function dw({provider:t,compact:s=!1}){const i=lw(t);return e.jsx("div",{className:"grid gap-4",children:i.map(n=>e.jsx(ow,{section:n,compact:s},n.title))})}const $a={google:{label:"Primary Google",serverUrl:""},apple:{label:"Primary Apple",serverUrl:"https://caldav.icloud.com"},microsoft:{label:"Primary Exchange Online",serverUrl:""},caldav:{label:"Primary CalDAV",serverUrl:"https://caldav.example.com"}};function Cn(t){return{provider:t,label:$a[t].label,serverUrl:$a[t].serverUrl,username:"",password:"",clientId:"",clientSecret:"",refreshToken:"",selectedCalendarUrls:[],forgeCalendarUrl:null,createForgeCalendar:!1}}function ii(t,s){const i=s.trim();return i.length>0?i:$a[t].label}function cw({open:t,onOpenChange:s,initialProvider:i="google",initialStepId:n,microsoftSetup:a,onSubmit:r,pending:l=!1}){const[d,o]=c.useState(()=>Cn(i)),[x,f]=c.useState(null),[b,m]=c.useState(null),[h,p]=c.useState(null),w=c.useRef(null),v=()=>{p(null),w.current=null},I=y=>{m(y);const N=y.calendars.filter(T=>T.selectedByDefault).map(T=>T.url),A=y.calendars.find(T=>T.isForgeCandidate);o(T=>({...T,selectedCalendarUrls:T.selectedCalendarUrls.length>0?T.selectedCalendarUrls.filter(F=>y.calendars.some(u=>u.url===F)):N,forgeCalendarUrl:T.provider==="microsoft"?null:(A==null?void 0:A.url)??T.forgeCalendarUrl??null,createForgeCalendar:T.provider==="microsoft"?!1:T.createForgeCalendar&&!A})),f(null)};c.useEffect(()=>{var y;if(!t){(y=w.current)==null||y.close(),w.current=null;return}f(null),m(null),o(Cn(i)),v()},[i,t]),c.useEffect(()=>{if(!t||!h||h.status!=="pending")return;const y=A=>{var T,F;A.origin===window.location.origin&&(((T=A.data)==null?void 0:T.type)!=="forge:microsoft-calendar-auth"||((F=A.data)==null?void 0:F.sessionId)!==h.sessionId||S(h.sessionId))},N=window.setInterval(()=>{!w.current||!w.current.closed||(w.current=null,S(h.sessionId,{afterPopupClose:!0}))},400);return window.addEventListener("message",y),()=>{window.removeEventListener("message",y),window.clearInterval(N)}},[h,t]);const k=ge({mutationFn:()=>d.provider==="google"?dn({provider:"google",username:d.username,clientId:d.clientId,clientSecret:d.clientSecret,refreshToken:d.refreshToken}):d.provider==="apple"?dn({provider:"apple",username:d.username,password:d.password}):dn({provider:"caldav",serverUrl:d.serverUrl,username:d.username,password:d.password}),onSuccess:({discovery:y})=>{I(y)},onError:y=>{m(null),f(y instanceof Error?y.message:"Forge could not discover calendars with these credentials.")}}),S=async(y,N)=>{try{const{session:A}=await vp(y);if(p(A),A.status==="authorized"&&A.discovery){I(A.discovery),f(null);return}if(A.status==="error"||A.status==="expired"){f(A.error??"Microsoft sign-in did not complete. Start the guided sign-in again.");return}N!=null&&N.afterPopupClose&&f("The Microsoft sign-in window closed before Forge received permission.")}catch(A){f(A instanceof Error?A.message:"Forge could not confirm the Microsoft sign-in session.")}},M=async()=>{var y;try{if(!a.isReadyForSignIn)throw new Error("Finish the Microsoft setup in Settings -> Calendar before starting sign-in.");f(null),m(null);const{session:N}=await fp({label:ii("microsoft",d.label)});if(!N.authUrl)throw new Error("Forge could not prepare the Microsoft sign-in URL.");if(p(N),(y=w.current)==null||y.close(),w.current=window.open(N.authUrl,"forge-microsoft-calendar-auth","popup=yes,width=520,height=720,resizable=yes,scrollbars=yes"),!w.current)throw new Error("The Microsoft sign-in popup was blocked. Allow popups for Forge and try again.");w.current.focus()}catch(N){v(),f(N instanceof Error?N.message:"Forge could not start the Microsoft sign-in flow.")}},P=c.useMemo(()=>[{id:"provider",eyebrow:"Connection",title:"Choose the calendar provider Forge should connect to",description:"Apple uses autodiscovery from caldav.icloud.com, Google uses CalDAV over OAuth, Exchange Online uses guided Microsoft sign-in in read-only mode, and custom CalDAV stays available for everything else.",render:(y,N)=>e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Y,{label:"Provider",description:"Each setup path is guided. Forge discovers calendars before anything is saved.",children:e.jsx(tt,{value:y.provider,onChange:A=>{m(null),f(null),v(),N(Cn(A))},options:[{value:"google",label:"Google Calendar",description:"Discover calendars from Google CalDAV using your OAuth refresh token."},{value:"apple",label:"Apple Calendar",description:"Start from https://caldav.icloud.com and autodiscover calendars with your app password."},{value:"microsoft",label:"Exchange Online",description:"Save the Microsoft app registration fields in Settings, then sign in with Microsoft and mirror selected Exchange Online calendars in read-only mode."},{value:"caldav",label:"Custom CalDAV",description:"Use a CalDAV base URL for Nextcloud, Fastmail, Baikal, and other compatible providers."}]})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 text-white",children:[e.jsx(Vm,{className:"size-4 text-[var(--primary)]"}),e.jsx("div",{className:"font-medium",children:"Dedicated write calendar"})]}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/60",children:y.provider==="microsoft"?"Exchange Online is read-only for now. Forge mirrors selected calendars into Forge, but it does not publish work blocks or owned timeboxes back to Microsoft.":e.jsxs(e.Fragment,{children:["Forge writes work blocks and owned timeboxes into a dedicated calendar named ",e.jsx("span",{className:"font-medium text-white",children:"Forge"}),"."]})})]}),e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 text-white",children:[e.jsx(Qs,{className:"size-4 text-[var(--primary)]"}),e.jsx("div",{className:"font-medium",children:"Discovery first"})]}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/60",children:y.provider==="microsoft"?"Forge starts a Microsoft sign-in popup, then discovers the calendars available to that account before you choose what to mirror.":"Forge discovers the actual calendar collections before you choose which ones to mirror and which one should receive owned timeboxes."})]})]}),e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Setup guide"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:"These are the exact setup steps for the selected provider. They stay inside this guided flow so Settings can stay focused on connection health and actions."}),e.jsx("div",{className:"mt-4",children:e.jsx(dw,{provider:y.provider,compact:!0})})]})]})},{id:"credentials",eyebrow:"Credentials",title:d.provider==="google"?"Provide the Google CalDAV credentials":d.provider==="apple"?"Provide the Apple account email and app-specific password":d.provider==="microsoft"?"Sign in with Microsoft":"Provide the custom CalDAV base URL and credentials",description:d.provider==="apple"?"Apple discovery starts from https://caldav.icloud.com, so you only need the Apple ID email and app password here.":d.provider==="microsoft"?"Forge uses the Microsoft client ID, tenant, and redirect URI saved in Settings -> Calendar, then runs a guided popup sign-in. No client secret is required in the user-facing setup.":"Forge stores the secrets securely, then discovers the available calendars before anything is saved.",render:(y,N)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(Y,{label:"Connection label",description:"This is the readable label Forge shows in settings and the calendar health cards.",children:e.jsx(ie,{value:y.label,onChange:A=>N({label:A.target.value}),placeholder:$a[y.provider].label})}),y.provider==="microsoft"?e.jsx("div",{className:"grid gap-4",children:e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(20,32,48,0.98),rgba(11,18,30,0.98))] p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Guided Microsoft sign-in"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-white/60",children:"Forge uses the Microsoft client ID and redirect URI saved in Calendar Settings, opens a Microsoft login popup, completes a local MSAL public-client authorization-code flow with PKCE, and then brings the discovered calendars back here for selection."})]}),e.jsx(O,{className:"bg-sky-400/12 text-sky-100",children:"Read only"})]}),e.jsxs("div",{className:"mt-4 rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/68",children:[e.jsxs("div",{children:["Saved client ID:"," ",e.jsx("span",{className:"font-medium text-white",children:a.clientId||"Not configured yet"})]}),e.jsxs("div",{children:["Tenant:"," ",e.jsx("span",{className:"font-medium text-white",children:a.tenantId})]}),e.jsxs("div",{className:"break-all",children:["Redirect URI:"," ",e.jsx("span",{className:"font-medium text-white",children:a.redirectUri})]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-3",children:[e.jsxs(W,{type:"button",onClick:()=>void M(),disabled:!a.isReadyForSignIn,pending:(h==null?void 0:h.status)==="pending",pendingLabel:"Waiting for Microsoft",children:[e.jsx(Ia,{className:"size-4"}),(h==null?void 0:h.status)==="authorized"?"Sign in again":"Sign in with Microsoft"]}),h!=null&&h.accountLabel?e.jsxs(O,{className:"bg-emerald-500/16 text-emerald-100",children:[e.jsx(td,{className:"mr-1 size-3.5"}),h.accountLabel]}):null]}),e.jsxs("div",{className:"mt-4 grid gap-3 md:grid-cols-2",children:[e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/68",children:"Users do not paste client secrets or refresh tokens here."}),e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/68",children:"After sign-in, Forge will let you choose which Exchange Online calendars to mirror into the Calendar page."})]}),a.isReadyForSignIn?null:e.jsx("div",{className:"mt-4 rounded-[18px] border border-amber-400/20 bg-amber-400/10 px-4 py-3 text-sm leading-6 text-amber-100",children:a.setupMessage})]})}):e.jsxs(e.Fragment,{children:[y.provider==="caldav"?e.jsx(Y,{label:"CalDAV base URL",description:"Use the account-level CalDAV server URL, not an individual calendar collection URL.",children:e.jsx(ie,{value:y.serverUrl,onChange:A=>N({serverUrl:A.target.value}),placeholder:"https://caldav.example.com"})}):null,y.provider==="apple"?e.jsx(Y,{label:"Apple CalDAV base URL",children:e.jsx(ie,{value:"https://caldav.icloud.com",disabled:!0})}):null,e.jsx(Y,{label:"Account email or username",children:e.jsx(ie,{value:y.username,onChange:A=>N({username:A.target.value}),placeholder:"operator@example.com"})}),y.provider==="google"?e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Google client ID",children:e.jsx(ie,{value:y.clientId,onChange:A=>N({clientId:A.target.value}),placeholder:"1234567890-abcdef.apps.googleusercontent.com"})}),e.jsx(Y,{label:"Google client secret",children:e.jsx(ie,{type:"password",value:y.clientSecret,onChange:A=>N({clientSecret:A.target.value}),placeholder:"GOCSPX-..."})}),e.jsx(Y,{label:"Refresh token",children:e.jsx(ie,{type:"password",value:y.refreshToken,onChange:A=>N({refreshToken:A.target.value}),placeholder:"1//0g..."})})]}):e.jsx(Y,{label:y.provider==="apple"?"App-specific password":"Password or app password",children:e.jsx(ie,{type:"password",value:y.password,onChange:A=>N({password:A.target.value}),placeholder:"Password"})})]})]})},{id:"discovery",eyebrow:"Discovery",title:"Discover the calendars and choose what Forge should sync",description:d.provider==="microsoft"?"Select the Exchange Online calendars Forge should mirror into the Calendar page. This connection stays read-only for now.":"Select the calendars Forge should mirror into the Calendar page, then choose the calendar Forge should write into for work blocks and timeboxes.",render:(y,N)=>e.jsxs("div",{className:"grid gap-4",children:[y.provider==="microsoft"?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(W,{type:"button",onClick:()=>void M(),pending:(h==null?void 0:h.status)==="pending",pendingLabel:"Waiting for Microsoft",children:[e.jsx(Ia,{className:"size-4"}),(h==null?void 0:h.status)==="authorized"?"Reconnect Microsoft":"Sign in with Microsoft"]}),b?e.jsxs(O,{className:"bg-white/[0.08] text-white/74",children:[b.calendars.length," discovered"]}):null]}):e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(W,{pending:k.isPending,pendingLabel:"Discovering",onClick:()=>void k.mutateAsync(),children:[e.jsx(ps,{className:"size-4"}),"Discover calendars"]}),b?e.jsxs(O,{className:"bg-white/[0.08] text-white/74",children:[b.calendars.length," discovered"]}):null]}),b?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4 text-sm leading-6 text-white/64",children:["Discovered through"," ",e.jsx("span",{className:"font-medium text-white",children:b.serverUrl}),b.homeUrl?e.jsxs(e.Fragment,{children:[" ","· home set"," ",e.jsx("span",{className:"font-medium text-white",children:b.homeUrl})]}):null]}),e.jsx("div",{className:"grid gap-3",children:b.calendars.map(A=>{const T=y.selectedCalendarUrls.includes(A.url),F=y.forgeCalendarUrl===A.url;return e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:A.displayName}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[A.timezone||"No timezone exposed"," ·"," ",A.url]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[A.isForgeCandidate?e.jsx(O,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"Forge match"}):null,A.isPrimary?e.jsx(O,{className:"bg-white/[0.08] text-white/74",children:"Primary"}):null]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:()=>N({selectedCalendarUrls:T?y.selectedCalendarUrls.filter(u=>u!==A.url):[...y.selectedCalendarUrls,A.url]}),className:`rounded-full px-3 py-2 text-sm transition ${T?"bg-[var(--primary)]/18 text-[var(--primary)] shadow-[inset_0_0_0_1px_rgba(192,193,255,0.24)]":"bg-white/[0.05] text-white/62 hover:bg-white/[0.08]"}`,children:T?"Mirrored":"Mirror into Forge"}),y.provider!=="microsoft"?e.jsx("button",{type:"button",onClick:()=>N({forgeCalendarUrl:A.url,createForgeCalendar:!1}),className:`rounded-full px-3 py-2 text-sm transition ${F?"bg-emerald-500/18 text-emerald-100 shadow-[inset_0_0_0_1px_rgba(16,185,129,0.28)]":"bg-white/[0.05] text-white/62 hover:bg-white/[0.08]"}`,children:F?"Forge writes here":"Use for Forge writes"}):e.jsx(O,{className:"bg-sky-400/12 text-sky-100",children:"Read only"})]})]},A.url)})}),y.provider!=="microsoft"?e.jsxs("div",{className:"rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:"No Forge calendar yet?"}),e.jsxs("p",{className:"mt-2 text-sm leading-6 text-white/60",children:["If none of the discovered calendars should receive Forge-owned work blocks and timeboxes, let Forge create a dedicated calendar named"," ",e.jsx("span",{className:"font-medium text-white",children:"Forge"}),"."]}),e.jsx("div",{className:"mt-4",children:e.jsx("button",{type:"button",onClick:()=>N({forgeCalendarUrl:null,createForgeCalendar:!y.createForgeCalendar}),className:`rounded-full px-3 py-2 text-sm transition ${y.createForgeCalendar?"bg-emerald-500/18 text-emerald-100 shadow-[inset_0_0_0_1px_rgba(16,185,129,0.28)]":"bg-white/[0.05] text-white/62 hover:bg-white/[0.08]"}`,children:y.createForgeCalendar?"Forge will create one":"Create a new Forge calendar"})})]}):e.jsx("div",{className:"rounded-[24px] border border-sky-400/20 bg-sky-400/10 p-4 text-sm leading-6 text-sky-50",children:"Exchange Online is connected through Microsoft Graph in read-only mode. Forge will mirror the calendars you select here, but it will keep work blocks and owned timeboxes local or publish them through another writable provider."})]}):e.jsx("div",{className:"rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] px-4 py-6 text-sm leading-6 text-white/58",children:y.provider==="microsoft"?e.jsx(e.Fragment,{children:"Start the guided Microsoft sign-in first. Forge will bring the discovered Exchange Online calendars back here as soon as the popup completes."}):e.jsxs(e.Fragment,{children:["Discover calendars after entering the credentials. For Apple, Forge starts from"," ",e.jsx("span",{className:"font-medium text-white",children:"https://caldav.icloud.com"})," ","and resolves the principal plus calendar home automatically."]})})]})},{id:"review",eyebrow:"Review",title:"Confirm what Forge will mirror and where it will write",description:"This keeps the sync model explicit before the provider connection is saved.",render:y=>e.jsx("div",{className:"grid gap-4",children:e.jsxs("div",{className:"rounded-[26px] border border-white/8 bg-[linear-gradient(180deg,rgba(21,31,42,0.96),rgba(10,16,26,0.96))] p-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-[18px] bg-[var(--primary)]/14 p-3 text-[var(--primary)]",children:e.jsx(rs,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-display text-xl text-white",children:ii(y.provider,y.label)}),e.jsx("div",{className:"mt-1 text-sm text-white/58",children:y.provider==="google"?"Google Calendar":y.provider==="apple"?"Apple Calendar":y.provider==="microsoft"?"Exchange Online":"Custom CalDAV"})]})]}),e.jsxs("div",{className:"mt-4 grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] px-4 py-3 text-sm text-white/72",children:["Mirrored calendars:"," ",e.jsx("span",{className:"font-medium text-white",children:y.selectedCalendarUrls.length})]}),e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] px-4 py-3 text-sm text-white/72",children:["Forge writes:"," ",e.jsx("span",{className:"font-medium text-white",children:y.provider==="microsoft"?"read only":y.forgeCalendarUrl?"existing calendar":y.createForgeCalendar?"new Forge calendar":"not selected"})]})]})]})})}],[b,k.isPending,d.provider,h]);return e.jsx(it,{open:t,onOpenChange:s,eyebrow:"Calendar settings",title:"Connect a calendar provider",description:"Discover provider calendars first, then choose which calendars Forge should mirror and, for writable providers, which calendar Forge should write into.",value:d,onChange:y=>{o(y),b&&y.provider!==b.provider&&m(null)},steps:P,submitLabel:"Connect provider",pending:l,pendingLabel:"Connecting",error:x,initialStepId:n,onSubmit:async()=>{try{if(f(null),!b){f("Discover the available calendars before saving the connection.");return}if(d.selectedCalendarUrls.length===0){f("Select at least one calendar to mirror into Forge.");return}if(d.provider!=="microsoft"&&!d.forgeCalendarUrl&&!d.createForgeCalendar){f("Choose the calendar Forge should write into, or ask Forge to create one.");return}if(d.provider==="google")await r({provider:"google",label:ii("google",d.label),username:d.username.trim(),clientId:d.clientId.trim(),clientSecret:d.clientSecret.trim(),refreshToken:d.refreshToken.trim(),selectedCalendarUrls:d.selectedCalendarUrls,forgeCalendarUrl:d.forgeCalendarUrl,createForgeCalendar:d.createForgeCalendar});else if(d.provider==="apple")await r({provider:"apple",label:ii("apple",d.label),username:d.username.trim(),password:d.password.trim(),selectedCalendarUrls:d.selectedCalendarUrls,forgeCalendarUrl:d.forgeCalendarUrl,createForgeCalendar:d.createForgeCalendar});else if(d.provider==="microsoft"){if(!(h!=null&&h.sessionId)||h.status!=="authorized"){f("Complete the Microsoft sign-in flow before saving this connection.");return}await r({provider:"microsoft",label:ii("microsoft",d.label),authSessionId:h.sessionId,selectedCalendarUrls:d.selectedCalendarUrls})}else await r({provider:"caldav",label:ii("caldav",d.label),serverUrl:d.serverUrl.trim(),username:d.username.trim(),password:d.password.trim(),selectedCalendarUrls:d.selectedCalendarUrls,forgeCalendarUrl:d.forgeCalendarUrl,createForgeCalendar:d.createForgeCalendar});s(!1)}catch(y){f(y instanceof Error?y.message:"Forge could not create this calendar connection.")}}})}function ai(t){try{const s=new URL(t);return s.pathname.endsWith("/")||(s.pathname=`${s.pathname}/`),s.toString()}catch{return t}}function vo(t){switch(t){case"google":return"Google Calendar";case"apple":return"Apple Calendar";case"microsoft":return"Exchange Online";case"caldav":default:return"Custom CalDAV"}}const yo="/api/v1/calendar/oauth/microsoft/callback",mw=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;function jo(t){return{clientId:t.clientId,tenantId:t.tenantId,redirectUri:t.redirectUri}}function hw(t){const s={};if(t.clientId.trim()?mw.test(t.clientId.trim())||(s.clientId="Use the Microsoft app registration client ID GUID."):s.clientId="Microsoft client ID is required.",!t.redirectUri.trim())s.redirectUri="Redirect URI is required.";else try{const i=new URL(t.redirectUri.trim());i.protocol!=="http:"&&i.protocol!=="https:"?s.redirectUri="Redirect URI must use http or https.":i.pathname!==yo&&(s.redirectUri=`Redirect URI must end with ${yo}.`)}catch{s.redirectUri="Redirect URI must be a full URL."}return{issues:s,isValid:Object.keys(s).length===0}}function uw(t,s){return t.clientId.trim()===s.clientId.trim()&&t.tenantId.trim()===s.tenantId.trim()&&t.redirectUri.trim()===s.redirectUri.trim()}function pw(){var E,z,K,je,V;const t=We(),[s,i]=ft(),[n,a]=c.useState(!1),[r,l]=c.useState("google"),[d,o]=c.useState(void 0),[x,f]=c.useState(null),[b,m]=c.useState([]),[h,p]=c.useState(!1),[w,v]=c.useState(null),[I,k]=c.useState(()=>Xd()),[S,M]=c.useState({clientId:"",tenantId:"common",redirectUri:""}),P=pe({queryKey:["forge-operator-session"],queryFn:Ci}),y=P.isSuccess,N=pe({queryKey:["forge-settings"],queryFn:Wa,enabled:y}),A=pe({queryKey:["forge-calendar-connections"],queryFn:bp,enabled:y}),T=pe({queryKey:["forge-calendar-resources"],queryFn:Cp,enabled:y}),F=async()=>{await Promise.all([t.invalidateQueries({queryKey:["forge-settings"]}),t.invalidateQueries({queryKey:["forge-calendar-connections"]}),t.invalidateQueries({queryKey:["forge-calendar-resources"]}),t.invalidateQueries({queryKey:["forge-calendar-overview"]}),t.invalidateQueries({queryKey:["forge-snapshot"]})])},u=ge({mutationFn:jp,onSuccess:F}),j=ge({mutationFn:D=>Np(D),onSuccess:F}),L=ge({mutationFn:({connectionId:D,patch:X})=>kp(D,X),onSuccess:F}),q=ge({mutationFn:D=>Sp(D),onSuccess:F}),G=ge({mutationFn:D=>Ld({calendarProviders:{microsoft:D}}),onSuccess:F}),Q=ge({mutationFn:D=>wp({clientId:D.clientId.trim(),tenantId:D.tenantId.trim()||"common",redirectUri:D.redirectUri.trim()})});c.useEffect(()=>{if(!y)return;const D=s.get("intent"),X=s.get("provider");if(D!=="connect")return;l(X==="apple"||X==="caldav"||X==="google"||X==="microsoft"?X:"google"),o(X==="microsoft"?"credentials":void 0),a(!0);const he=new URLSearchParams(s);he.delete("intent"),he.delete("provider"),i(he,{replace:!0})},[y,s,i]),c.useEffect(()=>{var X;const D=(X=N.data)==null?void 0:X.settings.calendarProviders.microsoft;D&&M(jo(D))},[N.data]);const ne=c.useMemo(()=>{var X;const D=new Map;for(const he of((X=T.data)==null?void 0:X.calendars)??[]){const ye=D.get(he.connectionId)??[];ye.push(he),D.set(he.connectionId,ye)}return D},[T.data]),H=c.useMemo(()=>{var D;return Yd(((D=T.data)==null?void 0:D.calendars)??[],I.calendarColors)},[(E=T.data)==null?void 0:E.calendars,I.calendarColors]),_=c.useMemo(()=>{var D;return((D=A.data)==null?void 0:D.connections.find(X=>X.id===x))??null},[A.data,x]),U=c.useMemo(()=>{var D;return((D=A.data)==null?void 0:D.connections.find(X=>X.id===w))??null},[A.data,w]),R=c.useMemo(()=>x?ne.get(x)??[]:[],[ne,x]),C=((z=N.data)==null?void 0:z.settings.calendarProviders.microsoft)??null,J=c.useMemo(()=>hw(S),[S]),ee=C!==null&&!uw(S,jo(C)),le=!(C!=null&&C.isReadyForSignIn)||!J.isValid||ee||G.isPending,oe=pe({queryKey:["forge-calendar-connection-discovery",x],queryFn:()=>yp(x),enabled:y&&x!==null});c.useEffect(()=>{if(!x){m([]),p(!1);return}const D=R.filter(X=>X.selectedForSync).map(X=>ai(X.remoteId));m(D),p(!0)},[x,R]),c.useEffect(()=>{sg(I)},[I]);const ue=c.useMemo(()=>[{id:"mirrors",eyebrow:"Mirroring",title:"Choose which calendars Forge should mirror",description:"Unselected calendars stop showing up in Forge’s mirrored calendar views. The Forge write calendar stays available for work blocks and timeboxes.",render:(D,X)=>{var fe,Pe;if(oe.isLoading)return e.jsx("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.03] px-4 py-6 text-sm leading-6 text-white/58",children:"Rediscovering calendars for this connection."});if(oe.isError||!((fe=oe.data)!=null&&fe.discovery))return e.jsx("div",{className:"rounded-[24px] border border-rose-400/20 bg-rose-400/10 px-4 py-6 text-sm leading-6 text-rose-100",children:oe.error instanceof Error?oe.error.message:"Forge could not rediscover calendars for this connection."});const he=oe.data.discovery,ye=(_==null?void 0:_.provider)==="microsoft",ze=typeof((Pe=_==null?void 0:_.config)==null?void 0:Pe.forgeCalendarUrl)=="string"?ai(_.config.forgeCalendarUrl):null;return e.jsx("div",{className:"grid gap-3",children:he.calendars.map(Ge=>{const Z=ai(Ge.url),He=h?D.selectedCalendarUrls.includes(Z):R.some(Qe=>Qe.selectedForSync&&ai(Qe.remoteId)===Z),Ue=ze===Z;return e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:Ge.displayName}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[Ge.timezone||"No timezone exposed"," · ",Ge.url]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Ue&&!ye?e.jsx(O,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"Forge writes here"}):null,ye?e.jsx(O,{className:"bg-sky-400/12 text-sky-100",children:"Read only"}):null,Ge.isPrimary?e.jsx(O,{className:"bg-white/[0.08] text-white/74",children:"Primary"}):null]})]}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:e.jsx("button",{type:"button",disabled:Ue&&!ye,onClick:()=>X({selectedCalendarUrls:He?D.selectedCalendarUrls.filter(Qe=>Qe!==Z):[...D.selectedCalendarUrls,Z]}),className:`rounded-full px-3 py-2 text-sm transition ${Ue&&!ye?"cursor-not-allowed bg-white/[0.05] text-white/35":He?"bg-emerald-500/18 text-emerald-100 shadow-[inset_0_0_0_1px_rgba(16,185,129,0.28)]":"bg-white/[0.05] text-white/62 hover:bg-white/[0.08]"}`,children:Ue&&!ye?"Always available for Forge writes":He?"Mirrored into Forge":"Do not mirror"})})]},Ge.url)})})}}],[_,oe]);if(P.isLoading||N.isLoading||A.isLoading||T.isLoading)return e.jsx(It,{eyebrow:"Settings · Calendar",title:"Loading calendar settings",description:"Checking the operator session and loading provider connections.",columns:2,blocks:6});if(P.isError)return e.jsx(Oe,{eyebrow:"Settings · Calendar",error:P.error,onRetry:()=>void P.refetch()});if(N.isError||A.isError||T.isError||!((K=N.data)!=null&&K.settings)||!A.data||!T.data)return e.jsx(Oe,{eyebrow:"Settings · Calendar",error:N.error??A.error??T.error??new Error("Calendar settings are unavailable."),onRetry:()=>{N.refetch(),A.refetch(),T.refetch()}});const{providers:me,connections:$}=A.data,ce=N.data.settings.calendarProviders.microsoft;return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(Ke,{title:"Calendar settings",description:"Manage provider connections, review dedicated Forge write calendars where supported, and open guided setup only when you need to connect or reconfigure a provider.",badge:`${$.length} connection${$.length===1?"":"s"}`}),e.jsx(gs,{}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(se,{className:"grid gap-5 rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(17,28,41,0.98),rgba(9,16,27,0.98))]",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Exchange Online local setup"}),e.jsx("p",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/60",children:"Self-hosted Forge uses a Microsoft public client with PKCE. Save the Microsoft app registration details here first, then continue to the guided sign-in flow to choose which Exchange calendars Forge should mirror."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(O,{className:"bg-sky-400/12 text-sky-100",children:"Read only"}),ce.isReadyForSignIn&&!ee?e.jsxs(O,{className:"bg-emerald-500/16 text-emerald-100",children:[e.jsx(td,{className:"mr-1 size-3.5"}),"Ready for sign-in"]}):e.jsxs(O,{className:"bg-white/[0.08] text-white/74",children:[e.jsx(Qs,{className:"mr-1 size-3.5"}),"Setup required"]})]})]}),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("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-white",children:"Microsoft client ID"}),e.jsx("span",{className:"text-sm leading-6 text-white/54",children:"Use the Application (client) ID from the Microsoft Entra app registration for this local Forge instance."}),e.jsx("input",{className:"min-h-12 rounded-[18px] border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white outline-none transition placeholder:text-white/28 focus:border-[var(--primary)]/40 focus:bg-white/[0.06]",value:S.clientId,onChange:D=>M(X=>({...X,clientId:D.target.value})),placeholder:"00000000-0000-0000-0000-000000000000"}),J.issues.clientId?e.jsx("span",{className:"text-sm text-rose-300",children:J.issues.clientId}):null]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-white",children:"Tenant / authority"}),e.jsxs("span",{className:"text-sm leading-6 text-white/54",children:["Use ",e.jsx("span",{className:"font-medium text-white",children:"common"})," for a normal self-hosted delegated flow unless you need a tenant-specific authority."]}),e.jsx("input",{className:"min-h-12 rounded-[18px] border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white outline-none transition placeholder:text-white/28 focus:border-[var(--primary)]/40 focus:bg-white/[0.06]",value:S.tenantId,onChange:D=>M(X=>({...X,tenantId:D.target.value})),placeholder:"common"})]}),e.jsxs("div",{className:"grid gap-2 rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Microsoft access mode"}),e.jsx("p",{className:"text-sm leading-6 text-white/54",children:"Forge currently requests delegated read access only. Exchange calendars are mirrored into Forge, but Forge does not publish work blocks or owned timeboxes back to Microsoft yet."}),e.jsx(O,{className:"w-fit bg-sky-400/12 text-sky-100",children:"Read-only mirroring"})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-white",children:"Redirect URI"}),e.jsx("span",{className:"text-sm leading-6 text-white/54",children:"Register this exact Forge callback URI in the Microsoft app registration. The default works for the local backend on port 4317."}),e.jsx("input",{className:"min-h-12 rounded-[18px] border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white outline-none transition placeholder:text-white/28 focus:border-[var(--primary)]/40 focus:bg-white/[0.06]",value:S.redirectUri,onChange:D=>M(X=>({...X,redirectUri:D.target.value})),placeholder:"http://127.0.0.1:4317/api/v1/calendar/oauth/microsoft/callback"}),J.issues.redirectUri?e.jsx("span",{className:"text-sm text-rose-300",children:J.issues.redirectUri}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{onClick:()=>void G.mutateAsync({clientId:S.clientId.trim(),tenantId:S.tenantId.trim()||"common",redirectUri:S.redirectUri.trim()}),disabled:!J.isValid,pending:G.isPending,pendingLabel:"Saving",children:"Save Microsoft settings"}),e.jsx(W,{variant:"secondary",onClick:()=>void Q.mutateAsync(S),disabled:!J.isValid,pending:Q.isPending,pendingLabel:"Testing",children:"Test Microsoft configuration"}),e.jsxs(W,{variant:"secondary",onClick:()=>{l("microsoft"),o("credentials"),a(!0)},disabled:le,children:[e.jsx(Ia,{className:"size-4"}),"Sign in with Microsoft"]})]}),G.error instanceof Error?e.jsx("div",{className:"rounded-[18px] border border-rose-400/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100",children:G.error.message}):null,Q.isSuccess?e.jsx("div",{className:"rounded-[18px] border border-emerald-400/20 bg-emerald-500/[0.08] px-4 py-3 text-sm text-emerald-100",children:Q.data.result.message}):null,Q.error instanceof Error?e.jsx("div",{className:"rounded-[18px] border border-rose-400/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100",children:Q.error.message}):null]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"What the user needs first"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/58",children:"Microsoft sign-in cannot work until this Forge instance has a registered Microsoft app client ID and callback URI. Forge no longer asks the user for a client secret or refresh token in local self-hosted mode."})]}),e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Current saved setup"}),e.jsxs("div",{className:"mt-3 grid gap-2 text-sm text-white/66",children:[e.jsxs("div",{children:["Client ID:"," ",e.jsx("span",{className:"font-medium text-white",children:ce.clientId||"Not saved yet"})]}),e.jsxs("div",{children:["Tenant:"," ",e.jsx("span",{className:"font-medium text-white",children:ce.tenantId})]}),e.jsxs("div",{className:"break-all",children:["Redirect URI:"," ",e.jsx("span",{className:"font-medium text-white",children:ce.redirectUri})]})]})]}),e.jsx("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4 text-sm leading-6 text-white/60",children:ee?"Save these Microsoft settings before you try to sign in, otherwise the popup will still use the previous saved configuration.":ce.setupMessage})]})]})]}),e.jsxs(se,{className:"grid gap-4 rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Provider connections"}),e.jsxs("p",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/60",children:["All provider setup lives here. Writable providers can publish work blocks and owned timeboxes into a dedicated calendar named ",e.jsx("span",{className:"font-medium text-white",children:"Forge"}),", while read-only providers only mirror the calendars you select. Exact provider instructions appear only inside the guided setup flow."]})]}),e.jsxs(O,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[e.jsx(Xo,{className:"mr-1 size-3.5"}),"Settings-owned"]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:me.map(D=>e.jsxs("button",{type:"button",onClick:()=>{l(D.provider),o(D.provider==="microsoft"?"credentials":void 0),a(!0)},className:"rounded-[26px] border border-white/8 bg-white/[0.04] p-5 text-left transition hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-[18px] bg-[var(--primary)]/14 p-3 text-[var(--primary)]",children:e.jsx(rs,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:D.label}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:"Connect and manage sync"})]})]}),e.jsx("p",{className:"mt-4 text-sm leading-6 text-white/60",children:D.connectionHelp}),e.jsx("div",{className:"mt-4 inline-flex rounded-full bg-white/[0.06] px-3 py-2 text-xs uppercase tracking-[0.16em] text-white/52",children:"Open guided setup"})]},D.provider))})]}),e.jsxs(se,{className:"grid gap-4 rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Calendar colors"}),e.jsx("p",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/60",children:"Calendar colors are on by default so each mirrored calendar stays legible in the week view. Adjust any display color here without changing the provider itself."})]}),e.jsx("button",{type:"button",onClick:()=>k(D=>({...D,useCalendarColors:!D.useCalendarColors})),className:`rounded-full px-4 py-2 text-sm transition ${I.useCalendarColors?"bg-[var(--primary)]/16 text-[var(--primary)] shadow-[inset_0_0_0_1px_rgba(192,193,255,0.2)]":"bg-white/[0.06] text-white/62 hover:bg-white/[0.08]"}`,children:I.useCalendarColors?"Colors on":"Colors off"})]}),(((je=T.data)==null?void 0:je.calendars)??[]).length>0?e.jsx("div",{className:"grid gap-3",children:(((V=T.data)==null?void 0:V.calendars)??[]).map(D=>e.jsxs("div",{className:"grid gap-3 rounded-[22px] border border-white/8 bg-white/[0.04] p-4 md:grid-cols-[minmax(0,1fr)_auto]",children:[e.jsx("div",{className:"min-w-0",children:e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{"aria-hidden":"true",className:"size-3 shrink-0 rounded-full",style:{backgroundColor:H[D.id]}}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate font-medium text-white",children:D.title}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[D.canWrite?"Writable":"Read only"," · ",D.timezone]})]})]})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{"aria-label":`Choose display color for ${D.title}`,type:"color",value:H[D.id],onChange:X=>k(he=>({...he,calendarColors:{...he.calendarColors,[D.id]:X.target.value}})),className:"h-10 w-12 cursor-pointer rounded-[14px] border border-white/12 bg-transparent p-1"}),e.jsx(W,{size:"sm",variant:"secondary",onClick:()=>k(X=>{const he={...X.calendarColors};return delete he[D.id],{...X,calendarColors:he}}),children:"Reset palette"})]})]},D.id))}):e.jsx("div",{className:"rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] px-4 py-5 text-sm leading-6 text-white/56",children:"Connect a provider first, then Forge will let you tune the display color of each mirrored calendar here."})]}),e.jsxs(se,{className:"grid gap-4 rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",children:[e.jsx("div",{className:"flex items-center justify-between gap-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Connected providers"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:"Review connection health and confirm which provider calendars Forge can read, mirror, or write."})]})}),$.length>0?e.jsx("div",{className:"grid gap-3",children:$.map(D=>{var he;const X=ne.get(D.id)??[];return e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:D.label}),e.jsxs("div",{className:"mt-1 text-sm text-white/55",children:[vo(D.provider)," · ",D.accountLabel||"No account label yet"]}),D.lastSyncedAt?e.jsxs("div",{className:"mt-2 text-sm text-white/48",children:["Last synced ",new Date(D.lastSyncedAt).toLocaleString()]}):null,D.lastSyncError?e.jsx("div",{className:"mt-2 text-sm text-rose-200",children:D.lastSyncError}):null]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{className:"bg-white/[0.08] text-white/74",children:D.status}),((he=D.config)==null?void 0:he.readOnly)===!0?e.jsx(O,{className:"bg-sky-400/12 text-sky-100",children:"Read only"}):null,e.jsxs(W,{size:"sm",variant:"secondary",pending:j.isPending&&j.variables===D.id,pendingLabel:"Syncing",onClick:()=>void j.mutateAsync(D.id),children:[e.jsx(ps,{className:"size-4"}),"Sync"]}),e.jsxs(W,{size:"sm",variant:"secondary",onClick:()=>{const ye=(ne.get(D.id)??[]).filter(ze=>ze.selectedForSync).map(ze=>ai(ze.remoteId));m(ye),p(!0),f(D.id)},children:[e.jsx(Zm,{className:"size-4"}),"Manage mirrored calendars"]}),e.jsxs(W,{size:"sm",variant:"secondary",onClick:()=>v(D.id),children:[e.jsx(bt,{className:"size-4"}),"Remove"]})]})]}),e.jsx("div",{className:"mt-4 grid gap-2",children:X.map(ye=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white",children:ye.title}),e.jsxs("div",{className:"mt-1 text-xs uppercase tracking-[0.16em] text-white/45",children:[ye.canWrite?"Writable":"Read only"," · ",ye.timezone]})]}),ye.forgeManaged?e.jsx(O,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"Forge"}):e.jsxs(O,{className:"bg-white/[0.08] text-white/74",children:[e.jsx(us,{className:"mr-1 size-3.5"}),"Mirrored"]})]},ye.id))})]},D.id)})}):e.jsxs("div",{className:"rounded-[26px] border border-dashed border-white/10 bg-white/[0.03] px-5 py-6 text-sm leading-6 text-white/60",children:["No provider is connected yet. Open a guided setup flow above when you are ready. Forge will either create or reuse a dedicated ",e.jsx("span",{className:"font-medium text-white",children:"Forge"})," calendar for writable providers, or mirror selected calendars in read-only mode for providers like Exchange Online."]})]})]}),e.jsx(cw,{open:n,onOpenChange:D=>{a(D),D||o(void 0)},initialProvider:r,initialStepId:d,microsoftSetup:ce,pending:u.isPending,onSubmit:async D=>{await u.mutateAsync(D)}}),e.jsx(it,{open:x!==null,onOpenChange:D=>{D||f(null)},eyebrow:"Calendar settings",title:"Manage mirrored calendars",description:"Choose which calendars this connection should mirror into Forge.",value:{selectedCalendarUrls:b},onChange:D=>m(D.selectedCalendarUrls),steps:ue,pending:L.isPending,pendingLabel:"Saving",submitLabel:"Save mirror selection",error:L.error instanceof Error?L.error.message:null,onSubmit:async()=>{x&&(await L.mutateAsync({connectionId:x,patch:{selectedCalendarUrls:b.map(ai)}}),p(!1),f(null))}}),e.jsx(it,{open:w!==null,onOpenChange:D=>{D||v(null)},eyebrow:"Calendar settings",title:"Remove calendar connection",description:"This removes the provider connection, stops syncing its calendars, removes mirrored external events from Forge, and keeps Forge-native events local.",value:{acknowledgement:!1},onChange:()=>{},steps:[{id:"confirm",eyebrow:"Disconnect",title:U?`Remove ${U.label}?`:"Remove this connection?",description:"Use this when you want to disconnect the account entirely. You can reconnect later with the guided setup flow.",render:()=>e.jsx("div",{className:"rounded-[24px] border border-rose-400/20 bg-rose-400/10 p-4 text-sm leading-6 text-rose-100",children:U?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"font-medium text-white",children:[vo(U.provider)," · ",U.accountLabel||"No account label"]}),e.jsx("div",{className:"mt-2",children:"Mirrored provider calendars and external mirrored events from this connection will be removed. Forge-owned events, work blocks, and timeboxes remain in Forge."})]}):"This connection will be removed from Forge."})}],pending:q.isPending,pendingLabel:"Removing",submitLabel:"Remove connection",error:q.error instanceof Error?q.error.message:null,onSubmit:async()=>{w&&(await q.mutateAsync(w),v(null))}})]})}function xw(t){return t.replaceAll("."," ")}function gw(t){const s=typeof t.sleepSessions=="number"?t.sleepSessions:0,i=typeof t.workouts=="number"?t.workouts:0;return`${s} sleep · ${i} workouts`}function No(t){return t?"signal":"meta"}function bw(){const t=Ye(),s=We(),i=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],n=Nt(i),[a,r]=c.useState(null),[l,d]=c.useState(!1),[o,x]=c.useState(null),f=pe({queryKey:["forge-companion-overview",...i],queryFn:async()=>(await Up(i)).overview}),b=ge({mutationFn:async()=>Gp({userId:n??null}),onSuccess:async k=>{x({qrPayload:k.qrPayload}),d(!0),await s.invalidateQueries({queryKey:["forge-companion-overview"]})}}),m=ge({mutationFn:async k=>Hp(k),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-companion-overview"]})}}),h=ge({mutationFn:async()=>Xp({userIds:i,includeRevoked:!1}),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-companion-overview"]})}});if(c.useEffect(()=>{if(!o){r(null);return}eh.toDataURL(JSON.stringify(o.qrPayload),{width:320,margin:1}).then(r)},[o]),f.isLoading)return e.jsx(It,{eyebrow:"Companion",title:"Loading mobile companion",description:"Checking pairing state and recent sync status.",columns:2,blocks:5});if(f.isError||!f.data)return e.jsx(Oe,{eyebrow:"Companion",error:f.error??new Error("Companion overview unavailable"),onRetry:()=>void f.refetch()});const p=f.data,w=p.pairings.filter(k=>k.status!=="revoked"),v=p.pairings.length-w.length,I=async()=>{if(o&&l){d(!1);return}if(o&&!l){d(!0);return}await b.mutateAsync()};return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(Ke,{title:"Mobile companion",description:"Pair the native iPhone companion, sync Apple Health, and keep the bridge open for watch and location signals.",badge:p.healthState.replaceAll("_"," ")}),e.jsx(gs,{}),e.jsxs("section",{className:"grid gap-4",children:[e.jsxs(se,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Pair iPhone"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Open a pairing QR only when you need it"}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:"Keep the page compact by generating or reopening the one-time QR only when you are about to scan it from Forge Companion."})]}),e.jsxs(W,{onClick:()=>void I(),pending:b.isPending,pendingLabel:"Generating",children:[e.jsx(th,{className:"size-4"}),o?l?"Hide QR":"Show QR":"Generate QR",o?l?e.jsx(_a,{className:"size-4"}):e.jsx(Si,{className:"size-4"}):null]})]}),l?e.jsxs("div",{className:"grid gap-4 rounded-[24px] border border-white/8 bg-white/[0.03] p-4 sm:p-5",children:[a?e.jsxs("div",{className:"grid justify-items-center gap-4 rounded-[24px] bg-white px-6 py-6 text-slate-950",children:[e.jsx("img",{src:a,alt:"Forge Companion pairing QR code",className:"w-full max-w-[320px]"}),e.jsx("div",{className:"max-w-[320px] text-center text-sm text-slate-600",children:"Scan this in the iOS companion to pass the Forge API address and the one-time pairing token."})]}):e.jsx("div",{className:"rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] px-5 py-8 text-center text-sm text-white/55",children:"Generating the QR code now."}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"text-sm text-white/62",children:o?e.jsxs(e.Fragment,{children:["Expires"," ",new Date(o.qrPayload.expiresAt).toLocaleString(),"."]}):"Generate the one-time QR and scan it from the iPhone app."}),o?e.jsxs(W,{variant:"secondary",pending:b.isPending,pendingLabel:"Generating",onClick:()=>void b.mutateAsync(),children:[e.jsx(ps,{className:"size-4"}),"Regenerate QR"]}):null]}),o?e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] p-4 text-sm text-white/62",children:[e.jsx("div",{className:"rounded-[16px] bg-slate-950/60 p-3 font-mono text-[11px] leading-5 text-white/70",children:JSON.stringify(o.qrPayload,null,2)}),e.jsx("div",{className:"text-xs text-white/45",children:"The same payload can be pasted into the iPhone app if the camera path is unavailable."})]}):null]}):e.jsx("div",{className:"rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] px-5 py-6 text-sm text-white/55",children:"Tap the QR button when you actually want to pair a phone."})]}),e.jsxs(se,{className:"grid gap-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Companion state"}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Pairings"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:w.length}),v>0?e.jsxs("div",{className:"mt-2 text-xs text-white/42",children:[v," revoked hidden"]}):null]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Sleep sessions"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:p.counts.sleepSessions})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Workouts"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:p.counts.workouts})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Reflected sleep"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:p.counts.reflectiveSleepSessions})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Linked workouts"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:p.counts.linkedWorkouts})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Habit-generated"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:p.counts.habitGeneratedWorkouts})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Reconciled"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:p.counts.reconciledWorkouts})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(O,{children:p.healthState.replaceAll("_"," ")}),p.lastSyncAt?e.jsxs(O,{tone:"meta",children:["Last sync ",new Date(p.lastSyncAt).toLocaleString()]}):null,e.jsxs(O,{tone:No(p.permissions.healthKitAuthorized),children:["HealthKit ",p.permissions.healthKitAuthorized?"ready":"needed"]}),e.jsxs(O,{tone:No(p.permissions.backgroundRefreshEnabled),children:["Background refresh"," ",p.permissions.backgroundRefreshEnabled?"ready":"not yet"]}),e.jsxs(O,{tone:"meta",children:["Location ",p.permissions.locationReady?"ready":"later"]}),e.jsxs(O,{tone:"meta",children:["Motion ",p.permissions.motionReady?"ready":"later"]})]}),e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Pairing path"}),e.jsxs("div",{className:"grid gap-2 text-sm text-white/62",children:[e.jsx("div",{children:"1. Generate a one-time QR code here inside Forge Settings."}),e.jsx("div",{children:"2. Scan it in Forge Companion to pass the API URL and pairing token."}),e.jsx("div",{children:"3. Approve Health access on iPhone, then run the first sync."}),e.jsx("div",{children:"4. Review import history below and open Sleep or Sports to enrich the imported records."})]})]}),e.jsxs("div",{className:"grid gap-3",children:[w.length>0?e.jsx("div",{className:"flex justify-end",children:e.jsxs(W,{variant:"secondary",pending:h.isPending,pendingLabel:"Revoking all",onClick:()=>void h.mutateAsync(),children:[e.jsx(Xr,{className:"size-4"}),"Revoke all"]})}):null,w.map(k=>e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-base text-white",children:k.deviceName??k.label}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[k.platform??"ios"," · ",k.status]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(O,{tone:k.status==="healthy"?"signal":"meta",children:k.status.replaceAll("_"," ")}),k.lastSyncAt?e.jsxs(O,{tone:"meta",children:["Synced ",new Date(k.lastSyncAt).toLocaleString()]}):null]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:k.capabilities.map(S=>e.jsx(O,{tone:"meta",size:"sm",wrap:!0,children:xw(S)},S))}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 text-sm text-white/55",children:[e.jsxs("div",{className:"grid gap-1",children:[e.jsx("div",{children:k.apiBaseUrl}),e.jsxs("div",{children:["Expires ",new Date(k.expiresAt).toLocaleString()]}),k.lastSyncError?e.jsx("div",{className:"text-rose-200/80",children:k.lastSyncError}):null]}),e.jsxs(W,{variant:"secondary",pending:m.isPending&&m.variables===k.id,pendingLabel:"Revoking",disabled:k.status==="revoked",onClick:()=>void m.mutateAsync(k.id),children:[e.jsx(Xr,{className:"size-4"}),k.status==="revoked"?"Revoked":"Revoke"]})]})]},k.id)),w.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-6 text-sm text-white/55",children:"No companion paired yet. Generate a QR code, then open the iOS companion and scan it."}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(W,{variant:"secondary",onClick:()=>void f.refetch(),children:[e.jsx(ps,{className:"size-4"}),"Refresh status"]}),e.jsxs(Le,{to:"/sleep",className:"inline-flex min-h-11 items-center gap-2 rounded-[16px] border border-white/8 bg-white/[0.03] px-4 py-3 text-sm text-white/72 transition hover:bg-white/[0.06] hover:text-white",children:[e.jsx(rs,{className:"size-4"}),"Open sleep view"]}),e.jsxs(Le,{to:"/sports",className:"inline-flex min-h-11 items-center gap-2 rounded-[16px] border border-white/8 bg-white/[0.03] px-4 py-3 text-sm text-white/72 transition hover:bg-white/[0.06] hover:text-white",children:[e.jsx(rs,{className:"size-4"}),"Open sports view"]})]})]})]}),e.jsxs(se,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Sync history"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Recent HealthKit import runs"})]}),e.jsxs(O,{tone:"meta",children:[p.importRuns.length," recent runs"]})]}),e.jsxs("div",{className:"grid gap-3",children:[p.importRuns.map(k=>e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] px-4 py-4 lg:grid-cols-[minmax(0,1fr)_auto]",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(sh,{className:"size-4 text-white/55"}),e.jsxs("div",{className:"text-base text-white",children:[k.sourceDevice||"iPhone"," import"]}),e.jsx(O,{tone:k.status==="completed"?"signal":"meta",children:k.status})]}),e.jsxs("div",{className:"text-sm text-white/60",children:[new Date(k.importedAt).toLocaleString()," ·"," ",gw(k.payloadSummary)]}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-sm text-white/60",children:[e.jsxs(O,{tone:"meta",children:["Imported ",k.importedCount]}),e.jsxs(O,{tone:"meta",children:["Created ",k.createdCount]}),e.jsxs(O,{tone:"meta",children:["Updated ",k.updatedCount]}),e.jsxs(O,{tone:"meta",children:["Merged ",k.mergedCount]})]}),k.errorMessage?e.jsx("div",{className:"text-sm text-rose-200/80",children:k.errorMessage}):null]}),k.pairingSessionId?e.jsxs("div",{className:"text-sm text-white/45 lg:text-right",children:["Pairing ",k.pairingSessionId]}):null]},k.id)),p.importRuns.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-6 text-sm text-white/55",children:"No sync runs yet. Pair the iPhone companion and run the first HealthKit import."}):null]})]})]})}const fw=["error","warning","info","debug"],ww=["server","ui","system","agent","openclaw"],vw=120;function Bs(t){return t.trim().toLowerCase()}function xi(t){return Array.from(new Set(t.map(s=>(s==null?void 0:s.trim())??"").filter(Boolean)))}function ni(t,s){const i=xi(t.getAll(s));if(i.length>0)return i;const n=t.get(s);return n!=null&&n.trim()?[n.trim()]:[]}function yw(t){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}).format(new Date(t))}function ko(t){return t==="error"?"border-rose-400/20 bg-rose-500/[0.08] text-rose-100":t==="warning"?"border-amber-400/20 bg-amber-500/[0.08] text-amber-100":t==="info"?"border-sky-400/20 bg-sky-500/[0.08] text-sky-100":"border-white/10 bg-white/[0.04] text-white/68"}function In(t){return t==="error"?"Errors":t==="warning"?"Warnings":t==="info"?"Info":"Debug"}function Tn(t){return t==="openclaw"?"OpenClaw":t.charAt(0).toUpperCase()+t.slice(1)}function jw(t){return[t.scope?`scope: ${t.scope}`:null,t.eventKey?`event: ${t.eventKey}`:null,t.route?`route: ${t.route}`:null,t.functionName?`function: ${t.functionName}`:null,t.jobId?`job: ${t.jobId}`:null,t.entityType&&t.entityId?`entity: ${t.entityType}:${t.entityId}`:null,t.requestId?`request: ${t.requestId}`:null].filter(s=>!!s)}function Nw(t){return Bs([t.message,t.scope,t.eventKey,t.route,t.functionName,t.requestId,t.entityType,t.entityId,t.jobId,JSON.stringify(t.details)].filter(Boolean).join(" "))}function zs(t,s){return e.jsx(O,{size:"sm",className:re("bg-white/[0.08] text-white/74",s),children:t})}function St(t,s,i,n){return t==="user"?e.jsx($e,{user:i??null,compact:!0}):t==="tag"?e.jsx(O,{size:"sm",className:"bg-white/[0.08] text-white/84",style:n!=null&&n.color?{color:n.color}:void 0,children:s}):zh(t)?e.jsx(ke,{kind:t,label:s,compact:!0,gradient:!1}):zs(s,"bg-[rgba(192,193,255,0.12)] text-white/84")}function ri({label:t,placeholder:s,options:i,selectedIds:n,onChange:a,emptyMessage:r="No matches yet."}){const[l,d]=c.useState(!1),[o,x]=c.useState(""),[f,b]=c.useState(0),m=c.useMemo(()=>n.map(I=>i.find(k=>k.id===I)??null).filter(I=>I!==null),[i,n]),h=Bs(o),p=c.useMemo(()=>{const I=i.filter(k=>!n.includes(k.id));return h?I.filter(k=>Bs(`${k.label} ${k.description??""} ${k.searchText??""}`).includes(h)).slice(0,10):I.slice(0,10)},[h,i,n]),w=I=>{n.includes(I)||(a([...n,I]),x(""),b(0),d(!1))},v=I=>{a(n.filter(k=>k!==I))};return e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-[11px] font-medium uppercase tracking-[0.18em] text-white/45",children:t}),e.jsxs("div",{className:"relative rounded-[20px] border border-white/8 bg-white/[0.04] px-3 py-2.5",children:[m.length>0?e.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:m.map(I=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-white/8 bg-white/[0.05] px-1.5 py-1",children:[I.badge,e.jsx("button",{type:"button",className:"rounded-full p-0.5 text-white/46 transition hover:text-white",onClick:()=>v(I.id),"aria-label":`Remove ${I.label}`,children:e.jsx(mt,{className:"size-3"})})]},I.id))}):null,e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dt,{className:"size-3.5 text-white/34"}),e.jsx("input",{value:o,onChange:I=>{x(I.target.value),b(0),d(!0)},onFocus:()=>d(!0),onBlur:()=>{window.setTimeout(()=>d(!1),120)},onKeyDown:I=>{if(I.key==="Backspace"&&!o&&n.length>0){v(n[n.length-1]);return}if(I.key==="ArrowDown"){I.preventDefault(),d(!0),b(k=>p.length===0?0:Math.min(p.length-1,k+1));return}if(I.key==="ArrowUp"){I.preventDefault(),b(k=>Math.max(0,k-1));return}if(I.key==="Escape"){d(!1);return}I.key==="Enter"&&p[f]&&(I.preventDefault(),w(p[f].id))},placeholder:s,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 left-0 right-0 top-full z-20 mt-2 max-h-64 overflow-y-auto rounded-[20px] border border-white/8 bg-[rgba(8,13,24,0.96)] p-2 shadow-[0_26px_60px_rgba(4,8,18,0.32)] backdrop-blur-xl",children:p.length>0?p.map((I,k)=>e.jsx("button",{type:"button",className:re("flex w-full items-start justify-between gap-3 rounded-[16px] px-3 py-2 text-left transition",k===f?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>b(k),onMouseDown:S=>S.preventDefault(),onClick:()=>w(I.id),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:I.menuBadge??I.badge}),I.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/46",children:I.description}):null]})},I.id)):e.jsx("div",{className:"px-3 py-2 text-sm text-white/42",children:r})}):null]})]})}function vs(t,s){const i=`${s.entityType}:${s.entityId}`;t.has(i)||t.set(i,{id:i,label:s.label,description:s.description,searchText:s.searchText,badge:s.badge,menuBadge:s.menuBadge})}function kw(t,s){const i=new Map;if(t){for(const n of t.dashboard.goals)vs(i,{entityType:"goal",entityId:n.id,label:Je(n.title,n.user),description:Be(n.description,n.user),searchText:qe([n.title,n.description,n.status,n.horizon],n),badge:St("goal",n.title,n.user),menuBadge:St("goal",n.title,n.user)});for(const n of t.dashboard.projects)vs(i,{entityType:"project",entityId:n.id,label:Je(n.title,n.user),description:Be(n.description,n.user),searchText:qe([n.title,n.description,n.status,n.goalTitle],n),badge:St("project",n.title,n.user),menuBadge:St("project",n.title,n.user)});for(const n of t.dashboard.tasks)vs(i,{entityType:"task",entityId:n.id,label:Je(n.title,n.user),description:Be(n.description,n.user),searchText:qe([n.title,n.description,n.status],n),badge:St("task",n.title,n.user),menuBadge:St("task",n.title,n.user)});for(const n of t.dashboard.habits)vs(i,{entityType:"habit",entityId:n.id,label:Je(n.title,n.user),description:Be(n.description,n.user),searchText:qe([n.title,n.description,n.frequency,n.status],n),badge:St("habit",n.title,n.user),menuBadge:St("habit",n.title,n.user)});for(const n of t.strategies)vs(i,{entityType:"strategy",entityId:n.id,label:Je(n.title,n.user),description:Be(n.overview,n.user),searchText:qe([n.title,n.overview,n.endStateDescription],n),badge:St("strategy",n.title,n.user),menuBadge:St("strategy",n.title,n.user)});for(const n of t.dashboard.tags)vs(i,{entityType:"tag",entityId:n.id,label:n.name,description:n.description||"Forge tag",searchText:Bs(`${n.name} ${n.description??""}`),badge:St("tag",n.name,null,n),menuBadge:St("tag",n.name,null,n)});for(const n of t.users)vs(i,{entityType:"user",entityId:n.id,label:Je(n.displayName,n),description:n.description||`${n.kind} Forge user`,searchText:Bs(`${n.displayName} ${n.handle??""} ${n.kind} ${n.description??""}`),badge:St("user",n.displayName,n),menuBadge:St("user",n.displayName,n)})}for(const n of s){if(!n.entityType||!n.entityId)continue;const a=`${n.entityType}:${n.entityId}`;if(i.has(a))continue;const r=n.entityType==="wiki_ingest_job"?`Ingest ${n.entityId}`:`${n.entityType} ${n.entityId}`;vs(i,{entityType:n.entityType,entityId:n.entityId,label:r,description:"Seen in diagnostics logs",searchText:Bs(`${r} ${n.scope} ${n.message} ${n.eventKey}`),badge:St(n.entityType,r),menuBadge:St(n.entityType,r)})}return Array.from(i.values()).sort((n,a)=>n.label.localeCompare(a.label))}function Sw(){const[t,s]=ft(),i=c.useMemo(()=>{var F,u;const N=((F=t.get("entityType"))==null?void 0:F.trim())||"",A=((u=t.get("entityId"))==null?void 0:u.trim())||"",T=ni(t,"entity");return T.length===0&&N&&A&&T.push(`${N}:${A}`),{search:t.get("search")||"",levels:ni(t,"level"),sources:ni(t,"source"),scopes:ni(t,"scope"),routes:ni(t,"route"),jobs:ni(t,"jobId"),entities:xi(T)}},[t]),n=ih({queryKey:["forge-diagnostic-logs","settings-filters"],initialPageParam:null,queryFn:({pageParam:N})=>fx({limit:vw,beforeCreatedAt:N==null?void 0:N.beforeCreatedAt,beforeId:N==null?void 0:N.beforeId}),getNextPageParam:N=>N.nextCursor}),a=pe({queryKey:["forge-diagnostic-log-entities"],queryFn:()=>yd(),staleTime:6e4}),r=(N,A)=>{const T=new URLSearchParams(t);A.trim()?T.set(N,A.trim()):T.delete(N),s(T,{replace:!0})},l=(N,A,T=[])=>{const F=new URLSearchParams(t);F.delete(N);for(const u of T)F.delete(u);for(const u of xi(A))F.append(N,u);s(F,{replace:!0})},d=()=>{const N=new URLSearchParams(t);["search","level","source","scope","route","jobId","entity","entityType","entityId"].forEach(A=>N.delete(A)),s(N,{replace:!0})};if(n.isPending)return e.jsx(It,{eyebrow:"Settings",title:"Loading diagnostics",description:"Collecting the latest frontend, backend, and runtime traces.",columns:1,blocks:6});if(n.isError)return e.jsx(Oe,{eyebrow:"Settings",error:n.error,onRetry:()=>void n.refetch()});const o=c.useMemo(()=>{var N;return((N=n.data)==null?void 0:N.pages.flatMap(A=>A.logs))??[]},[n.data]),x=Bs(i.search),f=c.useRef(null),b=c.useMemo(()=>fw.map(N=>({id:N,label:In(N),searchText:`${N} ${In(N)}`,badge:e.jsx(O,{size:"sm",className:ko(N),children:In(N)})})),[]),m=c.useMemo(()=>ww.map(N=>({id:N,label:Tn(N),searchText:`${N} ${Tn(N)}`,badge:zs(Tn(N))})),[]),h=c.useMemo(()=>xi(o.map(N=>N.scope)).map(N=>({id:N,label:N,searchText:N,badge:zs(N)})),[o]),p=c.useMemo(()=>xi(o.map(N=>N.route)).map(N=>({id:N,label:N,description:"Filter logs to one or more exact routes.",searchText:N,badge:zs(N,"max-w-[16rem]"),menuBadge:zs(N)})),[o]),w=c.useMemo(()=>xi(o.map(N=>N.jobId)).map(N=>({id:N,label:N,description:"Background job or ingest run id.",searchText:N,badge:zs(N,"max-w-[14rem]"),menuBadge:zs(N)})),[o]),v=c.useMemo(()=>kw(a.data,o),[o,a.data]),I=c.useMemo(()=>o.filter(N=>{if(x&&!Nw(N).includes(x)||i.levels.length>0&&!i.levels.includes(N.level)||i.sources.length>0&&!i.sources.includes(N.source)||i.scopes.length>0&&!i.scopes.includes(N.scope)||i.routes.length>0&&!i.routes.includes(N.route??"")||i.jobs.length>0&&!i.jobs.includes(N.jobId??""))return!1;if(i.entities.length>0){const A=N.entityType&&N.entityId?`${N.entityType}:${N.entityId}`:"";if(!A||!i.entities.includes(A))return!1}return!0}),[i,x,o]),k=[i.search,i.levels.join("|"),i.sources.join("|"),i.scopes.join("|"),i.routes.join("|"),i.jobs.join("|"),i.entities.join("|")].join("::");c.useEffect(()=>{var N;(N=f.current)==null||N.scrollTo({top:0})},[k]);const S=ah({count:I.length,getScrollElement:()=>f.current,estimateSize:()=>260,overscan:8}),M=S.getVirtualItems(),P=()=>{const N=f.current;if(!N||!n.hasNextPage||n.isFetchingNextPage)return;N.scrollHeight-N.scrollTop-N.clientHeight<=800&&n.fetchNextPage()},y=i.levels.length+i.sources.length+i.scopes.length+i.routes.length+i.jobs.length+i.entities.length+(i.search.trim()?1:0);return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(Ke,{title:"Logs",description:"Inspect shared diagnostics from the UI, backend routes, background jobs, and LLM flows.",badge:`${I.length} matching${I.length!==o.length?` · ${o.length} loaded`:""}${n.hasNextPage?" · more available":""}`}),e.jsx(gs,{}),e.jsxs(se,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Filters"}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:"Use token filters with OR-style badge selections for levels, sources, routes, jobs, scopes, and linked entities. Search still matches the message body and structured details."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y>0?e.jsxs(W,{variant:"ghost",size:"sm",onClick:d,children:["Clear ",y]}):null,e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>void n.refetch(),pending:n.isRefetching&&!n.isFetchingNextPage,pendingLabel:"Refreshing",children:"Refresh"})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-[11px] font-medium uppercase tracking-[0.18em] text-white/45",children:"Search message or details"}),e.jsx(ie,{value:i.search,onChange:N=>r("search",N.target.value),placeholder:"LLM compilation failed, wiki_ingest, request_failed…",className:"h-11 rounded-[20px]"})]}),e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsx(ri,{label:"Levels",placeholder:"Add one or more levels",options:b,selectedIds:i.levels,onChange:N=>l("level",N),emptyMessage:"No additional log levels."}),e.jsx(ri,{label:"Sources",placeholder:"Add one or more sources",options:m,selectedIds:i.sources,onChange:N=>l("source",N),emptyMessage:"No additional log sources."}),e.jsx(ri,{label:"Scopes",placeholder:"Search scopes",options:h,selectedIds:i.scopes,onChange:N=>l("scope",N),emptyMessage:"No scopes match the current logs."}),e.jsx(ri,{label:"Routes",placeholder:"Search exact routes",options:p,selectedIds:i.routes,onChange:N=>l("route",N),emptyMessage:"No routes match the current logs."}),e.jsx(ri,{label:"Jobs",placeholder:"Search job ids",options:w,selectedIds:i.jobs,onChange:N=>l("jobId",N),emptyMessage:"No job ids match the current logs."}),e.jsx(ri,{label:"Entities",placeholder:"Search Forge entities or logged ids",options:v,selectedIds:i.entities,onChange:N=>l("entity",N,["entityType","entityId"]),emptyMessage:a.isFetching?"Loading Forge entities…":"No Forge entities or logged ids match yet."})]})]}),e.jsx("div",{className:"grid gap-3",children:I.length===0?e.jsx(se,{className:"text-sm text-white/58",children:"No diagnostic entries match the current filters yet."}):e.jsx(se,{className:"p-0",children:e.jsxs("div",{ref:f,onScroll:P,className:"h-[72vh] overflow-y-auto px-3 py-3",children:[e.jsx("div",{className:"relative",style:{height:`${S.getTotalSize()}px`},children:M.map(N=>{const A=I[N.index];return A?e.jsx("div",{"data-index":N.index,ref:S.measureElement,className:"absolute left-0 top-0 w-full pb-3",style:{transform:`translateY(${N.start}px)`},children:e.jsxs(se,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:re("rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em]",ko(A.level)),children:A.level}),e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-white/60",children:A.source}),e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-white/60",children:A.scope}),A.eventKey?e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-white/46",children:A.eventKey}):null]}),e.jsx("div",{className:"text-base font-medium text-white",children:A.message}),e.jsx("div",{className:"flex flex-wrap gap-3 text-xs text-white/45",children:jw(A).map(T=>e.jsx("span",{children:T},T))})]}),e.jsxs("div",{className:"shrink-0 text-right text-xs text-white/40",children:[e.jsx("div",{children:yw(A.createdAt)}),e.jsx("div",{className:"mt-1 font-mono text-[11px]",children:A.id})]})]}),Object.keys(A.details).length>0?e.jsxs("details",{className:"rounded-[18px] border border-white/8 bg-[rgba(7,11,21,0.72)] px-4 py-3",children:[e.jsx("summary",{className:"cursor-pointer text-sm text-white/70",children:"View structured details"}),e.jsx("pre",{className:"mt-3 overflow-x-auto whitespace-pre-wrap text-xs leading-6 text-white/58",children:JSON.stringify(A.details,null,2)})]}):null]})},A.id):null})}),e.jsx("div",{className:"border-t border-white/6 px-1 py-3 text-center text-xs text-white/46",children:n.isFetchingNextPage?"Loading older logs…":n.hasNextPage?"Scroll to load older logs.":`Showing all ${o.length} loaded logs.`})]})})})]})}function Cw(t){return JSON.stringify(t,null,2)}function So(t){const s=t.trim();if(!s)return{};const i=JSON.parse(s);if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Expected a JSON object.");return i}function Iw(){var T,F,u;const t=Ye(),s=We(),[i,n]=c.useState(""),[a,r]=c.useState(null),[l,d]=c.useState(null),o=pe({queryKey:["forge-operator-session"],queryFn:Ci}),x=o.isSuccess,f=pe({queryKey:["forge-xp-metrics"],queryFn:Ad}),b=pe({queryKey:["forge-reward-rules"],queryFn:dx,enabled:x}),m=pe({queryKey:["forge-reward-ledger"],queryFn:()=>hx(30),enabled:x}),h=pe({queryKey:["forge-psyche-overview"],queryFn:async()=>(await Ba()).overview}),p=Ca({defaultValues:{title:"",description:"",active:!0,configJson:"{}"}}),w=Ca({defaultValues:{entityType:"task",entityId:"",deltaXp:15,reasonTitle:"Operator bonus",reasonSummary:"Manual boost for a meaningful action captured with good provenance.",metadataJson:"{}"}}),v=async()=>{await Promise.all([s.invalidateQueries({queryKey:["forge-xp-metrics"]}),s.invalidateQueries({queryKey:["forge-reward-rules"]}),s.invalidateQueries({queryKey:["forge-reward-ledger"]})])},I=ge({mutationFn:j=>cx(j.ruleId,{title:j.title,description:j.description,active:j.active,config:j.config}),onSuccess:v}),k=ge({mutationFn:mx,onSuccess:v}),S=((T=b.data)==null?void 0:T.rules)??[],M=c.useMemo(()=>{var j,L,q,G,Q,ne;return{system:[{id:"operator_manual_reward",label:"Operator reward ledger"}],goal:t.snapshot.goals.map(H=>({id:H.id,label:H.title})),project:t.snapshot.dashboard.projects.map(H=>({id:H.id,label:H.title})),task:t.snapshot.tasks.map(H=>({id:H.id,label:H.title})),habit:t.snapshot.habits.map(H=>({id:H.id,label:H.title})),tag:t.snapshot.tags.map(H=>({id:H.id,label:H.name})),note:[],insight:[],psyche_value:(((j=h.data)==null?void 0:j.values)??[]).map(H=>({id:H.id,label:H.title})),behavior_pattern:(((L=h.data)==null?void 0:L.patterns)??[]).map(H=>({id:H.id,label:H.title})),behavior:(((q=h.data)==null?void 0:q.behaviors)??[]).map(H=>({id:H.id,label:H.title})),belief_entry:(((G=h.data)==null?void 0:G.beliefs)??[]).map(H=>({id:H.id,label:H.statement})),mode_profile:(((Q=h.data)==null?void 0:Q.modes)??[]).map(H=>({id:H.id,label:H.title})),trigger_report:(((ne=h.data)==null?void 0:ne.reports)??[]).map(H=>({id:H.id,label:H.title}))}},[h.data,t.snapshot.dashboard.projects,t.snapshot.goals,t.snapshot.habits,t.snapshot.tags,t.snapshot.tasks]);c.useEffect(()=>{var G;const j=w.getValues("entityType"),L=w.getValues("entityId"),q=M[j]??[];L&&q.some(Q=>Q.id===L)||w.setValue("entityId",((G=q[0])==null?void 0:G.id)??"")},[w,M]),c.useEffect(()=>{S.length&&(!i||!S.some(j=>j.id===i))&&n(S[0].id)},[S,i]);const P=S.find(j=>j.id===i)??S[0]??null;c.useEffect(()=>{P&&(p.reset({title:P.title,description:P.description,active:P.active,configJson:Cw(P.config)}),r(null))},[P,p]);const y=(F=f.data)==null?void 0:F.metrics,A=(((u=m.data)==null?void 0:u.ledger)??[]).filter(j=>j.metadata.manual===!0).slice(0,8);return o.isLoading?e.jsx(It,{eyebrow:"Settings · Rewards",title:"Loading reward controls",description:"Establishing the operator session and fetching reward configuration.",columns:2,blocks:6}):o.isError?e.jsx(Oe,{eyebrow:"Settings · Rewards",error:o.error,onRetry:()=>void o.refetch()}):e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(Ke,{title:"Rewards",description:"XP command deck, reward rule editor, manual bonus grants, and ledger history."}),e.jsx(gs,{}),e.jsx("div",{className:"grid gap-5",children:e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Reward operations"}),e.jsxs("div",{className:"mt-4 grid gap-4",children:[y?e.jsx(xc,{profile:y.profile,achievements:y.achievements,milestoneRewards:y.milestoneRewards,momentumPulse:y.momentumPulse,recentLedger:y.recentLedger}):null,y?e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(ks,{label:"Total XP",value:y.profile.totalXp,tone:"core"}),e.jsx(ks,{label:"Daily ambient",value:`${y.dailyAmbientXp} / ${y.dailyAmbientCap}`,tone:"core"})]}):null,e.jsxs("div",{className:"grid gap-4 xl:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:"Reward rule editor"}),S.length>0?e.jsxs("form",{className:"mt-4 grid gap-4",onSubmit:p.handleSubmit(async j=>{try{r(null);const L=So(j.configJson);if(!P)return;await I.mutateAsync({ruleId:P.id,title:j.title,description:j.description,active:j.active,config:L})}catch(L){r(L instanceof Error?L.message:"Invalid reward rule config.")}}),children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Rule"}),e.jsx("select",{className:"rounded-[14px] bg-white/[0.06] px-3 py-3 text-white",value:i,onChange:j=>n(j.target.value),children:S.map(j=>e.jsx("option",{value:j.id,children:j.title},j.id))})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Title"}),e.jsx(ie,{...p.register("title")})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Description"}),e.jsx(Ce,{className:"min-h-24",...p.register("description")})]}),e.jsxs("label",{className:"flex items-center justify-between rounded-[18px] bg-[rgba(8,13,28,0.68)] px-4 py-3",children:[e.jsx("span",{className:"text-white/72",children:"Rule is active"}),e.jsx("input",{type:"checkbox",...p.register("active")})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Config JSON"}),e.jsx(Ce,{className:"min-h-28 font-mono text-xs",...p.register("configJson")})]}),a?e.jsx("div",{className:"text-sm text-amber-300",children:a}):null,e.jsx(W,{type:"submit",pending:I.isPending,pendingLabel:"Saving rule",children:"Save reward rule"})]}):e.jsx("div",{className:"mt-4 text-sm text-white/58",children:"Loading reward rules…"})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:"Manual bonus XP"}),e.jsxs("form",{className:"mt-4 grid gap-4",onSubmit:w.handleSubmit(async j=>{try{d(null);const L=So(j.metadataJson);await k.mutateAsync({entityType:j.entityType,entityId:j.entityId,deltaXp:j.deltaXp,reasonTitle:j.reasonTitle,reasonSummary:j.reasonSummary,metadata:L}),w.reset({...j,entityId:"",reasonTitle:"Operator bonus",reasonSummary:"Manual boost for a meaningful action captured with good provenance.",metadataJson:"{}"})}catch(L){d(L instanceof Error?L.message:"Invalid metadata payload.")}}),children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Entity type"}),e.jsx("select",{className:"rounded-[14px] bg-white/[0.06] px-3 py-3 text-white",...w.register("entityType"),children:Object.keys(M).map(j=>e.jsx("option",{value:j,children:j.replaceAll("_"," ")},j))})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Entity id"}),e.jsx("select",{className:"rounded-[14px] bg-white/[0.06] px-3 py-3 text-white",...w.register("entityId"),children:(M[w.watch("entityType")]??[]).map(j=>e.jsx("option",{value:j.id,children:j.label},j.id))})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Delta XP"}),e.jsx(ie,{type:"number",...w.register("deltaXp",{valueAsNumber:!0})})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Reason title"}),e.jsx(ie,{...w.register("reasonTitle")})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Reason summary"}),e.jsx(Ce,{className:"min-h-24",...w.register("reasonSummary")})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Metadata JSON"}),e.jsx(Ce,{className:"min-h-24 font-mono text-xs",...w.register("metadataJson")})]}),l?e.jsx("div",{className:"text-sm text-amber-300",children:l}):null,e.jsx(W,{type:"submit",pending:k.isPending,pendingLabel:"Issuing bonus",children:"Issue bonus XP"})]}),k.data?e.jsxs("div",{className:"mt-4 rounded-[18px] bg-[rgba(192,193,255,0.12)] p-4 text-sm text-white",children:["Granted ",k.data.reward.deltaXp>0?"+":"",k.data.reward.deltaXp," XP for ",e.jsx("strong",{children:k.data.reward.reasonTitle}),"."]}):null]})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:"Manual bonus history"}),e.jsx("div",{className:"mt-4 grid gap-3",children:A.length===0?e.jsx("div",{className:"rounded-[18px] bg-[rgba(8,13,28,0.68)] p-4 text-sm text-white/58",children:"No manual bonus grants yet."}):A.map(j=>e.jsxs("div",{className:"rounded-[18px] bg-[rgba(8,13,28,0.68)] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:j.reasonTitle}),e.jsxs(O,{className:j.deltaXp>=0?"text-emerald-300":"text-amber-300",children:[j.deltaXp>0?"+":"",j.deltaXp," XP"]})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:j.reasonSummary||"No summary supplied."}),e.jsxs("div",{className:"mt-2 text-xs uppercase tracking-[0.16em] text-white/38",children:[j.entityType," · ",j.entityId," · ",new Date(j.createdAt).toLocaleString()]})]},j.id))})]})]})]})})]})}const _c=[{id:"visibility",label:"Discovery and visibility",description:"What the source user can discover, inspect, and pull into read flows on the target side.",rights:[{key:"discoverable",label:"Discoverable",description:"The target appears as a reachable collaborator in the source user's graph and pickers."},{key:"canListUsers",label:"List users",description:"The source user can include the target in directory, comparison, and routing surfaces."},{key:"canReadProfile",label:"Read profile",description:"The source user can inspect the target's identity card, handle, type, and description."},{key:"canReadEntities",label:"Read entities",description:"The source user can read the target's goals, projects, tasks, notes, strategies, and related records."},{key:"canSearchEntities",label:"Search entities",description:"The source user can find the target's work through Forge search and entity pickers."}]},{id:"coordination",label:"Messaging, context, and handoff",description:"What the source user can message, connect, and coordinate on the target side before changing execution.",rights:[{key:"canLinkEntities",label:"Share context",description:"The source user can attach the target's records into shared notes, strategies, calendar context, and cross-owner plans."},{key:"canCoordinate",label:"Message and coordinate",description:"The source user can communicate with the target through Forge, hand off work, and coordinate execution."},{key:"canViewMetrics",label:"View metrics",description:"The source user can inspect the target's XP, alignment, and progress metrics."},{key:"canViewActivity",label:"View activity",description:"The source user can inspect the target's activity stream, evidence, and execution trail."}]},{id:"execution",label:"Plan and execution control",description:"What the source user can actually change on the target side once collaboration is trusted.",rights:[{key:"canManageStrategies",label:"Manage strategies",description:"The source user can draft and update strategies that belong to the target."},{key:"canCreateOnBehalf",label:"Create on behalf",description:"The source user can intentionally create new target-owned entities."},{key:"canAffectEntities",label:"Affect entities",description:"The source user can mutate work that belongs to the target."}]}],Tw=[{id:"full_collab",label:"Full collaboration",description:"Use when two humans or agents can see, coordinate, plan, and change each other's work.",rights:{discoverable:!0,canListUsers:!0,canReadProfile:!0,canReadEntities:!0,canSearchEntities:!0,canLinkEntities:!0,canCoordinate:!0,canAffectEntities:!0,canManageStrategies:!0,canCreateOnBehalf:!0,canViewMetrics:!0,canViewActivity:!0}},{id:"coordination_only",label:"Coordinate only",description:"Use when the source user may see and coordinate with the target but should not directly mutate target-owned work.",rights:{discoverable:!0,canListUsers:!0,canReadProfile:!0,canReadEntities:!0,canSearchEntities:!0,canLinkEntities:!0,canCoordinate:!0,canAffectEntities:!1,canManageStrategies:!0,canCreateOnBehalf:!1,canViewMetrics:!0,canViewActivity:!0}},{id:"observe_only",label:"Observe only",description:"Use when the source user should keep visibility into the target without planning or execution control.",rights:{discoverable:!0,canListUsers:!0,canReadProfile:!0,canReadEntities:!0,canSearchEntities:!0,canLinkEntities:!1,canCoordinate:!1,canAffectEntities:!1,canManageStrategies:!1,canCreateOnBehalf:!1,canViewMetrics:!0,canViewActivity:!0}},{id:"hidden",label:"Hidden edge",description:"Use when this direction should stop discovering, reading, or acting on the target.",rights:{discoverable:!1,canListUsers:!1,canReadProfile:!1,canReadEntities:!1,canSearchEntities:!1,canLinkEntities:!1,canCoordinate:!1,canAffectEntities:!1,canManageStrategies:!1,canCreateOnBehalf:!1,canViewMetrics:!1,canViewActivity:!1}}],fi=_c.reduce((t,s)=>t+s.rights.length,0);function Za(t){return Object.values(t.config.rights).filter(Boolean).length}function Rc(t){const s=[];return t.config.rights.canReadEntities&&s.push("See"),t.config.rights.canCoordinate&&s.push("Message"),t.config.rights.canManageStrategies&&s.push("Plan"),t.config.rights.canAffectEntities&&s.push("Affect"),s.join(" · ")||"Hidden"}function Pw(t){return!t.config.rights.discoverable&&!t.config.rights.canReadEntities?"Hidden":t.config.rights.canAffectEntities&&t.config.rights.canManageStrategies?"Trusted":t.config.rights.canCoordinate||t.config.rights.canLinkEntities?"Coordinated":"Observed"}function zc(t){return[{id:"see",label:"See",enabled:t.config.rights.discoverable&&t.config.rights.canReadEntities&&t.config.rights.canSearchEntities},{id:"message",label:"Message",enabled:t.config.rights.canCoordinate},{id:"share",label:"Share context",enabled:t.config.rights.canLinkEntities},{id:"plan",label:"Plan",enabled:t.config.rights.canManageStrategies},{id:"affect",label:"Affect",enabled:t.config.rights.canAffectEntities||t.config.rights.canCreateOnBehalf}]}function Mw(t,s){return Object.entries(s.rights).every(([i,n])=>t.config.rights[i]===n)}function Ew(t,s){const i=t.filter(l=>l.kind==="human"),n=t.filter(l=>l.kind==="bot"),a=[{entries:i,x:120},{entries:n,x:1040}],r=new Set(s.selectedGrant?[s.selectedGrant.subjectUserId,s.selectedGrant.targetUserId]:s.selectedUserId?[s.selectedUserId]:[]);return a.flatMap(l=>l.entries.map((d,o)=>{const x=r.has(d.id),f=d.id===s.selectedUserId;return{id:d.id,position:{x:l.x,y:64+o*168},draggable:!1,selectable:!1,data:{label:e.jsxs("div",{className:`min-w-[206px] rounded-[22px] border px-4 py-4 shadow-[0_24px_60px_rgba(0,0,0,0.28)] transition ${f?"border-[rgba(244,185,122,0.45)] bg-[rgba(27,16,10,0.92)]":x?"border-white/18 bg-[rgba(14,20,34,0.94)]":"border-white/10 bg-[rgba(9,15,28,0.92)]"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx($e,{user:d}),e.jsx(O,{className:"bg-white/[0.08] text-white/65",children:d.kind})]}),e.jsxs("div",{className:"mt-3 text-xs text-white/52",children:["@",d.handle]}),e.jsx("div",{className:"mt-2 line-clamp-2 text-xs leading-5 text-white/46",children:d.description||"No user description yet."})]})},style:{background:"transparent",border:"none",padding:0}}}))}function Aw(t,s,i){return t.filter(n=>n.subjectUserId!==n.targetUserId).map(n=>{const a=s===n.id,r=i!==null&&(n.subjectUserId===i||n.targetUserId===i),l=Za(n),d=a?"#f4b97a":!n.config.rights.discoverable&&!n.config.rights.canReadEntities?"rgba(248,113,113,0.55)":r?"rgba(192,193,255,0.78)":"rgba(255,255,255,0.32)";return{id:n.id,source:n.subjectUserId,target:n.targetUserId,label:`${Rc(n)} · ${l}/${fi}`,markerEnd:{type:Zo.ArrowClosed,color:d},labelStyle:{fill:a?"#f4b97a":"rgba(255,255,255,0.68)",fontSize:11,fontWeight:600},style:{stroke:d,strokeWidth:a?2.5:r?1.8:1.25},animated:a}})}function Lw({users:t,grants:s,selectedGrantId:i=null,selectedUserId:n=null,onOpenGrant:a,onOpenUser:r}){const l=s.find(h=>h.id===i)??null,d=c.useMemo(()=>Ew(t,{selectedUserId:n,selectedGrant:l}),[l,n,t]),o=c.useMemo(()=>Aw(s,i,n),[s,i,n]),x=c.useMemo(()=>s.filter(h=>h.subjectUserId!==h.targetUserId),[s]),f=x.filter(h=>Za(h)===fi).length,b=x.filter(h=>h.config.rights.canCoordinate).length,m=x.filter(h=>h.config.rights.canAffectEntities||h.config.rights.canCreateOnBehalf).length;return e.jsxs(se,{className:"overflow-hidden p-0",children:[e.jsxs("div",{className:"grid gap-4 border-b border-white/8 px-5 py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"max-w-3xl",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Directed relationship graph"}),e.jsx(Xe,{content:"Keep Forge, OpenClaw, Hermes, and the browser on the same runtime and storage root when these arrows should describe one shared human and bot system.",label:"Explain the shared runtime rule"})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Click a user card to open that user's settings. Click any arrow to open the exact directional relationship flow for that lane."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(O,{className:"bg-white/[0.08] text-white/70",children:[x.length," edges"]}),e.jsxs(O,{className:"bg-emerald-500/12 text-emerald-200",children:[f," fully open"]})]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Full collaboration"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:f}),e.jsx("div",{className:"text-xs leading-5 text-white/48",children:"Directions still running with the default fully open posture."})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Coordination lanes"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:b}),e.jsx("div",{className:"text-xs leading-5 text-white/48",children:"Directions allowed to coordinate directly through Forge."})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Execution control"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:m}),e.jsx("div",{className:"text-xs leading-5 text-white/48",children:"Directions allowed to create or mutate target-owned work."})]})]})]}),e.jsx("div",{className:"h-[min(72vh,54rem)] min-h-[34rem] bg-[radial-gradient(circle_at_top,rgba(244,185,122,0.08),transparent_34%),linear-gradient(180deg,rgba(6,10,20,0.97),rgba(8,14,26,0.94))]",children:e.jsxs(Jo,{nodes:d,edges:o,fitView:!0,fitViewOptions:{padding:.12,maxZoom:1},nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,onNodeClick:(h,p)=>{r(p.id)},onEdgeClick:(h,p)=>{a(p.id)},attributionPosition:"bottom-left",children:[e.jsx(Yo,{showInteractive:!1}),e.jsx(Vo,{gap:28,size:1,color:"rgba(255,255,255,0.06)"})]})})]})}const Dw={kind:"human",handle:"",displayName:"",description:"",accentColor:"#c0c1ff"};function Co(t){return t?{kind:t.kind,handle:t.handle,displayName:t.displayName,description:t.description,accentColor:t.accentColor}:Dw}function $w({open:t,onOpenChange:s,user:i,grants:n,ownership:a,xp:r,pending:l=!1,onSubmit:d,onOpenRelationship:o}){const[x,f]=c.useState(()=>Co(i)),[b,m]=c.useState(null);c.useEffect(()=>{t&&(f(Co(i)),m(null))},[t,i]);const h=c.useMemo(()=>n.filter(I=>I.subjectUserId!==I.targetUserId),[n]),p=c.useMemo(()=>i?h.filter(I=>I.subjectUserId===i.id):[],[h,i]),w=c.useMemo(()=>i?h.filter(I=>I.targetUserId===i.id):[],[h,i]),v=[{id:"identity",eyebrow:i?"Edit user":"Create user",title:i?"Update the user identity":"Add a human or bot user",description:"Set the owner type and the public identity Forge will use across ownership, routing, and collaboration surfaces.",render:(I,k)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Kind",description:"Humans represent real people. Bots represent agents or automations with their own ownership lane.",children:e.jsx(tt,{columns:2,value:I.kind,onChange:S=>k({kind:S}),options:[{value:"human",label:"Human",description:"Use for a real person in the Forge runtime."},{value:"bot",label:"Bot",description:"Use for an agent, assistant, or automation actor."}]})}),e.jsx(Y,{label:"Handle",description:"This becomes the stable short id shown as @handle.",hint:"Use lowercase and a durable label, for example forge-operator or planner-bot.",children:e.jsx(ie,{value:I.handle,onChange:S=>k({handle:S.target.value}),placeholder:"forge-operator"})}),e.jsx(Y,{label:"Display name",description:"This is the human-readable label used across the UI.",children:e.jsx(ie,{value:I.displayName,onChange:S=>k({displayName:S.target.value}),placeholder:"Forge Operator"})})]})},{id:"profile",eyebrow:"Profile",title:"Describe the user lane",description:"Capture what this user represents in the shared Forge runtime and pick the accent color that helps the lane stay recognizable.",render:(I,k)=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{label:"Description",description:"Explain what this user is responsible for and what side of the system it represents.",children:e.jsx(Ce,{value:I.description,onChange:S=>k({description:S.target.value}),className:"min-h-36",placeholder:"Primary human operator for strategy, execution, and review."})}),e.jsx(Y,{label:"Accent color",description:"Forge uses this accent to help the user stand out in ownership and collaboration surfaces.",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ie,{value:I.accentColor,onChange:S=>k({accentColor:S.target.value}),placeholder:"#c0c1ff"}),e.jsx("div",{className:"size-10 shrink-0 rounded-full border border-white/10",style:{backgroundColor:I.accentColor||"#c0c1ff"}})]})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Owned records"}),e.jsx("div",{className:"mt-2 text-white",children:(a==null?void 0:a.totalOwnedEntities)??0})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Total XP"}),e.jsx("div",{className:"mt-2 text-white",children:(r==null?void 0:r.totalXp)??0})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Weekly XP"}),e.jsx("div",{className:"mt-2 text-white",children:(r==null?void 0:r.weeklyXp)??0})]})]})]})},{id:"relationships",eyebrow:"Relationships",title:"Open directional relationship settings",description:"Each arrow is a separate contract. Open the exact lane you want to adjust and Forge will take you into the relationship flow.",render:()=>i?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx($e,{user:i}),e.jsxs("div",{className:"mt-3 text-sm leading-6 text-white/56",children:["@",i.handle," · ",i.description||"No description yet."]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Outbound lanes"}),p.length>0?p.map(I=>e.jsxs("button",{type:"button",className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-4 text-left transition hover:bg-white/[0.05]",onClick:()=>o(I.id),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx($e,{user:I.subjectUser}),e.jsx("span",{className:"text-white/45",children:"→"}),e.jsx($e,{user:I.targetUser})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(O,{className:"bg-white/[0.08] text-white/74",children:Rc(I)}),e.jsxs(O,{className:"bg-white/[0.08] text-white/74",children:[Za(I),"/",fi," rights"]})]})]},I.id)):e.jsx("div",{className:"rounded-[20px] border border-dashed border-white/10 bg-white/[0.02] px-4 py-4 text-sm text-white/52",children:"No outbound relationship lanes yet."})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Inbound lanes"}),w.length>0?w.map(I=>e.jsxs("button",{type:"button",className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-4 text-left transition hover:bg-white/[0.05]",onClick:()=>o(I.id),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx($e,{user:I.subjectUser}),e.jsx("span",{className:"text-white/45",children:"→"}),e.jsx($e,{user:I.targetUser})]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:zc(I).map(k=>e.jsx(O,{className:k.enabled?"bg-white/[0.08] text-white/74":"bg-white/[0.04] text-white/38",children:k.label},`${I.id}-${k.id}`))})]},I.id)):e.jsx("div",{className:"rounded-[20px] border border-dashed border-white/10 bg-white/[0.02] px-4 py-4 text-sm text-white/52",children:"No inbound relationship lanes yet."})]})]})]}):e.jsx("div",{className:"rounded-[20px] border border-dashed border-white/10 bg-white/[0.02] px-4 py-4 text-sm leading-6 text-white/52",children:"Create the user first, then Forge will generate the directional relationship lanes you can tune from here."})}];return e.jsx(it,{open:t,onOpenChange:s,eyebrow:i?"User settings":"Create user",title:i?"User settings":"Create user",description:"Edit the user identity, clarify what this lane represents, and jump into relationship settings without crowding the page.",value:x,onChange:f,steps:v,submitLabel:i?"Save user":"Create user",pending:l,pendingLabel:i?"Saving user":"Creating user",error:b,contentClassName:"lg:w-[min(58rem,calc(100vw-1.5rem))]",onSubmit:async()=>{const I=x.handle.trim(),k=x.displayName.trim();if(I.length===0){m("Add a handle before saving this user.");return}if(k.length===0){m("Add a display name before saving this user.");return}await d({userId:i==null?void 0:i.id,input:{kind:x.kind,handle:I,displayName:k,description:x.description.trim(),accentColor:x.accentColor.trim()||"#c0c1ff"}}),s(!1)}})}function Io(t,s){return{accessLevel:(t==null?void 0:t.accessLevel)??"manage",applyScope:"this_arrow",rights:{discoverable:(t==null?void 0:t.config.rights.discoverable)??!0,canListUsers:(t==null?void 0:t.config.rights.canListUsers)??!0,canReadProfile:(t==null?void 0:t.config.rights.canReadProfile)??!0,canReadEntities:(t==null?void 0:t.config.rights.canReadEntities)??!0,canSearchEntities:(t==null?void 0:t.config.rights.canSearchEntities)??!0,canLinkEntities:(t==null?void 0:t.config.rights.canLinkEntities)??!0,canCoordinate:(t==null?void 0:t.config.rights.canCoordinate)??!0,canAffectEntities:(t==null?void 0:t.config.rights.canAffectEntities)??!0,canManageStrategies:(t==null?void 0:t.config.rights.canManageStrategies)??!0,canCreateOnBehalf:(t==null?void 0:t.config.rights.canCreateOnBehalf)??!0,canViewMetrics:(t==null?void 0:t.config.rights.canViewMetrics)??!0,canViewActivity:(t==null?void 0:t.config.rights.canViewActivity)??!0}}}function Ow({open:t,onOpenChange:s,grant:i,grants:n,pending:a=!1,onSubmit:r}){const l=c.useMemo(()=>i?n.find(m=>m.subjectUserId===i.targetUserId&&m.targetUserId===i.subjectUserId)??null:null,[i,n]),[d,o]=c.useState(()=>Io(i,!!l));c.useEffect(()=>{t&&o(Io(i,!!l))},[i,t,l]);const x=c.useMemo(()=>Object.values(d.rights).filter(Boolean).length,[d.rights]),f=Math.round(x/fi*100),b=[{id:"posture",eyebrow:"Relationship posture",title:"Set the trust mode for this arrow",description:"Each arrow is directional. Decide whether you want to tune only this lane or mirror the same contract onto both directions.",render:(m,h)=>e.jsxs(e.Fragment,{children:[i?e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx($e,{user:i.subjectUser}),e.jsx("span",{className:"text-white/45",children:"→"}),e.jsx($e,{user:i.targetUser})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(O,{className:"bg-white/[0.08] text-white/74",children:Pw(i)}),e.jsxs(O,{className:"bg-white/[0.08] text-white/74",children:[Za(i),"/",fi," rights"]})]})]}):null,e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Access level"}),e.jsx(tt,{columns:2,value:m.accessLevel,onChange:p=>h({accessLevel:p}),options:[{value:"view",label:"View",description:"Use when this lane should stay mostly observational."},{value:"manage",label:"Manage",description:"Use when the source side can actively collaborate or act."}]})]}),l?e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Apply scope"}),e.jsx(tt,{columns:2,value:m.applyScope,onChange:p=>h({applyScope:p}),options:[{value:"this_arrow",label:"This arrow",description:"Only change the exact direction you opened."},{value:"both_arrows",label:"Both arrows",description:"Mirror the same contract onto the reverse direction too."}]})]}):null]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Quick preset"}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:Tw.map(p=>e.jsxs("button",{type:"button",className:`rounded-[22px] border p-4 text-left transition ${i&&Mw(i,p)?"border-[rgba(244,185,122,0.35)] bg-[rgba(244,185,122,0.08)]":"border-white/8 bg-white/[0.03] hover:bg-white/[0.05]"}`,onClick:()=>h({rights:{...m.rights,...p.rights}}),children:[e.jsx("div",{className:"text-sm font-medium text-white",children:p.label}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:p.description})]},p.id))})]})]})},{id:"rights",eyebrow:"Rights",title:"Tune the individual permissions",description:"Use the preset as the starting point, then sharpen the exact boundaries only where this relationship needs them.",render:(m,h)=>e.jsx(e.Fragment,{children:_c.map(p=>e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-white",children:p.label}),e.jsx("div",{className:"mt-1 text-sm leading-6 text-white/54",children:p.description})]}),e.jsx("div",{className:"grid gap-2",children:p.rights.map(w=>e.jsxs("label",{className:"flex items-start justify-between gap-3 rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-white",children:w.label}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/50",children:w.description})]}),e.jsx("input",{type:"checkbox",checked:m.rights[w.key],onChange:v=>h({rights:{...m.rights,[w.key]:v.target.checked}})})]},w.key))})]},p.id))})},{id:"review",eyebrow:"Review",title:"Review the final relationship contract",description:"Check the enabled capabilities, confirm whether both directions should match, and then save the relationship.",render:m=>{var h,p;return e.jsx(e.Fragment,{children:e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Capability coverage"}),e.jsx("div",{className:"mt-4",children:e.jsx(ts,{value:f})}),e.jsxs("div",{className:"mt-3 text-sm text-white/62",children:[x,"/",fi," rights enabled"]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:zc({...i??{id:"draft",subjectUserId:"",targetUserId:"",accessLevel:m.accessLevel,config:{self:!1,mutable:!0,linkedEntities:!0,rights:m.rights},createdAt:"",updatedAt:"",subjectUser:null,targetUser:null},accessLevel:m.accessLevel,config:{...(i==null?void 0:i.config)??{self:!1,mutable:!0,linkedEntities:!0},rights:m.rights}}).map(w=>e.jsx(O,{className:w.enabled?"bg-white/[0.08] text-white/74":"bg-white/[0.04] text-white/38",children:w.label},w.id))})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Save scope"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:m.applyScope==="both_arrows"&&l?"Forge will apply the same access level and rights to both directions of this pair.":"Forge will only update the exact arrow you opened."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(O,{className:"bg-white/[0.08] text-white/74",children:["access ",m.accessLevel]}),e.jsxs(O,{className:"bg-white/[0.08] text-white/74",children:["scope"," ",m.applyScope==="both_arrows"&&l?"both arrows":"this arrow"]})]}),l?e.jsxs("div",{className:"mt-4 rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-3 text-sm text-white/54",children:["Reverse arrow available:"," ",((h=l.subjectUser)==null?void 0:h.displayName)??l.subjectUserId," ","→"," ",((p=l.targetUser)==null?void 0:p.displayName)??l.targetUserId]}):null]})]})})}}];return e.jsx(it,{open:t,onOpenChange:s,eyebrow:"Relationship settings",title:"Relationship settings",description:"Edit the exact directional contract between two users without keeping the full rights editor pinned on the page.",value:d,onChange:o,steps:b,submitLabel:"Save relationship",pending:a,pendingLabel:"Saving relationship",contentClassName:"lg:w-[min(62rem,calc(100vw-1.5rem))]",onSubmit:async()=>{i&&(await r({grantId:i.id,patch:{accessLevel:d.accessLevel,rights:d.rights},reverseGrantId:(l==null?void 0:l.id)??null,applyToReverse:d.applyScope==="both_arrows"&&l!==null}),s(!1))}})}function Fw(){var T;const t=Ye(),[s,i]=c.useState(null),[n,a]=c.useState(null),[r,l]=c.useState(!1),[d,o]=c.useState(!1),[x,f]=c.useState(""),b=pe({queryKey:["forge-user-directory"],queryFn:Vp}),m=async()=>{await Promise.all([t.refresh(),b.refetch()])},h=ge({mutationFn:async({input:F,userId:u})=>u?(await tx(u,F)).user:(await ex(F)).user,onSuccess:async()=>{i(null),l(!1),await m()}}),p=ge({mutationFn:async({grantId:F,patch:u})=>(await Zp(F,u)).grant,onSuccess:m}),w=(T=b.data)==null?void 0:T.directory,v=(w==null?void 0:w.grants.find(F=>F.id===n))??null,I=c.useMemo(()=>new Map(((w==null?void 0:w.ownership)??[]).map(F=>[F.userId,F])),[w==null?void 0:w.ownership]),k=c.useMemo(()=>new Map(((w==null?void 0:w.xp)??[]).map(F=>[F.userId,F])),[w==null?void 0:w.xp]),S=c.useMemo(()=>{const F=new Map;for(const u of(w==null?void 0:w.grants)??[]){if(!u.targetUser||u.subjectUserId===u.targetUserId)continue;const j=F.get(u.subjectUserId)??[];j.push(u.targetUser),F.set(u.subjectUserId,j)}return F},[w==null?void 0:w.grants]),M=c.useMemo(()=>{const F=((w==null?void 0:w.grants)??[]).filter(u=>u.subjectUserId!==u.targetUserId);return{totalEdges:F.length,fullyOpenEdges:F.filter(u=>Object.values(u.config.rights).every(Boolean)).length,coordinationEdges:F.filter(u=>u.config.rights.canCoordinate).length,executionEdges:F.filter(u=>u.config.rights.canAffectEntities||u.config.rights.canCreateOnBehalf).length}},[w==null?void 0:w.grants]),P=x.trim().toLowerCase(),y=c.useMemo(()=>{const u=((w==null?void 0:w.users)??t.snapshot.users).filter(j=>P?[j.displayName,j.handle,j.kind,j.description].join(" ").toLowerCase().includes(P):!0);return{humans:u.filter(j=>j.kind==="human"),bots:u.filter(j=>j.kind==="bot")}},[w==null?void 0:w.users,P,t.snapshot.users]),N=(v==null?void 0:v.subjectUserId)??(s==null?void 0:s.id)??null,A=(v==null?void 0:v.id)??null;return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1440px] gap-5",children:[e.jsx(Ke,{title:"Users",description:"Forge users can be human or bot. Ownership, search, and routing are prepared so work can move across both sides of the system.",badge:`${t.snapshot.users.length} users`}),e.jsx(gs,{}),e.jsx($w,{open:r,onOpenChange:l,user:s,grants:(w==null?void 0:w.grants)??[],ownership:s?I.get(s.id)??null:null,xp:s?k.get(s.id)??null:null,pending:h.isPending,onSubmit:async F=>{await h.mutateAsync(F)},onOpenRelationship:F=>{l(!1),a(F),o(!0)}}),e.jsx(Ow,{open:d,onOpenChange:o,grant:v,grants:(w==null?void 0:w.grants)??[],pending:p.isPending,onSubmit:async F=>{await p.mutateAsync({grantId:F.grantId,patch:F.patch}),F.applyToReverse&&F.reverseGrantId&&await p.mutateAsync({grantId:F.reverseGrantId,patch:F.patch})}}),e.jsxs(se,{className:"grid gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Multi-user posture"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:(w==null?void 0:w.posture.summary)??"Forge is preparing modular user access while keeping the current posture permissive."})]}),e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:(w==null?void 0:w.posture.accessModel)??"permissive"})]}),e.jsx("div",{className:"flex items-center gap-3 rounded-[18px] bg-white/[0.04] px-4 py-3",children:e.jsx(ie,{value:x,onChange:F=>f(F.target.value),placeholder:"Search human, bot, @handle, or description"})})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(se,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Multi-agent onboarding"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:"Forge now treats the users graph as the collaboration control plane. Create each human or bot here, keep the runtime shared, then narrow only the specific arrows that should stop seeing, coordinating, planning, or affecting another user."})]}),e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:"default open"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Directional edges"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:M.totalEdges})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Fully open"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:M.fullyOpenEdges})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Coordination"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:M.coordinationEdges})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Execution control"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:M.executionEdges})]})]}),e.jsxs("div",{className:"grid gap-2 text-sm leading-6 text-white/56",children:[e.jsx("div",{children:"1. Create the human and bot users that should exist in the shared Forge system."}),e.jsx("div",{children:"2. Point OpenClaw, Hermes, and the browser at the same Forge runtime and storage root."}),e.jsx("div",{children:"3. Use the graph below to decide what each direction can see, message, plan, or change."}),e.jsx("div",{children:"4. Keep strategy drafting open while the plan is negotiated, then lock the strategy once it becomes the contract."})]})]}),e.jsx(Lw,{users:(w==null?void 0:w.users)??t.snapshot.users,grants:(w==null?void 0:w.grants)??[],selectedGrantId:A,selectedUserId:N,onOpenUser:F=>{const u=((w==null?void 0:w.users)??t.snapshot.users).find(j=>j.id===F)??null;a(null),i(u),l(!0)},onOpenGrant:F=>{i(null),a(F),o(!0)}}),e.jsxs(se,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Agent onboarding"}),e.jsx("div",{className:"text-sm leading-6 text-white/60",children:"OpenClaw, Hermes, and the Forge UI all read this same multi-user graph. Keep the defaults open while you are still wiring collaboration, then narrow specific arrows when one user or agent should stop seeing, messaging, planning, or changing another user's work."}),e.jsx("div",{className:"text-sm leading-6 text-white/52",children:"Forge now treats every owner as either human or bot, keeps search cross-user by default, and allows cross-owner links plus explicit coordination lanes between projects, tasks, notes, and strategies."}),e.jsx("div",{children:e.jsx(Le,{to:"/settings/agents",className:"inline-flex min-h-10 items-center justify-center rounded-[var(--radius-control)] bg-white/8 px-3 py-2 text-[13px] font-medium text-white transition hover:bg-white/12",children:"Open agent onboarding"})})]})]}),e.jsx(se,{children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"User directory"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:"Open any user to edit its identity and jump into the exact directional relationship lanes from the user settings flow."})]}),e.jsx(W,{onClick:()=>{a(null),i(null),l(!0)},children:"Create user"})]})}),e.jsx("div",{className:"grid gap-5",children:[{title:"Human users",users:y.humans},{title:"Bot users",users:y.bots}].map(F=>e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:F.title}),e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:F.users.length})]}),e.jsx("div",{className:"mt-4 grid gap-3",children:F.users.map(u=>{var j,L,q,G,Q,ne;return e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx($e,{user:u}),e.jsxs("div",{className:"mt-3 text-sm text-white/58",children:["@",u.handle]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:u.description||"No description yet."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(O,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[((j=k.get(u.id))==null?void 0:j.totalXp)??0," XP"]}),e.jsxs(O,{className:"bg-white/[0.08] text-white/70",children:[((L=k.get(u.id))==null?void 0:L.weeklyXp)??0," weekly"]}),e.jsxs(O,{className:"bg-white/[0.08] text-white/70",children:[((q=k.get(u.id))==null?void 0:q.rewardEventCount)??0," ","rewards"]}),Object.entries(((G=I.get(u.id))==null?void 0:G.entityCounts)??{}).sort((H,_)=>_[1]-H[1]).slice(0,4).map(([H,_])=>e.jsxs(O,{className:"bg-white/[0.08] text-white/70",children:[_," ",H]},`${u.id}-${H}`)),e.jsxs(O,{className:"bg-white/[0.08] text-white/70",children:[((Q=I.get(u.id))==null?void 0:Q.totalOwnedEntities)??0," ","owned"]})]}),e.jsxs("div",{className:"mt-3 text-xs leading-5 text-white/50",children:["Can currently read:"," ",(S.get(u.id)??[]).map(H=>`${H.displayName} (${H.kind})`).join(", ")||"no other users"]}),(ne=k.get(u.id))!=null&&ne.lastRewardAt?e.jsxs("div",{className:"mt-2 text-xs leading-5 text-white/45",children:["Last XP movement:"," ",new Date(k.get(u.id).lastRewardAt).toLocaleString()]}):null]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(W,{variant:"secondary",onClick:()=>{a(null),i(u),l(!0)},children:"Open settings"})})]})},u.id)})})]},F.title))})]})]})}function ms(t,s,i,n){return{value:t,label:s,description:i,searchText:`${s} ${i}`,kind:n}}function qc(t){return[...t.goals.map(s=>ms(`goal:${s.id}`,s.title,"Goal","goal")),...t.projects.map(s=>ms(`project:${s.id}`,s.title,"Project","project")),...t.tasks.map(s=>ms(`task:${s.id}`,s.title,"Task","task")),...t.habits.map(s=>ms(`habit:${s.id}`,s.title,"Habit","habit")),...t.values.map(s=>ms(`psyche_value:${s.id}`,s.title,"Value","value")),...t.patterns.map(s=>ms(`behavior_pattern:${s.id}`,s.title,"Pattern","pattern")),...t.behaviors.map(s=>ms(`behavior:${s.id}`,s.title,"Behavior","behavior")),...t.beliefs.map(s=>ms(`belief_entry:${s.id}`,s.statement,"Belief","belief")),...t.reports.map(s=>ms(`trigger_report:${s.id}`,s.title,"Report","report"))]}function Bc(t){return t.map(s=>{const i=s.indexOf(":");if(i===-1)return null;const n=s.slice(0,i),a=s.slice(i+1);return!n||!a?null:{entityType:n,entityId:a,relationshipType:"context"}}).filter(s=>s!==null)}function li(t){return`${(t/3600).toFixed(1)}h`}function wa(t){return`${Math.round(t*100)}%`}function To(t){return t?new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"n/a"}function _w(){const t=Ye(),s=We(),[i,n]=c.useState({}),a=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],r=pe({queryKey:["forge-sleep",...a],queryFn:async()=>(await Qp(a)).sleep}),l=pe({queryKey:["forge-sleep-values",...a],queryFn:async()=>(await ls(a)).values}),d=pe({queryKey:["forge-sleep-patterns",...a],queryFn:async()=>(await Xs(a)).patterns}),o=pe({queryKey:["forge-sleep-behaviors",...a],queryFn:async()=>(await os(a)).behaviors}),x=pe({queryKey:["forge-sleep-beliefs",...a],queryFn:async()=>(await As(a)).beliefs}),f=pe({queryKey:["forge-sleep-reports",...a],queryFn:async()=>(await Ti(a)).reports});c.useEffect(()=>{r.data&&n(Object.fromEntries(r.data.sessions.map(S=>[S.id,{qualitySummary:typeof S.annotations.qualitySummary=="string"?S.annotations.qualitySummary:"",notes:typeof S.annotations.notes=="string"?S.annotations.notes:"",tagsText:Array.isArray(S.annotations.tags)?S.annotations.tags.join(", "):"",linkValues:S.links.map(M=>`${M.entityType}:${M.entityId}`)}])))},[r.data]);const b=ge({mutationFn:async S=>Yp(S.sleepId,{qualitySummary:S.qualitySummary,notes:S.notes,tags:S.tagsText.split(",").map(M=>M.trim()).filter(Boolean),links:Bc(S.linkValues)}),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-sleep"]})}});if(r.isLoading)return e.jsx(It,{eyebrow:"Sleep",title:"Loading sleep view",description:"Reading HealthKit sleep sessions and reflective links.",columns:2,blocks:6});if(r.isError||!r.data)return e.jsx(Oe,{eyebrow:"Sleep",error:r.error??new Error("Sleep data unavailable"),onRetry:()=>void r.refetch()});const{summary:m,weeklyTrend:h,monthlyPattern:p,stageAverages:w,linkBreakdown:v,sessions:I}=r.data,k=qc({goals:t.snapshot.dashboard.goals,projects:t.snapshot.dashboard.projects,tasks:t.snapshot.dashboard.tasks,habits:t.snapshot.dashboard.habits,values:l.data??[],patterns:d.data??[],behaviors:o.data??[],beliefs:x.data??[],reports:f.data??[]});return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{entityKind:"habit",title:"Sleep",description:"A reflective sleep surface linking rest, timing, and Psyche-aware context instead of treating nights as disposable telemetry.",badge:`${I.length} nights`}),e.jsx(Ht,{}),e.jsxs("section",{className:"grid gap-4 lg:grid-cols-4",children:[e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Weekly sleep"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-[var(--primary)]",children:li(m.totalSleepSeconds)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Total sleep across the recent week."})]}),e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Average night"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:li(m.averageSleepSeconds)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Mean sleep duration across recent nights."})]}),e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Sleep score"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:m.averageSleepScore}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Derived score from duration, efficiency, and stages."})]}),e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Regularity"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:m.averageRegularityScore}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Timing consistency across recent nights."})]}),e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Efficiency"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:wa(m.averageEfficiency)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Average time asleep relative to time in bed."})]}),e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Restorative share"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:wa(m.averageRestorativeShare)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Deep and REM share across the recent week."})]}),e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Reflected nights"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:m.reflectiveNightCount}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Nights carrying notes, tags, or linked Psyche context."})]}),e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Bed and wake window"}),e.jsxs("div",{className:"mt-3 text-xl text-white",children:[m.averageBedtimeConsistencyMinutes,"m /"," ",m.averageWakeConsistencyMinutes,"m"]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Mean bedtime and wake-time drift against your recent baseline."})]})]}),e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[1.1fr_0.9fr]",children:[e.jsxs(se,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Trend"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Recent sleep pattern"})]}),e.jsx(O,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"7 nights"})]}),e.jsx("div",{className:"grid gap-3",children:h.map(S=>e.jsxs("div",{className:"grid gap-2 rounded-[18px] bg-white/[0.04] px-4 py-3 md:grid-cols-[110px_minmax(0,1fr)_100px_100px]",children:[e.jsx("div",{className:"text-sm text-white/62",children:S.dateKey}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-2 flex-1 overflow-hidden rounded-full bg-white/[0.08]",children:e.jsx("div",{className:"h-full rounded-full bg-[var(--primary)]",style:{width:`${Math.min(100,S.sleepHours/10*100)}%`}})}),e.jsxs("div",{className:"text-sm text-white",children:[S.sleepHours.toFixed(1),"h"]})]}),e.jsxs("div",{className:"text-sm text-white/62",children:["Score ",S.score]}),e.jsxs("div",{className:"text-sm text-white/62",children:["Reg ",S.regularity]})]},S.id))}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Latest bedtime"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:To(m.latestBedtime)})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Latest wake"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:To(m.latestWakeTime)})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Linked nights"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:m.linkedNightCount})]})]})]}),e.jsxs(se,{className:"grid gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Pattern surfaces"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Stage, timing, and linked context"})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Average stages"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:w.length>0?w.map(S=>e.jsxs(O,{tone:"meta",children:[S.stage," ",li(S.averageSeconds)]},S.stage)):e.jsx("div",{className:"text-sm text-white/48",children:"Stage data will appear here when HealthKit exposes it."})})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Most-linked context"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:v.length>0?v.slice(0,6).map(S=>e.jsxs(O,{tone:"meta",children:[S.entityType.replaceAll("_"," ")," ",S.count]},S.entityType)):e.jsx("div",{className:"text-sm text-white/48",children:"Linked habits, beliefs, projects, and reports will accumulate here."})})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Monthly timing"}),e.jsx("div",{className:"mt-3 grid gap-2",children:p.slice(-5).map(S=>e.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm text-white/66",children:[e.jsx("span",{children:S.dateKey}),e.jsxs("span",{children:[S.onsetHour,":00 to ",S.wakeHour,":00"]}),e.jsxs("span",{children:[S.sleepHours.toFixed(1),"h"]})]},S.id))})]})]})]})]}),e.jsx("div",{className:"grid gap-4",children:I.map(S=>{const M=i[S.id]??{qualitySummary:"",notes:"",tagsText:"",linkValues:[]};return e.jsxs(se,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-lg text-white",children:[e.jsx(nh,{className:"size-4 text-[var(--primary)]"}),e.jsxs("span",{children:[new Date(S.startedAt).toLocaleString()," to"," ",new Date(S.endedAt).toLocaleString()]})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsxs(O,{children:[li(S.asleepSeconds)," asleep"]}),e.jsxs(O,{tone:"meta",children:[li(S.timeInBedSeconds)," in bed"]}),e.jsxs(O,{tone:"meta",children:["Score ",S.sleepScore??"n/a"]}),e.jsxs(O,{tone:"meta",children:["Eff"," ",wa(typeof S.derived.efficiency=="number"?S.derived.efficiency:S.timeInBedSeconds>0?S.asleepSeconds/S.timeInBedSeconds:0)]}),e.jsxs(O,{tone:"meta",children:["Restorative"," ",wa(typeof S.derived.restorativeShare=="number"?S.derived.restorativeShare:0)]}),e.jsxs(O,{tone:"meta",children:[S.links.length," linked entities"]})]})]}),e.jsxs(W,{size:"sm",pending:b.isPending,pendingLabel:"Saving",onClick:()=>void b.mutateAsync({sleepId:S.id,qualitySummary:M.qualitySummary,notes:M.notes,tagsText:M.tagsText,linkValues:M.linkValues}),children:[e.jsx(Zn,{className:"size-4"}),"Save reflection"]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[1.1fr_0.9fr]",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Stage breakdown"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:S.stageBreakdown.length>0?S.stageBreakdown.map(P=>e.jsxs(O,{tone:"meta",children:[P.stage," ",li(P.seconds)]},P.stage)):e.jsx("div",{className:"text-sm text-white/48",children:"No stage data synced for this night."})})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Bedtime drift"}),e.jsxs("div",{className:"mt-2 text-lg text-white",children:[S.bedtimeConsistencyMinutes??0,"m"]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Wake drift"}),e.jsxs("div",{className:"mt-2 text-lg text-white",children:[S.wakeConsistencyMinutes??0,"m"]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Recovery state"}),e.jsx("div",{className:"mt-2 text-lg text-white capitalize",children:typeof S.derived.recoveryState=="string"?S.derived.recoveryState:"n/a"})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Quality summary"}),e.jsx(ie,{value:M.qualitySummary,onChange:P=>n(y=>({...y,[S.id]:{...M,qualitySummary:P.target.value}})),placeholder:"Restless before sleep but recovered by morning."})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Tags"}),e.jsx(ie,{value:M.tagsText,onChange:P=>n(y=>({...y,[S.id]:{...M,tagsText:P.target.value}})),placeholder:"overload, rumination, travel, good-routine"})]})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Reflection, habits, beliefs, or trigger context"}),e.jsx(Ce,{className:"min-h-[120px]",value:M.notes,onChange:P=>n(y=>({...y,[S.id]:{...M,notes:P.target.value}})),placeholder:"Link this night to overload, bedtime rumination, wind-down habits, values conflict, or project pressure."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Linked Forge and Psyche records"}),e.jsx(st,{options:k,selectedValues:M.linkValues,onChange:P=>n(y=>({...y,[S.id]:{...M,linkValues:P}})),placeholder:"Search habits, goals, beliefs, patterns, reports…"})]})]})]})]},S.id)})})]})}function Po(t){return`${Math.round(t/60)}m`}function Rw(t){return t?`${(t/1e3).toFixed(1)} km`:"n/a"}function zw(){const t=Ye(),s=We(),i=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],[n,a]=c.useState({}),r=pe({queryKey:["forge-fitness",...i],queryFn:async()=>(await Wp(i)).fitness}),l=pe({queryKey:["forge-health-values",...i],queryFn:async()=>(await ls(i)).values}),d=pe({queryKey:["forge-health-patterns",...i],queryFn:async()=>(await Xs(i)).patterns}),o=pe({queryKey:["forge-health-behaviors",...i],queryFn:async()=>(await os(i)).behaviors}),x=pe({queryKey:["forge-health-beliefs",...i],queryFn:async()=>(await As(i)).beliefs}),f=pe({queryKey:["forge-health-reports",...i],queryFn:async()=>(await Ti(i)).reports});c.useEffect(()=>{r.data&&a(Object.fromEntries(r.data.sessions.map(I=>[I.id,{subjectiveEffort:I.subjectiveEffort!==null?String(I.subjectiveEffort):"",moodBefore:I.moodBefore??"",moodAfter:I.moodAfter??"",meaningText:I.meaningText??"",plannedContext:I.plannedContext??"",socialContext:I.socialContext??"",tagsText:I.tags.join(", "),linkValues:I.links.map(k=>`${k.entityType}:${k.entityId}`)}])))},[r.data]);const b=ge({mutationFn:async I=>Jp(I.workoutId,{subjectiveEffort:I.subjectiveEffort.trim().length>0?Number(I.subjectiveEffort):null,moodBefore:I.moodBefore,moodAfter:I.moodAfter,meaningText:I.meaningText,plannedContext:I.plannedContext,socialContext:I.socialContext,tags:I.tagsText.split(",").map(k=>k.trim()).filter(Boolean),links:Bc(I.linkValues)}),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-fitness"]})}});if(r.isLoading)return e.jsx(It,{eyebrow:"Sports",title:"Loading sports view",description:"Reading synced workouts and local reflection metadata.",columns:2,blocks:6});if(r.isError||!r.data)return e.jsx(Oe,{eyebrow:"Sports",error:r.error??new Error("Sports data unavailable"),onRetry:()=>void r.refetch()});const{summary:m,weeklyTrend:h,typeBreakdown:p,sessions:w}=r.data,v=qc({goals:t.snapshot.dashboard.goals,projects:t.snapshot.dashboard.projects,tasks:t.snapshot.dashboard.tasks,habits:t.snapshot.dashboard.habits,values:l.data??[],patterns:d.data??[],behaviors:o.data??[],beliefs:x.data??[],reports:f.data??[]});return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{entityKind:"project",title:"Sports",description:"A session-first training surface for workout data, subjective meaning, and links back into Forge execution and Psyche.",badge:`${w.length} sessions`}),e.jsxs("section",{className:"grid gap-4 lg:grid-cols-4",children:[e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Weekly volume"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-[var(--primary)]",children:Po(m.weeklyVolumeSeconds)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Total training time in the recent week."})]}),e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Exercise minutes"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:m.exerciseMinutes}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Aggregate exercise minutes from synced sessions."})]}),e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Energy burned"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:m.energyBurnedKcal}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Recent weekly kcal."})]}),e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Training streak"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:m.streakDays}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Distinct workout days in the recent week."})]}),e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Average session"}),e.jsxs("div",{className:"mt-3 font-display text-4xl text-white",children:[m.averageSessionMinutes,"m"]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Mean duration across recent sessions."})]}),e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Average effort"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:m.averageEffort||"n/a"}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Subjective effort across sessions that carry a rating."})]}),e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Linked sessions"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:m.linkedSessionCount}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Sessions already tied to Forge or Psyche entities."})]}),e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Top block"}),e.jsx("div",{className:"mt-3 text-xl text-white",children:m.topWorkoutType??"n/a"}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Dominant workout type across the recent window."})]})]}),e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[1.05fr_0.95fr]",children:[e.jsxs(se,{className:"grid gap-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Recent volume"}),e.jsx("div",{className:"grid gap-3",children:h.map(I=>e.jsxs("div",{className:"grid gap-2 rounded-[18px] bg-white/[0.04] px-4 py-3 md:grid-cols-[110px_150px_minmax(0,1fr)_90px]",children:[e.jsx("div",{className:"text-sm text-white/62",children:I.dateKey}),e.jsx("div",{className:"text-sm text-white",children:I.workoutType}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-2 flex-1 overflow-hidden rounded-full bg-white/[0.08]",children:e.jsx("div",{className:"h-full rounded-full bg-[var(--primary)]",style:{width:`${Math.min(100,I.durationMinutes/120*100)}%`}})}),e.jsxs("div",{className:"text-sm text-white",children:[I.durationMinutes,"m"]})]}),e.jsxs("div",{className:"text-sm text-white/62",children:[I.energyKcal," kcal"]})]},I.id))}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Distance"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Rw(m.distanceMeters)})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Planned sessions"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:m.plannedSessionCount})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Imported / merged"}),e.jsxs("div",{className:"mt-2 text-lg text-white",children:[m.importedSessionCount," / ",m.reconciledSessionCount]})]})]})]}),e.jsxs(se,{className:"grid gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Training composition"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Workout type and provenance mix"})]}),e.jsx("div",{className:"grid gap-3",children:p.slice(0,6).map(I=>e.jsxs("div",{className:"grid gap-2 rounded-[18px] bg-white/[0.04] px-4 py-3 md:grid-cols-[minmax(0,1fr)_90px_90px]",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-white",children:I.workoutType}),e.jsxs("div",{className:"mt-1 text-sm text-white/58",children:[I.sessionCount," sessions"]})]}),e.jsxs("div",{className:"text-sm text-white/72",children:[I.totalMinutes,"m"]}),e.jsxs("div",{className:"text-sm text-white/72",children:[I.energyKcal," kcal"]})]},I.workoutType))}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Habit-generated"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:m.habitGeneratedSessionCount})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Forge-linked"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:m.linkedSessionCount})]})]})]})]}),e.jsx("div",{className:"grid gap-4",children:w.map(I=>{const k=n[I.id]??{subjectiveEffort:"",moodBefore:"",moodAfter:"",meaningText:""};return e.jsxs(se,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-lg text-white",children:[e.jsx(Uo,{className:"size-4 text-[var(--primary)]"}),e.jsx("span",{children:I.workoutType})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsx(O,{children:Po(I.durationSeconds)}),I.totalEnergyKcal?e.jsxs(O,{tone:"meta",children:[Math.round(I.totalEnergyKcal)," kcal"]}):null,I.distanceMeters?e.jsxs(O,{tone:"meta",children:[(I.distanceMeters/1e3).toFixed(1)," km"]}):null,I.averageHeartRate?e.jsxs(O,{tone:"meta",children:["Avg HR ",Math.round(I.averageHeartRate)]}):null,e.jsx(O,{tone:"meta",children:I.reconciliationStatus})]})]}),e.jsxs(W,{size:"sm",pending:b.isPending,pendingLabel:"Saving",onClick:()=>void b.mutateAsync({workoutId:I.id,subjectiveEffort:k.subjectiveEffort,moodBefore:k.moodBefore,moodAfter:k.moodAfter,meaningText:k.meaningText,plannedContext:k.plannedContext,socialContext:k.socialContext,tagsText:k.tagsText,linkValues:k.linkValues}),children:[e.jsx(Zn,{className:"size-4"}),"Save metadata"]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4 text-sm text-white/62",children:[new Date(I.startedAt).toLocaleString()," to"," ",new Date(I.endedAt).toLocaleString()," ·"," ",I.sourceDevice]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Source"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:I.sourceType.replaceAll("_"," ")})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Steps"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:I.stepCount??"n/a"})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Max HR"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:I.maxHeartRate?Math.round(I.maxHeartRate):"n/a"})]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Effort"}),e.jsx(ie,{type:"number",min:1,max:10,value:k.subjectiveEffort,onChange:S=>a(M=>({...M,[I.id]:{...k,subjectiveEffort:S.target.value}}))})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Mood before"}),e.jsx(ie,{value:k.moodBefore,onChange:S=>a(M=>({...M,[I.id]:{...k,moodBefore:S.target.value}}))})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Mood after"}),e.jsx(ie,{value:k.moodAfter,onChange:S=>a(M=>({...M,[I.id]:{...k,moodAfter:S.target.value}}))})]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Planned vs spontaneous"}),e.jsx(ie,{value:k.plannedContext,onChange:S=>a(M=>({...M,[I.id]:{...k,plannedContext:S.target.value}})),placeholder:"Planned recovery block"})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Social context"}),e.jsx(ie,{value:k.socialContext,onChange:S=>a(M=>({...M,[I.id]:{...k,socialContext:S.target.value}})),placeholder:"Solo, coach, group class, partner"})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Tags"}),e.jsx(ie,{value:k.tagsText,onChange:S=>a(M=>({...M,[I.id]:{...k,tagsText:S.target.value}})),placeholder:"sleep-support, recovery, strength-block"})]})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Meaning, link to sleep, project, value, or therapeutic plan"}),e.jsx(Ce,{className:"min-h-[120px]",value:k.meaningText,onChange:S=>a(M=>({...M,[I.id]:{...k,meaningText:S.target.value}})),placeholder:"Planned recovery walk linked to sleep repair, stress regulation, or a specific project rhythm."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Linked Forge and Psyche records"}),e.jsx(st,{options:v,selectedValues:k.linkValues,onChange:S=>a(M=>({...M,[I.id]:{...k,linkValues:S}})),placeholder:"Search goals, projects, habits, values, beliefs, patterns…"})]})]})]})]},I.id)})})]})}function oi({label:t,help:s}){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/58",children:[e.jsx("span",{children:t}),s?e.jsx(Xe,{content:s,label:`Explain ${t}`}):null]})}const _i=[{status:"backlog",label:"Backlog",description:"Not started yet.",icon:yi},{status:"focus",label:"Focus",description:"Ready to start soon.",icon:Oa},{status:"in_progress",label:"In progress",description:"Work is active now.",icon:Cs},{status:"blocked",label:"Blocked",description:"Something is stopping progress.",icon:Ho},{status:"done",label:"Done",description:"The task is completed.",icon:Hi}];function qw(){var U,R;const{t,formatDate:s,formatDateTime:i}=at(),n=Ye(),a=Array.isArray(n.selectedUserIds)?n.selectedUserIds:[],r=Hs(),l=ht(),d=We(),o=Nt(a),[x,f]=c.useState(!1),[b,m]=c.useState(!1),[h,p]=c.useState(!1),[w,v]=c.useState(()=>typeof window<"u"?window.matchMedia("(max-width: 1023px)").matches:!1),[I]=c.useState(()=>{const C=new Date,J=new Date(C);J.setHours(0,0,0,0);const ee=new Date(C);return ee.setHours(23,59,59,999),{from:J.toISOString(),to:ee.toISOString()}});c.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const C=window.matchMedia("(max-width: 1023px)"),J=ee=>v(ee?ee.matches:C.matches);return J(),typeof C.addEventListener=="function"?(C.addEventListener("change",J),()=>C.removeEventListener("change",J)):(C.addListener(J),()=>C.removeListener(J))},[]);const k=pe({queryKey:["task-context",r.taskId],queryFn:()=>jx(r.taskId),enabled:!!r.taskId}),S=pe({queryKey:["task-calendar-overview",r.taskId,I.from,I.to,...a],queryFn:()=>Qa({...I,userIds:a}),enabled:!!r.taskId}),M=async()=>{await Promise.all([d.invalidateQueries({queryKey:["forge-snapshot"]}),d.invalidateQueries({queryKey:["task-context",r.taskId]}),d.invalidateQueries({queryKey:["activity-archive"]}),d.invalidateQueries({queryKey:["project-board"]}),d.invalidateQueries({queryKey:["forge-xp-metrics"]}),d.invalidateQueries({queryKey:["forge-reward-ledger"]}),d.invalidateQueries({queryKey:["forge-operator-context"]})])},P=ge({mutationFn:({taskId:C,patch:J})=>Yi(C,J),onSuccess:M}),y=ge({mutationFn:C=>ur(C),onSuccess:M}),N=ge({mutationFn:C=>_d(C),onSuccess:M}),A=ge({mutationFn:({runId:C,actor:J,note:ee})=>zd(C,{actor:J,note:ee??""}),onSuccess:M}),T=ge({mutationFn:({runId:C,actor:J,note:ee})=>Rd(C,{actor:J,note:ee??""}),onSuccess:M}),F=ge({mutationFn:Fd,onSuccess:M}),u=ge({mutationFn:C=>hr(C),onSuccess:M}),j=k.data;if(k.isLoading)return e.jsx(It,{});if(k.isError)return e.jsx(Oe,{eyebrow:t("common.taskDetail.errorEyebrow"),error:k.error,onRetry:()=>void k.refetch()});if(!j)return e.jsx(Oe,{eyebrow:t("common.taskDetail.errorEyebrow"),error:new Error(t("common.taskDetail.emptyPayload")),onRetry:()=>void k.refetch()});const L=j.activeTaskRun??null,q=_i.find(C=>C.status===j.task.status)??_i[0];_i.filter(C=>C.status!==j.task.status);const G=pb(j.task,(U=j.project)==null?void 0:U.schedulingRules),Q=fc({rules:G,overview:(R=S.data)==null?void 0:R.calendar}),ne=C=>{switch(C){case"active":return"Active";case"completed":return"Completed";case"released":return"Paused";case"timed_out":return"Timed out";default:return C}},H=async C=>{await P.mutateAsync({taskId:j.task.id,patch:{status:C}}),p(!1)},_=async()=>{window.confirm(t("common.taskDetail.deleteTaskConfirm",{title:j.task.title}))&&(await u.mutateAsync(j.task.id),l(j.project?`/projects/${j.project.id}`:j.goal?`/goals/${j.goal.id}`:"/kanban"))};return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{entityKind:"task",title:e.jsx(_e,{kind:"task",label:j.task.title,variant:"heading",size:"lg",lines:3,className:"max-w-full",labelClassName:"[overflow-wrap:anywhere]"}),titleText:j.task.title,description:j.task.description?e.jsx(es,{markdown:j.task.description,className:"[&>p]:text-[13px] [&>p]:leading-6 [&>blockquote]:text-[13px] [&>ul]:text-[13px] [&>ol]:text-[13px]"}):"Edit the task, change its status, start work, and review its history from one page.",badge:`${j.task.points} xp`,actions:e.jsx(Ha,{userId:o,domain:"tasks",entityType:"task",entityId:j.task.id,label:j.task.title,description:j.task.description})}),j.task.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($e,{user:j.task.user})]}):null,e.jsxs(se,{className:"min-w-0 overflow-hidden",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Task"}),e.jsx("div",{className:"mt-2",children:e.jsx(_e,{kind:"task",label:j.task.title,variant:"heading",size:"xl",lines:3,className:"max-w-full",labelClassName:"[overflow-wrap:anywhere]"})}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:j.task.description?e.jsx(es,{markdown:j.task.description,className:"[&>p]:text-sm [&>p]:leading-6 [&>blockquote]:text-sm [&>ul]:text-sm [&>ol]:text-sm"}):"This page shows the task itself, where it belongs, what state it is in, and what has happened on it so far."})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-2",children:[e.jsxs(W,{pending:k.isFetching,pendingLabel:L?"Opening":"Starting",onClick:async()=>{await n.startTaskNow(j.task.id),await M()},children:[e.jsx(Cs,{className:"size-4 fill-current"}),L?"Focus work":"Start work"]}),L?e.jsxs(e.Fragment,{children:[e.jsx(W,{variant:"secondary",pending:A.isPending,pendingLabel:"Pausing",onClick:async()=>{await A.mutateAsync({runId:L.id,actor:L.actor,note:L.note})},children:"Pause"}),e.jsx(W,{variant:"secondary",pending:T.isPending,pendingLabel:"Completing",onClick:async()=>{await T.mutateAsync({runId:L.id,actor:L.actor,note:L.note})},children:"Complete"})]}):null,e.jsxs(W,{variant:"secondary",onClick:()=>m(!0),children:[e.jsx(yi,{className:"size-4"}),"Adjust work"]}),w?e.jsxs(e.Fragment,{children:[e.jsx(W,{variant:"secondary",size:"sm","aria-label":"Change task status",onClick:()=>p(!0),children:e.jsx(q.icon,{className:"size-4"})}),e.jsx(W,{variant:"secondary",size:"sm","aria-label":"Edit task",onClick:()=>f(!0),children:e.jsx(Us,{className:"size-4"})})]}):e.jsxs(W,{variant:"secondary",onClick:()=>f(!0),children:[e.jsx(Us,{className:"size-4"}),"Edit task"]}),j.task.status==="done"?e.jsx(W,{variant:"secondary",onClick:async()=>{await y.mutateAsync(j.task.id)},children:"Mark as not done"}):null,e.jsx(W,{variant:"ghost",className:"text-rose-200 hover:bg-rose-500/10",pending:u.isPending,pendingLabel:t("common.taskDetail.deleting"),onClick:()=>void _(),children:t("common.taskDetail.deleteTask")})]})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap gap-2",children:[e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:q.label}),e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:t(`common.enums.priority.${j.task.priority}`)}),e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:t(`common.enums.effort.${j.task.effort}`)}),e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:t(`common.enums.energy.${j.task.energy}`)}),e.jsxs(O,{className:"bg-white/[0.08] text-white/72",children:[j.task.points," xp"]}),j.task.time.totalCreditedSeconds>0?e.jsxs(O,{className:"bg-white/[0.08] text-white/72",children:[Math.floor(j.task.time.totalCreditedSeconds/60)," min tracked"]}):null,L?e.jsx(O,{className:"bg-emerald-500/12 text-emerald-200",children:"Timer active"}):null]}),w?null:e.jsxs("div",{className:"mt-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Status"}),e.jsx("div",{className:"mt-3 grid gap-2 md:grid-cols-2 xl:grid-cols-5",children:_i.map(C=>{const J=C.icon,ee=C.status===j.task.status;return e.jsxs("button",{type:"button",disabled:ee||P.isPending,className:`rounded-[18px] border px-3.5 py-3 text-left transition ${ee?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.14)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.08]"}`,onClick:()=>void H(C.status),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(J,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"font-medium",children:C.label})]}),e.jsx("div",{className:"mt-2 text-xs leading-5 text-white/54",children:C.description})]},C.status)})})]}),e.jsxs("div",{className:"mt-5 grid gap-4 xl:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Linked items"}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsxs("div",{children:[e.jsx(oi,{label:"Project",help:"The project is the main work stream this task belongs to."}),e.jsx("div",{className:"mt-2",children:j.project?e.jsx(Le,{to:`/projects/${j.project.id}`,className:"inline-flex max-w-full",children:e.jsx(ke,{kind:"project",label:j.project.title,compact:!0,gradient:!1,wrap:!0,className:"max-w-full"})}):e.jsx(O,{className:"bg-white/[0.08] text-white/65",children:"No project linked"})})]}),e.jsxs("div",{children:[e.jsx(oi,{label:"Goal",help:"The goal shows the longer-term result this task supports."}),e.jsx("div",{className:"mt-2",children:j.goal?e.jsx(Le,{to:`/goals/${j.goal.id}`,className:"inline-flex max-w-full",children:e.jsx(ke,{kind:"goal",label:j.goal.title,compact:!0,gradient:!1,wrap:!0,className:"max-w-full"})}):e.jsx(O,{className:"bg-white/[0.08] text-white/65",children:"No goal linked"})})]})]})]}),e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Task details"}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(oi,{label:"Due date",help:"Use a due date only when timing actually matters for this task."}),e.jsx("div",{className:"mt-2 text-white",children:s(j.task.dueDate)})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(oi,{label:"Owner",help:"The owner is the person or role expected to carry this task."}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2 text-white",children:[j.task.user?e.jsx($e,{user:j.task.user,compact:!0}):null,e.jsx("span",{children:j.task.owner})]})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(oi,{label:"Created"}),e.jsx("div",{className:"mt-2 text-white",children:i(j.task.createdAt)})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(oi,{label:"Updated"}),e.jsx("div",{className:"mt-2 text-white",children:i(j.task.updatedAt)})]})]})]})]}),e.jsxs("div",{className:"mt-5 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/58",children:[e.jsx("span",{children:"Current timer"}),e.jsx(Xe,{content:"This shows whether work is running on the task right now and how much time has been credited.",label:"Explain current timer"})]}),e.jsx("div",{className:"mt-3 text-white",children:L?`${L.timerMode==="planned"?"Planned":"Unlimited"} timer active with ${Math.floor(L.creditedSeconds/60)} credited minutes.`:"No timer is running on this task right now."})]}),e.jsxs("div",{className:"mt-5 grid gap-4 xl:grid-cols-[minmax(0,1fr)_20rem]",children:[e.jsx(pr,{title:"Task scheduling",subtitle:"Set when this task can run. If you leave it empty, the project defaults stay in force.",initialRules:j.task.schedulingRules,initialPlannedDurationSeconds:j.task.plannedDurationSeconds,allowPlannedDuration:!0,saveLabel:"Save task scheduling",onSave:async({schedulingRules:C,plannedDurationSeconds:J})=>{await P.mutateAsync({taskId:j.task.id,patch:{schedulingRules:C,plannedDurationSeconds:J}}),await d.invalidateQueries({queryKey:["task-calendar-overview",r.taskId]})}}),e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Calendar status"}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(O,{className:Q.tone==="blocked"?"bg-rose-500/14 text-rose-100":Q.tone==="waiting"?"bg-amber-500/14 text-amber-100":"bg-emerald-500/14 text-emerald-100",children:Q.label}),e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:j.task.schedulingRules?"Task override":"Using project defaults"}),j.task.plannedDurationSeconds?e.jsxs(O,{className:"bg-white/[0.08] text-white/72",children:[Math.round(j.task.plannedDurationSeconds/60)," min target"]}):null]}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:"Forge checks these rules before a live run starts. If the current calendar context is blocked, you can still override with an explicit reason."}),Q.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:Q.context.map(C=>e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:C},C))})]}):null,Q.conflicts.length>0?e.jsx("div",{className:"mt-4 grid gap-2",children:Q.conflicts.map(C=>e.jsx("div",{className:"rounded-[16px] bg-rose-500/10 px-3 py-2 text-sm text-rose-100",children:C},C))}):null,e.jsx("div",{className:"mt-4",children:e.jsx(Le,{to:"/calendar",children:e.jsx(W,{variant:"secondary",children:"Open calendar workspace"})})})]})]}),e.jsx("div",{className:"mt-5",children:e.jsx(Ga,{entityType:"task",entityId:j.task.id,title:"Task notes",description:"Capture real progress, blockers, and context in Markdown so the task keeps a durable work log.",invalidateQueryKeys:[["task-context",r.taskId],...j.task.projectId?[["project-board",j.task.projectId]]:[]]})}),e.jsxs("div",{className:"mt-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Activity"}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[j.activity.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] p-4 text-sm text-white/55",children:"No activity has been recorded for this task yet."}):null,j.activity.map(C=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-white",children:Xa(C)}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:Ja(C)}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.16em] text-white/35",children:i(C.createdAt)})]}),e.jsx(W,{variant:"ghost",className:"shrink-0",onClick:async()=>{await N.mutateAsync(C.id)},children:"Remove"})]}),Ms(C)&&Aa(C)?e.jsx(Le,{to:Ms(C),className:"mt-3 inline-flex text-[11px] uppercase tracking-[0.16em] text-[var(--primary)]",children:Aa(C)}):null]},C.id))]})]}),e.jsxs("div",{className:"mt-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Timer sessions"}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[j.taskRuns.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] p-4 text-sm text-white/55",children:"No timer sessions have been recorded for this task yet."}):null,j.taskRuns.map(C=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:C.actor}),e.jsx(O,{children:ne(C.status)})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:C.note||t("common.labels.noRunNote")}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.16em] text-white/35",children:i(C.updatedAt)})]},C.id))]})]})]}),e.jsx(za,{open:x,goals:n.snapshot.goals,projects:n.snapshot.dashboard.projects,tags:n.snapshot.tags,users:n.snapshot.users,editingTask:j.task,defaultUserId:j.task.userId??o,onOpenChange:f,onSubmit:async(C,J)=>{J&&await P.mutateAsync({taskId:J,patch:C})}}),e.jsx(gc,{open:b,onOpenChange:m,entityType:"task",entityId:j.task.id,targetLabel:j.task.title,currentCreditedSeconds:j.task.time.totalCreditedSeconds,pending:F.isPending,onSubmit:async C=>{await F.mutateAsync(C)}}),e.jsx(Ra,{open:h,onOpenChange:p,eyebrow:"Task status",title:"Change status",description:"Pick the state that best matches where this task is right now.",children:e.jsx("div",{className:"grid gap-3",children:_i.map(C=>{const J=C.icon,ee=C.status===j.task.status;return e.jsx("button",{type:"button",disabled:ee||P.isPending,className:`rounded-[22px] border px-4 py-4 text-left transition ${ee?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.14)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.08]"}`,onClick:()=>void H(C.status),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(J,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:C.label}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:C.description})]})]})},C.status)})})})]})}function Mo(t,s,i){var n;return((n=s.find(a=>a.id===t.goalId))==null?void 0:n.title)??i}function Bw(t,s){return t.tagIds.map(i=>s.find(n=>n.id===i)).filter(Boolean)}function Kw(t,s){(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),s())}function Uw(t,s){switch(t.status){case"backlog":return{label:s.backlog,action:"start",icon:Cs};case"focus":return{label:s.focus,action:"start",icon:Cs};case"in_progress":return{label:s.in_progress,nextStatus:"done",action:"move",icon:Hi};case"blocked":return{label:s.blocked,action:"start",icon:Cs};default:return null}}function Qw({tasks:t,timeline:s,goals:i,tags:n,notesSummaryByEntity:a,selectedTaskId:r,onSelectTask:l,onMove:d,onStartTask:o}){const{t:x,formatDate:f}=at(),b={backlog:x("common.dailyRunway.actionBacklog"),focus:x("common.dailyRunway.actionFocus"),in_progress:x("common.dailyRunway.actionProgress"),blocked:x("common.dailyRunway.actionBlocked")};return e.jsxs("div",{className:"grid min-w-0 gap-4 2xl:grid-cols-[minmax(0,1.3fr)_minmax(17rem,0.9fr)]",children:[e.jsxs("div",{className:"min-w-0 rounded-[24px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:x("common.dailyRunway.runwayEyebrow")}),e.jsx(Xe,{content:"These are the tasks that matter most for today. Click a card to open the task details. Use Start to begin work immediately."})]}),e.jsx("h4",{className:"mt-2 font-display text-2xl text-white",children:x("common.dailyRunway.runwayTitle")})]}),e.jsx(O,{className:"shrink-0 text-[var(--primary)]",children:x(t.length===1?"common.dailyRunway.prioritiesOne":"common.dailyRunway.prioritiesOther",{count:t.length})})]}),e.jsx("div",{className:"mt-4 grid min-w-0 gap-3",children:t.map((m,h)=>{const p=Uw(m,b),w=Bw(m,n).slice(0,2),v=r===m.id,I=Tt(a,"task",m.id).count;return e.jsxs("article",{role:"button",tabIndex:0,"aria-pressed":v,className:`grid w-full gap-3 rounded-[22px] px-4 py-4 text-left transition ${v?"bg-[linear-gradient(180deg,rgba(192,193,255,0.16),rgba(192,193,255,0.05))] shadow-[inset_0_0_0_1px_rgba(192,193,255,0.2)]":"bg-white/[0.03] hover:bg-white/[0.06]"}`,onClick:()=>l(m.id),onKeyDown:k=>Kw(k,()=>l(m.id)),children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:x("common.dailyRunway.runwayItem",{index:h+1})}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(ke,{kind:"goal",label:Mo(m,i,x("common.dailyRunway.unassigned")),compact:!0,gradient:!1}),m.time.activeRunCount>0?e.jsx(O,{className:"bg-emerald-500/12 text-emerald-200",children:"Live"}):null]}),e.jsx("div",{className:"mt-2",children:e.jsx(_e,{kind:"task",label:m.title,variant:"heading",size:"md"})}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:m.description||x("common.dailyRunway.noNote")})]}),e.jsx(O,{className:"shrink-0 self-start",children:m.status.replaceAll("_"," ")})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(O,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[m.points," xp"]}),e.jsx(yt,{entityType:"task",entityId:m.id,count:I}),m.time.totalCreditedSeconds>0?e.jsxs(O,{className:"bg-white/[0.08] text-white/70",children:[Math.floor(m.time.totalCreditedSeconds/60)," min tracked"]}):null,e.jsx(O,{className:"bg-white/[0.08] text-white/70",children:m.effort}),e.jsx(O,{className:"bg-white/[0.08] text-white/70",children:f(m.dueDate)}),w.map(k=>e.jsx(O,{className:"bg-white/[0.08]",style:{color:k.color},children:k.name},k.id))]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:m.owner}),p?e.jsxs(W,{variant:p.action==="start"?"primary":"secondary",className:"px-3 py-2 text-[11px] uppercase tracking-[0.16em]",onClick:async k=>{if(k.stopPropagation(),p.action==="start"){await o(m.id);return}p.nextStatus&&await d(m.id,p.nextStatus)},children:[e.jsx(p.icon,{className:"mr-2 size-3.5"}),p.label]}):null]})]},m.id)})})]}),e.jsxs("div",{className:"min-w-0 rounded-[24px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:x("common.dailyRunway.timelineEyebrow")}),e.jsx(Xe,{content:"This groups today's tasks by status, so you can see what is already moving, what is ready to start, what is blocked, and what is done."})]}),e.jsx("h4",{className:"mt-2 font-display text-2xl text-white",children:x("common.dailyRunway.timelineTitle")}),e.jsx("div",{className:"mt-4 grid min-w-0 gap-3",children:s.map(m=>e.jsxs("div",{className:"min-w-0 overflow-hidden rounded-[20px] bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:m.label}),e.jsx(O,{className:"bg-white/[0.08] text-white/65",children:m.tasks.length})]}),e.jsxs("div",{className:"mt-3 grid gap-2",children:[m.tasks.slice(0,3).map(h=>e.jsxs("button",{type:"button",className:"flex min-w-0 items-center justify-between gap-3 overflow-hidden rounded-[16px] bg-white/[0.03] px-3 py-3 text-left transition hover:bg-white/[0.06]",onClick:()=>l(h.id),children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx(_e,{kind:"task",label:h.title,className:"max-w-full",labelClassName:"[overflow-wrap:anywhere]"}),e.jsx("div",{className:"mt-2",children:e.jsx(ke,{kind:"goal",label:Mo(h,i,x("common.dailyRunway.unassigned")),compact:!0,gradient:!1})})]}),e.jsx(Gs,{className:"size-4 shrink-0 text-white/35"})]},h.id)),m.tasks.length===0?e.jsx("div",{className:"text-sm text-white/42",children:x("common.dailyRunway.emptyBucket")}):null]})]},m.id))})]})]})}const Pn=5;function Ww(){const t=new Date;t.setHours(0,0,0,0);const s=new Date(t);return s.setDate(s.getDate()+1),{start:t,end:s,from:t.toISOString(),to:s.toISOString()}}function Gw(t,s){const i=new Date(t.startAt),n=new Date(t.endAt);return i<s.end&&n>s.start}function Hw(t){if(t.isAllDay)return"All day";const s=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});return`${s.format(new Date(t.startAt))} - ${s.format(new Date(t.endAt))}`}function Xw(){var S,M;const{t}=at(),s=Ye(),i=Array.isArray(s.selectedUserIds)?s.selectedUserIds:[],n=ht(),a=c.useMemo(()=>Ww(),[]),r=pe({queryKey:["forge-calendar-overview",a.from,a.to,...i],queryFn:()=>Qa({from:a.from,to:a.to,userIds:i})}),l=s.snapshot.today.directive.task,d=s.snapshot.today.milestoneRewards.find(P=>!P.completed)??s.snapshot.today.milestoneRewards[0]??null,o=s.snapshot.risk.blockedTasks[0]??s.snapshot.risk.overdueTasks[0]??null,x=Math.max(0,s.snapshot.metrics.nextLevelXp-s.snapshot.metrics.currentLevelXp),f=8,b=4,m=10,h=20,p=c.useMemo(()=>{var P;return(((P=r.data)==null?void 0:P.calendar.events)??[]).filter(y=>!y.deletedAt&&y.status!=="cancelled"&&Gw(y,a)).sort((y,N)=>new Date(y.startAt).getTime()-new Date(N.startAt).getTime())},[(S=r.data)==null?void 0:S.calendar.events,a]),w=p.slice(0,Pn),v=p.length>0,I=c.useMemo(()=>new Intl.DateTimeFormat(void 0,{weekday:"short",month:"short",day:"numeric"}).format(a.start),[a.start]);return!(l!==null||s.snapshot.overview.topTasks.length>0||s.snapshot.today.dueHabits.length>0||s.snapshot.today.dailyQuests.length>0||s.snapshot.today.milestoneRewards.length>0||v)&&!r.isLoading?e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{title:"Today",titleText:"Today",description:"Start a task, earn XP, and keep today's work clear.",badge:`${s.snapshot.metrics.weeklyXp} weekly xp`}),e.jsx(gt,{eyebrow:t("common.todayPage.heroEyebrow"),title:t("common.todayPage.emptyTitle"),description:t("common.todayPage.emptyDescription"),action:e.jsx(Le,{to:"/goals",className:"inline-flex min-h-10 min-w-max shrink-0 items-center justify-center rounded-full bg-[var(--primary)] px-4 py-2 text-sm font-medium whitespace-nowrap text-slate-950 transition hover:opacity-90",children:t("common.todayPage.emptyAction")})})]}):e.jsxs("div",{className:"grid min-w-0 gap-5",children:[e.jsx(Ke,{title:"Today",titleText:"Today",description:(l==null?void 0:l.description)??"Start one real task, collect XP, and keep today's work moving.",badge:`${s.snapshot.metrics.weeklyXp} weekly xp`}),e.jsxs("section",{className:"grid gap-3 sm:grid-cols-2 2xl:grid-cols-4",children:[e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Weekly XP"}),e.jsx(Xe,{content:"Weekly XP is the XP earned since the start of the current week."})]}),e.jsx("div",{className:"mt-3 font-display text-4xl text-[var(--primary)]",children:s.snapshot.metrics.weeklyXp}),e.jsxs("div",{className:"mt-2 text-sm text-white/58",children:["Total XP: ",s.snapshot.metrics.totalXp]})]}),e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Level"}),e.jsx(Xe,{content:"Levels come from total XP. The progress bar below shows how much XP is left before the next level."})]}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:s.snapshot.metrics.level}),e.jsxs("div",{className:"mt-2 text-sm text-white/58",children:[x," xp to next level"]}),e.jsx("div",{className:"mt-3",children:e.jsx(ts,{value:s.snapshot.metrics.currentLevelXp/s.snapshot.metrics.nextLevelXp*100,tone:"tertiary"})})]}),e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Momentum"}),e.jsx(Xe,{content:"Momentum is a simple signal that combines weekly XP, active work, and overdue drag."})]}),e.jsxs("div",{className:"mt-3 font-display text-4xl text-white",children:[s.snapshot.metrics.momentumScore,"%"]}),e.jsxs("div",{className:"mt-2 text-sm text-white/58",children:[s.snapshot.metrics.streakDays," day streak"]})]}),e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Reward flows"}),e.jsx(Xe,{content:"Starting work, staying in work, completing work, and aligned habit check-ins all move XP through the same ledger."})]}),e.jsxs("div",{className:"mt-3 grid gap-2 text-sm text-white/70",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-3 py-2",children:[e.jsx("span",{children:"Start work"}),e.jsxs(O,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:["+",f," xp"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-3 py-2",children:[e.jsxs("span",{children:["Every ",m," min"]}),e.jsxs(O,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:["+",b," xp"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-3 py-2",children:[e.jsx("span",{children:"Complete timer"}),e.jsxs(O,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:["+",h," xp"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-3 py-2",children:[e.jsx("span",{children:"Aligned habit check-in"}),e.jsx(O,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"Habit XP"})]})]})]})]}),e.jsxs("section",{className:"grid min-w-0 gap-5 xl:grid-cols-[minmax(0,1.2fr)_minmax(18rem,22rem)] 2xl:grid-cols-[minmax(0,1.35fr)_24rem]",children:[e.jsx("div",{className:"min-w-0",children:e.jsx(Qw,{tasks:s.snapshot.overview.topTasks,timeline:s.snapshot.today.timeline,goals:s.snapshot.goals,tags:s.snapshot.tags,notesSummaryByEntity:s.snapshot.dashboard.notesSummaryByEntity,selectedTaskId:(l==null?void 0:l.id)??null,onSelectTask:P=>n(`/tasks/${P}`),onStartTask:async P=>{await s.startTaskNow(P)},onMove:async(P,y)=>{await s.patchTaskStatus(P,y)}})}),e.jsxs("div",{className:"grid min-w-0 gap-5",children:[v?e.jsxs(se,{className:"min-w-0 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Today's calendar"}),e.jsx(Xe,{content:"These are the calendar events already on today. Open any row to continue in the Calendar page."})]}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"inline-flex size-10 shrink-0 items-center justify-center rounded-2xl bg-[var(--primary)]/14 text-[var(--primary)]",children:e.jsx(us,{className:"size-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:I}),e.jsxs("div",{className:"text-sm text-white/58",children:[p.length," event",p.length===1?"":"s"," scheduled"]})]})]}),e.jsxs(Le,{to:"/calendar",className:"inline-flex shrink-0 items-center gap-2 rounded-full bg-white/[0.06] px-3 py-2 text-xs font-medium text-white/72 transition hover:bg-white/[0.1] hover:text-white",children:["Open calendar",e.jsx(An,{className:"size-3.5"})]})]}),e.jsxs("div",{className:"mt-4 grid gap-2.5",children:[w.map(P=>e.jsxs("button",{type:"button",className:"grid min-w-0 gap-2 rounded-[18px] bg-white/[0.04] px-3 py-3 text-left transition hover:bg-white/[0.07]",onClick:()=>n("/calendar"),children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white",children:P.title}),e.jsx("div",{className:"mt-1 text-sm text-white/58",children:Hw(P)})]}),e.jsx(O,{className:"shrink-0 bg-white/[0.08] text-white/72",children:P.originType==="native"?"Forge":P.originType})]}),P.description?e.jsx("div",{className:"line-clamp-2 text-sm leading-6 text-white/52",children:P.description}):null]},P.id)),p.length>Pn?e.jsxs(Le,{to:"/calendar",className:"inline-flex items-center justify-between rounded-[18px] bg-white/[0.03] px-3 py-3 text-sm text-white/62 transition hover:bg-white/[0.06] hover:text-white",children:[e.jsxs("span",{children:["See ",p.length-Pn," more events in Calendar"]}),e.jsx(An,{className:"size-4"})]}):null]})]}):null,e.jsxs(se,{className:"min-w-0 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Current task"}),e.jsx(Xe,{content:"This is the task Forge currently considers the best anchor for today."})]}),l?e.jsxs("button",{type:"button",className:"mt-4 grid w-full gap-3 rounded-[20px] bg-white/[0.04] p-4 text-left transition hover:bg-white/[0.06]",onClick:()=>n(`/tasks/${l.id}`),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-white",children:l.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:l.description||"No description yet."})]}),e.jsxs(O,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[s.snapshot.today.directive.rewardXp," xp"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.snapshot.today.directive.goalTitle?e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:s.snapshot.today.directive.goalTitle}):null,e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:s.snapshot.today.directive.sessionLabel}),e.jsx(yt,{entityType:"task",entityId:l.id,count:((M=s.snapshot.dashboard.notesSummaryByEntity[`task:${l.id}`])==null?void 0:M.count)??0})]})]}):e.jsx("div",{className:"mt-4 rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/58",children:"No task is selected for today yet. Start one from the list on the left."})]}),e.jsxs(se,{className:"min-w-0 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Due habits"}),e.jsx(Xe,{content:"Recurring records that still need a truthful check-in today."})]}),s.snapshot.today.dueHabits.length===0?e.jsx("div",{className:"mt-4 rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/58",children:"No due habits are waiting on today."}):e.jsx("div",{className:"mt-4 grid min-w-0 gap-3",children:s.snapshot.today.dueHabits.map(P=>{var y;return e.jsxs(Le,{to:"/habits",className:"grid gap-3 rounded-[20px] bg-white/[0.04] p-4 transition hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-white",children:P.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:P.description||"Recurring operating commitment."})]}),e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:P.polarity})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(O,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:["+",P.rewardXp," xp aligned"]}),e.jsxs(O,{className:"bg-white/[0.08] text-white/72",children:["Streak ",P.streakCount]}),e.jsx(yt,{entityType:"habit",entityId:P.id,count:((y=s.snapshot.dashboard.notesSummaryByEntity[`habit:${P.id}`])==null?void 0:y.count)??0})]})]},P.id)})})]}),e.jsxs(se,{className:"min-w-0 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.todayPage.questsTitle")}),e.jsx(Xe,{content:"Daily rewards are small XP targets for today. They should support real work, not replace it."})]}),s.snapshot.today.dailyQuests.length===0?e.jsx("div",{className:"mt-4 rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/58",children:t("common.todayPage.questsEmpty")}):e.jsx("div",{className:"mt-4 grid min-w-0 gap-3",children:s.snapshot.today.dailyQuests.map(P=>e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",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-medium leading-tight text-white",children:P.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:P.summary})]}),e.jsxs(O,{className:`shrink-0 self-start ${P.completed?"text-emerald-300":"text-[var(--tertiary)]"}`,children:["+",P.rewardXp," xp"]})]}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.16em] text-white/38",children:P.progressLabel})]},P.id))})]}),e.jsxs(se,{className:"min-w-0 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.todayPage.rewardsTitle")}),e.jsx(Xe,{content:"Milestones are larger progress targets that stay active across multiple days."})]}),s.snapshot.today.milestoneRewards.length===0?e.jsx("div",{className:"mt-4 rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/58",children:t("common.todayPage.rewardsEmpty")}):e.jsx("div",{className:"mt-4 grid min-w-0 gap-3",children:s.snapshot.today.milestoneRewards.map(P=>e.jsxs("div",{className:"overflow-hidden rounded-[20px] bg-white/[0.04] p-4",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-medium leading-tight text-white",children:P.title}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:P.summary})]}),e.jsx(O,{className:"max-w-[10.5rem] shrink-0 self-start",children:P.rewardLabel})]}),e.jsx("div",{className:"mt-4",children:e.jsx(ts,{value:P.current/P.target*100,tone:"tertiary"})}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.16em] text-white/38",children:P.progressLabel})]},P.id))})]}),e.jsxs(se,{className:"min-w-0 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Needs attention"}),e.jsx(Xe,{content:"This highlights the blocked or overdue task most likely to slow you down if ignored."})]}),o?e.jsx("button",{type:"button",className:"mt-4 grid w-full gap-3 rounded-[20px] bg-white/[0.04] p-4 text-left transition hover:bg-white/[0.06]",onClick:()=>n(`/tasks/${o.id}`),children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-white",children:o.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:o.description||s.snapshot.today.momentum.recoveryHint})]}),e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:o.status.replaceAll("_"," ")})]})}):e.jsx("div",{className:"mt-4 rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/58",children:s.snapshot.today.momentum.recoveryHint}),d?e.jsxs("div",{className:"mt-4 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:d.title}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:d.progressLabel})]}):null]})]})]})]})}function Jw(t){const s=[];let i,n;for(const a of t){const r=a.trim();if(!r)continue;const l=r.indexOf(":");if(l<=0){s.push({label:"Note",value:r});continue}const d=r.slice(0,l).trim(),o=r.slice(l+1).trim();if(!o)continue;const x=d.toLowerCase();if(x==="title"){i=o;continue}if(x==="summary"){n=o;continue}s.push({label:d,value:o})}return{title:i,summary:n,rows:s}}function Yw(t){const s=[],i=/(!?\[\[([^\]]+)\]\]|\[([^\]]+)\]\(([^)]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|\*([^*]+)\*)/g;let n=0,a=null;for(;(a=i.exec(t))!==null;){if(a.index>n&&s.push({type:"text",value:t.slice(n,a.index)}),a[1]&&a[2]){const r=a[2].trim(),l=a[1].startsWith("!"),d=r.indexOf("|"),o=d>=0?r.slice(0,d).trim():r,x=d>=0?r.slice(d+1).trim():o;if(o.toLowerCase().startsWith("forge:")){const[,f,...b]=o.split(":");s.push({type:"forge-link",entityType:f??"",entityId:b.join(":").trim(),label:x})}else s.push({type:"wiki-link",target:o,label:x,embed:l})}else a[3]&&a[4]?s.push({type:"link",label:a[3],href:a[4].trim()}):a[5]?s.push({type:"code",value:a[5]}):a[6]?s.push({type:"strong",value:a[6]}):a[7]&&s.push({type:"em",value:a[7]});n=i.lastIndex}return n<t.length&&s.push({type:"text",value:t.slice(n)}),s}function Vw(t){const s=t.replace(/\r/g,"").split(`
|
|
37
|
+
`),i=[],n=[];let a=null,r=0;for(;r<s.length;){const l=s[r]??"",d=l.trim();if(!d){r+=1;continue}if(d.startsWith("```")){const b=[];for(r+=1;r<s.length&&!(s[r]??"").trim().startsWith("```");)b.push(s[r]??""),r+=1;r+=1,i.push({type:"code",code:b.join(`
|
|
38
|
+
`)});continue}const o=d.match(/^:::([a-z0-9-]+)\s*$/i);if(o){const b=o[1].toLowerCase(),m=[];for(r+=1;r<s.length&&(s[r]??"").trim()!==":::";)m.push(s[r]??""),r+=1;r<s.length&&(r+=1);const h=[`:::${b}`,...m,":::"].join(`
|
|
39
|
+
`);n.push({kind:b,lines:m,raw:h}),b==="forge-infobox"?a=Jw(m):b==="note"||b==="tip"||b==="warning"||b==="danger"?i.push({type:"admonition",kind:b,lines:m}):(b==="forge-links"||b==="forge-media"||b==="forge-related")&&i.push({type:b,lines:m});continue}const x=l.match(/^(#{1,6})\s+(.*)$/);if(x){i.push({type:"heading",level:x[1].length,text:x[2].trim()}),r+=1;continue}if(/^>\s?/.test(l)){const b=[];for(;r<s.length&&/^>\s?/.test(s[r]??"");)b.push((s[r]??"").replace(/^>\s?/,"")),r+=1;i.push({type:"quote",text:b.join(" ").trim()});continue}if(/^[-*+]\s+/.test(l)||/^\d+\.\s+/.test(l)){const b=/^\d+\.\s+/.test(l),m=[];for(;r<s.length&&(/^[-*+]\s+/.test(s[r]??"")||/^\d+\.\s+/.test(s[r]??""));)m.push((s[r]??"").replace(/^[-*+]\s+/,"").replace(/^\d+\.\s+/,"").trim()),r+=1;i.push({type:"list",ordered:b,items:m});continue}const f=[];for(;r<s.length;){const b=s[r]??"",m=b.trim();if(!m||m.startsWith("```")||m.startsWith(":::")||/^#{1,6}\s+/.test(b)||/^>\s?/.test(b)||/^[-*+]\s+/.test(b)||/^\d+\.\s+/.test(b))break;f.push(m),r+=1}if(f.length>0){i.push({type:"paragraph",text:f.join(" ")});continue}r+=1}return{blocks:i,infobox:a,directives:n}}function Zw(t,s,i){return t.map((n,a)=>{const r=`${s}-${a}`;switch(n.type){case"text":return e.jsx(c.Fragment,{children:n.value},r);case"code":return e.jsx("code",{className:"rounded bg-black/10 px-1.5 py-0.5 font-mono text-[0.92em] text-white",children:n.value},r);case"strong":return e.jsx("strong",{className:"font-semibold text-white",children:n.value},r);case"em":return e.jsx("em",{className:"italic text-white/82",children:n.value},r);case"link":{const l=/^https?:\/\//i.test(n.href);return e.jsx("a",{href:n.href,target:l?"_blank":void 0,rel:l?"noreferrer":void 0,className:"text-[var(--secondary)] underline decoration-current/30 underline-offset-2 transition hover:text-white",children:n.label},r)}case"forge-link":{const l=Es(n.entityType,n.entityId),d=l?Ws(l):null;return d?e.jsx("a",{href:d,className:"rounded-sm bg-white/[0.08] px-1.5 py-0.5 text-white no-underline ring-1 ring-black/5 transition hover:bg-white/[0.12]",children:n.label},r):e.jsx("span",{className:"rounded-sm bg-white/[0.08] px-1.5 py-0.5 text-white/64",children:n.label},r)}case"wiki-link":return e.jsx(Le,{to:{pathname:`/wiki/page/${encodeURIComponent(n.target)}`,search:i?`?spaceId=${encodeURIComponent(i)}`:""},className:re("underline decoration-current/30 underline-offset-2 transition hover:text-white",n.embed?"text-[var(--primary)]":"text-[var(--secondary)]"),children:n.label},r)}})}function Ns(t,s,i){return Zw(Yw(t),s,i)}function ev(t,s){const i=t.map(n=>n.trim()).filter(Boolean);return i.length===0?null:e.jsx("ul",{className:"space-y-1.5 pl-4 text-[13px] leading-6 text-white/76",children:i.map((n,a)=>e.jsx("li",{children:Ns(n,`directive-${a}`,s)},`${n}-${a}`))})}function Eo(t,s,i){switch(t.type){case"heading":{const n=t.level===1?"text-[1.9rem] leading-[1.08]":t.level===2?"text-[1.25rem] leading-[1.2]":t.level===3?"text-[1.05rem] leading-[1.3]":"text-[0.92rem] leading-[1.35]";return e.jsx("h2",{className:re("font-semibold tracking-[-0.02em] text-white",s>0&&"mt-6",n),children:Ns(t.text,`heading-${s}`,i)},`heading-${s}`)}case"paragraph":return e.jsx("p",{className:"text-[14px] leading-7 text-white/78",children:Ns(t.text,`paragraph-${s}`,i)},`paragraph-${s}`);case"quote":return e.jsx("blockquote",{className:"border-l-[3px] border-white/16 pl-4 text-[14px] leading-7 text-white/62",children:Ns(t.text,`quote-${s}`,i)},`quote-${s}`);case"list":{const n=t.ordered?"ol":"ul";return e.jsx(n,{className:re("space-y-1.5 pl-5 text-[14px] leading-7 text-white/78",t.ordered?"list-decimal":"list-disc"),children:t.items.map((a,r)=>e.jsx("li",{children:Ns(a,`list-${s}-${r}`,i)},`item-${s}-${r}`))},`list-${s}`)}case"code":return e.jsx("pre",{className:"overflow-x-auto rounded-xl bg-[rgba(10,16,30,0.9)] px-4 py-3 text-[12px] leading-6 text-white ring-1 ring-black/5",children:e.jsx("code",{children:t.code})},`code-${s}`);case"admonition":return e.jsxs("aside",{className:re("rounded-xl border px-4 py-3",t.kind==="warning"||t.kind==="danger"?"border-amber-500/25 bg-amber-500/8":"border-white/12 bg-white/[0.04]"),children:[e.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-white/48",children:t.kind}),e.jsx("div",{className:"grid gap-2 text-[13px] leading-6 text-white/76",children:t.lines.map((n,a)=>e.jsx("p",{children:Ns(n,`admonition-${s}-${a}`,i)},`admonition-line-${a}`))})]},`admonition-${s}`);case"forge-links":case"forge-media":case"forge-related":return e.jsxs("section",{className:"rounded-xl border border-white/10 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-white/48",children:t.type.replace("forge-","")}),ev(t.lines,i)]},`${t.type}-${s}`)}}function tv(t,s,i){return e.jsx("div",{className:"text-[13px] leading-6 text-white/76",children:Ns(t,s,i)})}function sv({infobox:t,spaceId:s,className:i}){return e.jsxs("aside",{className:re("wiki-infobox rounded-2xl border border-white/10 bg-white/[0.03] p-4",i),children:[t.title?e.jsx("div",{className:"text-[1rem] font-semibold leading-tight text-white",children:t.title}):null,t.summary?e.jsx("p",{className:"mt-2 text-[13px] leading-6 text-white/60",children:Ns(t.summary,"infobox-summary",s)}):null,e.jsx("dl",{className:"mt-3 grid gap-2",children:t.rows.map((n,a)=>e.jsxs("div",{className:"grid gap-1 border-t border-white/10 pt-2 first:border-t-0 first:pt-0",children:[e.jsx("dt",{className:"text-[10px] font-semibold uppercase tracking-[0.16em] text-white/48",children:n.label}),e.jsx("dd",{children:tv(n.value,`infobox-row-${a}`,s)})]},`${n.label}-${a}`))})]})}function iv(t){const s=[],i=[];let n=!1;for(const a of t)!n&&a.type==="heading"&&a.level<=2&&s.length>0&&(n=!0),n?i.push(a):s.push(a);return{intro:s.length>0?s:t.slice(0,1),rest:s.length>0?i:t.slice(1)}}function Kc({markdown:t,spaceId:s,className:i}){const n=Vw(t),{intro:a,rest:r}=iv(n.blocks);return e.jsxs("div",{className:re("grid gap-4",i),children:[e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1fr)_19rem] xl:items-start",children:[e.jsx("div",{className:"grid gap-4",children:a.map((l,d)=>Eo(l,d,s))}),n.infobox?e.jsx(sv,{infobox:n.infobox,spaceId:s,className:"order-2 xl:order-none"}):null]}),r.length>0?e.jsx("div",{className:"grid gap-4",children:r.map((l,d)=>Eo(l,d+a.length,s))}):null]})}const di=new Set(["queued","processing"]),Ao=15e3,av=["goal","project","task","habit","strategy","psyche_value","note"];function Lo(t){return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(t))}function Ss(t,s){const i=t[s];return typeof i=="number"&&Number.isFinite(i)?i:null}function Ut(t,s){const i=t[s];return typeof i=="string"&&i.trim().length>0?i:null}function nv(t,s){const i=Ut(t.metadata,"currentFileName")??Ut(t.metadata,"fileName")??"current source",n=Ut(t.metadata,"status")??"in_progress",a=Ss(t.metadata,"chunkIndex"),r=Ss(t.metadata,"chunkCount"),l=Ss(t.metadata,"currentFileIndex"),d=Ss(t.metadata,"currentFileTotal"),o=l!==null&&d!==null?`${i} (${l}/${d})`:i,x=a!==null&&r!==null&&r>1?` · chunk ${a}/${r}`:"";return`Waiting for OpenAI on ${o}${x}. ${s} polls · ${n}.`}function rv(t){const s=[];for(const i of t){const n=Ut(i.metadata,"scope"),r=Ut(i.metadata,"eventKey")==="llm_compile_background_polled",l=Ut(i.metadata,"currentFileName")??Ut(i.metadata,"fileName"),d=Ss(i.metadata,"chunkIndex"),o=Ss(i.metadata,"chunkCount"),x=r?["poll",n??"",l??"",d??"",o??""].join(":"):null,f=s[s.length-1],b=f&&Ut(f.metadata,"eventKey"),m=f&&(Ut(f.metadata,"currentFileName")??Ut(f.metadata,"fileName")),h=f&&Ss(f.metadata,"chunkIndex"),p=f&&Ss(f.metadata,"chunkCount"),w=f&&b==="llm_compile_background_polled"?["poll",Ut(f.metadata,"scope")??"",m??"",h??"",p??""].join(":"):null;if(r&&f&&w===x){s[s.length-1]={...i,repetitionCount:f.repetitionCount+1,metadata:{...i.metadata,aggregatedPollCount:f.repetitionCount+1}};continue}s.push({...i,repetitionCount:1})}return s}function va(t){switch(t){case"goal":case"project":case"task":case"habit":case"strategy":return t;case"psyche_value":return"value";default:return null}}function Do(t){return typeof t=="string"&&av.includes(t)}function lv(t,s){return typeof s.title=="string"&&s.title.trim().length>0?s.title:typeof s.displayName=="string"&&s.displayName.trim().length>0?s.displayName:typeof s.statement=="string"&&s.statement.trim().length>0?s.statement:`${t}:${String(s.id??"")}`}function ov(t,s){const n=[s.description,s.summary,s.overview,s.valuedDirection,s.whyItMatters,s.originNote].find(a=>typeof a=="string"&&a.trim().length>0);return n||(t==="note"&&typeof s.kind=="string"?s.kind:"")}function dv({candidate:t,decision:s,onDecisionChange:i,spaceId:n}){const a=Do(t.payload.entityType)?t.payload.entityType:null,[r,l]=c.useState(s.mappedEntityLabel||t.title||""),[d,o]=c.useState(s.targetNoteLabel||t.title||""),x=typeof t.payload.contentMarkdown=="string"?t.payload.contentMarkdown:typeof t.payload.patchSummary=="string"?t.payload.patchSummary:typeof t.payload.rationale=="string"?t.payload.rationale:t.summary,f=pe({queryKey:["forge-wiki-ingest-map-search",a,r.trim()],enabled:t.candidateType==="entity"&&s.action==="map_existing"&&a!==null&&r.trim().length>0,queryFn:async()=>{var k;const I=(await ux({searches:[{entityTypes:a?[a]:void 0,query:r.trim(),limit:8}]})).results[0];return((k=I==null?void 0:I.matches)==null?void 0:k.filter(S=>!!(S&&Do(S.entityType)&&typeof S.id=="string"&&S.entity&&typeof S.entity=="object")).map(S=>({entityType:S.entityType,entityId:S.id,label:lv(S.entityType,S.entity),description:ov(S.entityType,S.entity),kind:va(S.entityType)})))??[]}}),b=f.data??[],m=pe({queryKey:["forge-wiki-ingest-merge-search",n,d.trim()],enabled:t.candidateType==="page"&&s.action==="merge_existing"&&d.trim().length>0,queryFn:async()=>(await cp({spaceId:n,kind:"wiki",mode:"text",query:d.trim(),limit:8})).results.map(I=>({noteId:I.page.id,title:I.page.title,slug:I.page.slug,summary:I.page.summary}))}),h=m.data??[],p=s.mappedEntityId&&s.mappedEntityType?b.find(v=>v.entityId===s.mappedEntityId&&v.entityType===s.mappedEntityType)??(s.mappedEntityLabel?{entityId:s.mappedEntityId,entityType:s.mappedEntityType,label:s.mappedEntityLabel,kind:va(s.mappedEntityType)}:null):null,w=s.targetNoteId?h.find(v=>v.noteId===s.targetNoteId)??(s.targetNoteLabel?{noteId:s.targetNoteId,title:s.targetNoteLabel}:null):null;return e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:t.candidateType.replaceAll("_"," ")}),e.jsx("div",{className:"mt-2 text-base font-semibold text-white",children:t.title||t.targetKey||"Untitled candidate"}),a?e.jsx("div",{className:"mt-2",children:va(a)?e.jsx(ke,{kind:va(a),label:a.replaceAll("_"," "),compact:!0,gradient:!1}):e.jsx(O,{className:"bg-white/[0.08] text-white/72",children:a.replaceAll("_"," ")})}):null,t.summary?e.jsx("div",{className:"mt-1 text-sm leading-6 text-white/58",children:t.summary}):null]}),e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.03] p-1",children:[e.jsx("button",{type:"button",className:re("rounded-full px-3 py-1.5 text-xs font-medium transition",s.action==="keep"?"bg-[rgba(192,193,255,0.2)] text-white":"text-white/54 hover:text-white"),onClick:()=>i({...s,action:"keep"}),children:"Keep"}),t.candidateType==="entity"&&a?e.jsx("button",{type:"button",className:re("rounded-full px-3 py-1.5 text-xs font-medium transition",s.action==="map_existing"?"bg-[rgba(133,222,255,0.18)] text-white":"text-white/54 hover:text-white"),onClick:()=>i({...s,action:"map_existing",mappedEntityType:a}),children:"Map existing"}):null,t.candidateType==="page"?e.jsx("button",{type:"button",className:re("rounded-full px-3 py-1.5 text-xs font-medium transition",s.action==="merge_existing"?"bg-[rgba(133,222,255,0.18)] text-white":"text-white/54 hover:text-white"),onClick:()=>i({...s,action:"merge_existing"}),children:"Merge existing"}):null,e.jsx("button",{type:"button",className:re("rounded-full px-3 py-1.5 text-xs font-medium transition",s.action==="discard"?"bg-[rgba(255,255,255,0.12)] text-white":"text-white/54 hover:text-white"),onClick:()=>i({...s,action:"discard"}),children:"Discard"})]})]}),t.candidateType==="entity"&&a&&s.action==="map_existing"?e.jsxs("div",{className:"mt-4 grid gap-3 rounded-[18px] border border-white/8 bg-[rgba(6,10,20,0.55)] p-4",children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:["Map to existing ",a.replaceAll("_"," ")]}),p?e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-white/8 bg-white/[0.06] px-2.5 py-1.5",children:[p.kind?e.jsx(ke,{kind:p.kind,label:p.label,compact:!0,gradient:!1,className:"max-w-[20rem]"}):e.jsx(O,{className:"bg-white/[0.08] text-white/78",children:p.label}),e.jsx("button",{type:"button",className:"rounded-full text-white/50 transition hover:text-white",onClick:()=>i({...s,mappedEntityId:void 0,mappedEntityLabel:void 0}),"aria-label":"Clear mapped entity",children:e.jsx(mt,{className:"size-3.5"})})]})}):null,e.jsxs("div",{className:"flex items-center gap-3 rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[e.jsx(dt,{className:"size-4 text-white/34"}),e.jsx("input",{value:r,onChange:v=>{l(v.target.value),s.mappedEntityId&&i({...s,mappedEntityId:void 0,mappedEntityLabel:void 0})},placeholder:`Search existing ${a.replaceAll("_"," ")}`,className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]}),e.jsx("div",{className:"grid gap-2",children:f.isPending?e.jsx("div",{className:"rounded-[16px] border border-white/8 bg-white/[0.03] px-3 py-3 text-sm text-white/48",children:"Searching Forge…"}):b.length===0?e.jsxs("div",{className:"rounded-[16px] border border-dashed border-white/10 px-3 py-3 text-sm text-white/42",children:["No existing ",a.replaceAll("_"," ")," matches yet."]}):b.map(v=>{const I=s.mappedEntityType===v.entityType&&s.mappedEntityId===v.entityId;return e.jsx("button",{type:"button",className:re("flex w-full items-start justify-between gap-3 rounded-[18px] border px-3 py-3 text-left transition",I?"border-[rgba(133,222,255,0.24)] bg-[rgba(133,222,255,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/72 hover:bg-white/[0.06] hover:text-white"),onClick:()=>i({action:"map_existing",mappedEntityType:v.entityType,mappedEntityId:v.entityId,mappedEntityLabel:v.label}),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:v.kind?e.jsx(ke,{kind:v.kind,label:v.label,compact:!0,gradient:!1}):v.label}),v.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/46",children:v.description}):null]})},`${v.entityType}:${v.entityId}`)})})]}):null,t.candidateType==="page"&&s.action==="merge_existing"?e.jsxs("div",{className:"mt-4 grid gap-3 rounded-[18px] border border-white/8 bg-[rgba(6,10,20,0.55)] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Merge into existing page"}),w?e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-white/8 bg-white/[0.06] px-2.5 py-1.5",children:[e.jsx(O,{className:"bg-white/[0.08] text-white/78",children:w.title}),e.jsx("button",{type:"button",className:"rounded-full text-white/50 transition hover:text-white",onClick:()=>i({...s,targetNoteId:void 0,targetNoteLabel:void 0}),"aria-label":"Clear merge target",children:e.jsx(mt,{className:"size-3.5"})})]})}):null,e.jsxs("div",{className:"flex items-center gap-3 rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[e.jsx(dt,{className:"size-4 text-white/34"}),e.jsx("input",{value:d,onChange:v=>{o(v.target.value),s.targetNoteId&&i({...s,targetNoteId:void 0,targetNoteLabel:void 0})},placeholder:"Search existing wiki pages",className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]}),e.jsx("div",{className:"grid gap-2",children:m.isPending?e.jsx("div",{className:"rounded-[16px] border border-white/8 bg-white/[0.03] px-3 py-3 text-sm text-white/48",children:"Searching Forge…"}):h.length===0?e.jsx("div",{className:"rounded-[16px] border border-dashed border-white/10 px-3 py-3 text-sm text-white/42",children:"No existing wiki pages match yet."}):h.map(v=>{const I=s.targetNoteId===v.noteId;return e.jsx("button",{type:"button",className:re("flex w-full items-start justify-between gap-3 rounded-[18px] border px-3 py-3 text-left transition",I?"border-[rgba(133,222,255,0.24)] bg-[rgba(133,222,255,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/72 hover:bg-white/[0.06] hover:text-white"),onClick:()=>i({action:"merge_existing",targetNoteId:v.noteId,targetNoteLabel:v.title}),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:v.title}),e.jsxs("div",{className:"mt-1 text-xs leading-5 text-white/46",children:[v.slug?`${v.slug}`:"",v.summary?`${v.slug?" · ":""}${v.summary}`:""]})]})},v.noteId)})})]}):null,x?e.jsx("div",{className:"mt-4 rounded-[18px] border border-white/8 bg-[rgba(6,10,20,0.65)] px-4 py-3 text-sm leading-6 text-white/72",children:e.jsx("pre",{className:"whitespace-pre-wrap font-sans",children:x})}):null]})}function Uc({open:t,onOpenChange:s,spaces:i,llmProfiles:n,initialSpaceId:a,selectedJobId:r,onJobSelected:l,linkedEntityHints:d=[]}){var je;const o=ht(),x=We(),[f,b]=c.useState("files"),[m,h]=c.useState(a),[p,w]=c.useState(""),[v,I]=c.useState(""),[k,S]=c.useState(""),[M,P]=c.useState([]),[y,N]=c.useState(!1),[A,T]=c.useState(!1),F=c.useMemo(()=>n.filter(V=>V.enabled&&!!V.secretId),[n]),[u,j]=c.useState(((je=F[0])==null?void 0:je.id)??""),[L,q]=c.useState("auto"),[G,Q]=c.useState({}),[ne,H]=c.useState(null),[_,U]=c.useState(null),R=c.useRef({});c.useEffect(()=>{a&&h(a)},[a]),c.useEffect(()=>{var V;!u&&((V=F[0])!=null&&V.id)&&j(F[0].id)},[u,F]);const C=F.find(V=>V.id===u)??F[0]??null,J=pe({queryKey:["forge-wiki-ingest-job",r],queryFn:()=>dp(r),enabled:t&&!!r,refetchInterval:V=>{const D=V.state.data;return D&&di.has(D.job.status)?2e3:!1}});c.useEffect(()=>{const V=J.data;V&&Q(Object.fromEntries(V.candidates.map(D=>[D.id,D.status==="rejected"?{action:"discard"}:{action:"keep"}])))},[J.data]),c.useEffect(()=>{_&&U(null)},[G,_]);const ee=ge({mutationFn:async V=>hp(V),onSuccess:(V,D)=>{V.job&&x.setQueryData(["forge-wiki-ingest-job",D],V.job),x.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),x.invalidateQueries({queryKey:["forge-wiki-ingest-history"]})}});c.useEffect(()=>{const V=J.data;if(!V||!di.has(V.job.status))return;const D=V.logs.reduce((Pe,Ge)=>{const Z=Number(new Date(Ge.createdAt));return Number.isFinite(Z)?Math.max(Pe,Z):Pe},0),X=Number(new Date(V.job.updatedAt)),he=Math.max(Number.isFinite(X)?X:0,D);if(!Number.isFinite(he)||he<=0)return;const ye=Date.now();if(!(ye-he>=Ao)||ee.isPending)return;const fe=R.current[V.job.id]??0;ye-fe<Ao||(R.current[V.job.id]=ye,ee.mutate(V.job.id))},[J.data,ee]);const le=ge({mutationFn:async()=>{if(!C)throw new Error("Set up an OpenAI wiki ingest profile first. Forge now requires an LLM profile before auto-ingest can turn source material into draft pages and entities.");if(f==="files"){if(M.length===0)throw new Error("Select at least one file to ingest.");return op({files:M,spaceId:m||void 0,titleHint:p.trim()||void 0,llmProfileId:C.id,parseStrategy:L,createAsKind:"wiki",linkedEntityHints:d})}if(f==="url"){if(!v.trim())throw new Error("Enter a URL to ingest.");return ul({spaceId:m||void 0,titleHint:p.trim()||void 0,sourceKind:"url",sourceUrl:v.trim(),llmProfileId:C.id,parseStrategy:L,createAsKind:"wiki",linkedEntityHints:d})}if(!k.trim())throw new Error("Paste some text to ingest.");return ul({spaceId:m||void 0,titleHint:p.trim()||void 0,sourceKind:"raw_text",sourceText:k,mimeType:"text/plain",llmProfileId:C.id,parseStrategy:L,createAsKind:"wiki",linkedEntityHints:d})},onSuccess:async V=>{var X;const D=((X=V.job)==null?void 0:X.job.id)??null;await x.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),await x.invalidateQueries({queryKey:["forge-wiki-ingest-history"]}),D&&l(D),H(null),U(null)},onError:V=>{H(V instanceof Error?V.message:"Unable to start ingest.")}}),oe=ge({mutationFn:async()=>{if(!r||!J.data)throw new Error("Choose an ingest job first.");const V=J.data.candidates.map(D=>{const X=G[D.id]??{action:"keep"};if(X.action==="map_existing"&&(!X.mappedEntityType||!X.mappedEntityId))throw new Error(`Choose an existing ${String(D.payload.entityType??"entity").replaceAll("_"," ")} before publishing the review.`);if(X.action==="merge_existing"&&!X.targetNoteId)throw new Error(`Choose an existing wiki page before publishing the review for ${D.title||"this page candidate"}.`);return X.action==="map_existing"?{candidateId:D.id,action:"map_existing",mappedEntityType:X.mappedEntityType,mappedEntityId:X.mappedEntityId}:X.action==="merge_existing"?{candidateId:D.id,action:"merge_existing",targetNoteId:X.targetNoteId}:{candidateId:D.id,action:X.action}});return up({jobId:r,decisions:V})},onSuccess:async V=>{U(null),await Promise.all([x.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),x.invalidateQueries({queryKey:["forge-wiki-ingest-history"]}),x.invalidateQueries({queryKey:["forge-wiki-ingest-job",V.job.job.id]}),x.invalidateQueries({queryKey:["forge-wiki-home"]}),x.invalidateQueries({queryKey:["forge-wiki-page-by-slug"]}),x.invalidateQueries({queryKey:["forge-wiki-tree"]})])},onError:V=>{U(V instanceof Error?V.message:"Unable to publish review.")}}),ue=ge({mutationFn:async()=>{if(!r)throw new Error("Choose an ingest job first.");return mp(r)},onSuccess:async V=>{var X;const D=((X=V.job)==null?void 0:X.job.id)??null;await Promise.all([x.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),x.invalidateQueries({queryKey:["forge-wiki-ingest-history"]}),x.invalidateQueries({queryKey:["forge-wiki-ingest-job",r]})]),D&&l(D),H(null),U(null)},onError:V=>{H(V instanceof Error?V.message:"Unable to rerun ingest.")}}),me=ge({mutationFn:async()=>{if(!r)throw new Error("Choose an ingest job first.");return Pd(r)},onSuccess:async()=>{await Promise.all([x.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),x.invalidateQueries({queryKey:["forge-wiki-ingest-history"]}),x.invalidateQueries({queryKey:["forge-wiki-ingest-job",r]})]),K(),H(null),U(null)},onError:V=>{H(V instanceof Error?V.message:"Unable to delete ingest.")}}),$=J.data??null,ce=$&&!di.has($.job.status),E=c.useMemo(()=>($==null?void 0:$.candidates.filter(V=>["suggested","accepted","rejected"].includes(V.status)))??[],[$]),z=c.useMemo(()=>rv(($==null?void 0:$.logs)??[]),[$==null?void 0:$.logs]),K=()=>{l(null),P([]),I(""),S(""),w(""),H(null),U(null)};return e.jsx(Lt,{open:t,onOpenChange:V=>{s(V),V||(H(null),U(null))},children:e.jsxs(Dt,{children:[e.jsx($t,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.78)] backdrop-blur-sm"}),e.jsxs(Ot,{className:"fixed inset-x-4 bottom-4 top-4 z-50 mx-auto flex max-w-[min(74rem,calc(100vw-2rem))] flex-col overflow-hidden rounded-[32px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,27,42,0.98),rgba(10,15,28,0.98))] shadow-[0_36px_110px_rgba(3,8,18,0.48)]",children:[e.jsx("div",{className:"border-b border-white/8 px-5 py-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Wiki Ingest"}),e.jsx(Rt,{className:"mt-2 font-display text-[1.5rem] tracking-[-0.04em] text-white",children:$?"Ingest review and progress":"Build wiki memory from source files"}),e.jsx(Gt,{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:"Upload notes, media, ZIP archives, links, or pasted text. Forge will process them in the background, propose pages and entities, and let you keep only what belongs."})]}),e.jsx(_t,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white","aria-label":"Close ingest modal",children:e.jsx(mt,{className:"size-4"})})})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto px-5 py-5",children:$?e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-white/[0.04] p-4 sm:p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:["Job ",$.job.id]}),e.jsx("div",{className:"mt-2 text-xl font-semibold text-white",children:$.job.latestMessage||"Ingest job"}),e.jsxs("div",{className:"mt-2 text-sm leading-6 text-white/56",children:[$.job.status," · ",$.job.phase," · started ",Lo($.job.createdAt)]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(W,{variant:"secondary",size:"sm",onClick:K,children:"New ingest"}),ce?e.jsxs(e.Fragment,{children:[e.jsxs(W,{variant:"secondary",size:"sm",pending:ue.isPending,pendingLabel:"Rerunning",onClick:()=>void ue.mutateAsync(),children:[e.jsx(vt,{className:"size-3.5"}),"Rerun"]}),e.jsx(W,{variant:"ghost",size:"sm",className:"border border-rose-300/18 bg-rose-400/10 text-rose-100 hover:bg-rose-400/16",pending:me.isPending,pendingLabel:"Deleting",onClick:()=>{window.confirm("Delete this ingest history entry? Published pages or entities will stay, but discarded or unreviewed ingest data will be removed.")&&me.mutateAsync()},children:"Delete"})]}):null]})]}),e.jsx("div",{className:"mt-5 grid gap-3 sm:grid-cols-4",children:[{label:"Progress",value:`${$.job.progressPercent}%`},{label:"Files",value:`${$.job.processedFiles}/${$.job.totalFiles}`},{label:"Pages",value:String($.job.createdPageCount)},{label:"Entities",value:String($.job.createdEntityCount)}].map(V=>e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-[rgba(8,12,22,0.68)] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:V.label}),e.jsx("div",{className:"mt-2 text-lg font-semibold text-white",children:V.value})]},V.label))}),e.jsx("div",{className:"mt-5",children:e.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-white/[0.06]",children:e.jsx("div",{className:"h-full rounded-full bg-[linear-gradient(90deg,rgba(192,193,255,0.8),rgba(133,222,255,0.8))] transition-all duration-300",style:{width:`${$.job.progressPercent}%`}})})}),ne?e.jsx("div",{className:"mt-4 rounded-[20px] border border-rose-300/22 bg-rose-400/10 px-4 py-3 text-sm text-rose-100",children:ne}):null]}),e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-white/[0.04] p-4 sm:p-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Rich log"}),e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>o(`/settings/logs?jobId=${encodeURIComponent($.job.id)}`),children:"Open full logs"})]}),e.jsx("div",{className:"mt-4 grid max-h-[28rem] gap-2 overflow-y-auto",children:z.length===0?e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 px-4 py-4 text-sm text-white/45",children:"Waiting for the backend to emit progress."}):z.map(V=>e.jsx("div",{className:"rounded-[18px] border border-white/8 bg-[rgba(7,11,21,0.72)] px-4 py-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-white/55",children:V.level}),typeof V.metadata.scope=="string"?e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-white/38",children:V.metadata.scope}):null,typeof V.metadata.eventKey=="string"?e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-white/38",children:V.metadata.eventKey}):null]}),e.jsx("div",{className:"mt-2 text-sm text-white/82",children:Ut(V.metadata,"eventKey")==="llm_compile_background_polled"?nv(V,V.repetitionCount):V.message}),V.repetitionCount>1?e.jsxs("div",{className:"mt-2 text-xs text-white/44",children:["Combined ",V.repetitionCount," repeated polling updates."]}):null,Object.keys(V.metadata).length>0?e.jsxs("details",{className:"mt-3",children:[e.jsx("summary",{className:"cursor-pointer text-xs text-white/45",children:"View metadata"}),e.jsx("pre",{className:"mt-2 overflow-x-auto whitespace-pre-wrap rounded-[14px] border border-white/8 bg-black/20 px-3 py-3 text-[11px] leading-5 text-white/52",children:JSON.stringify(V.metadata,null,2)})]}):null]}),e.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-white/38",children:Lo(V.createdAt)})]})},V.id))})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-white/[0.04] p-4 sm:p-5",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Source files"}),e.jsx("div",{className:"mt-4 grid gap-2",children:$.assets.map(V=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[18px] border border-white/8 bg-[rgba(7,11,21,0.72)] px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white",children:V.fileName||V.sourceLocator||"Source"}),e.jsx("div",{className:"mt-1 text-xs text-white/45",children:V.mimeType||V.sourceKind})]}),e.jsx("div",{className:"shrink-0 text-[11px] uppercase tracking-[0.14em] text-white/40",children:V.status})]},V.id))})]}),e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-white/[0.04] p-4 sm:p-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Review"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Keep the candidates that belong in Forge and discard the rest."})]}),di.has($.job.status)?e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-xs text-white/58",children:[e.jsx(sd,{className:"size-3.5 animate-spin"}),"Processing"]}):null]}),e.jsx("div",{className:"mt-4 grid gap-3",children:E.length===0?e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 px-4 py-4 text-sm text-white/45",children:di.has($.job.status)?"Candidates will appear here while the job progresses.":"This job has no reviewable candidates left."}):E.map(V=>e.jsx(dv,{candidate:V,spaceId:$.job.spaceId,decision:G[V.id]??{action:"keep"},onDecisionChange:D=>Q(X=>({...X,[V.id]:D}))},V.id))}),_?e.jsx("div",{className:"mt-4 rounded-[20px] border border-rose-300/22 bg-rose-400/10 px-4 py-3 text-sm text-rose-100",children:_}):null,E.length>0&&!di.has($.job.status)?e.jsx("div",{className:"mt-5",children:e.jsxs(W,{className:"min-h-12",pending:oe.isPending,pendingLabel:"Publishing review",onClick:()=>void oe.mutateAsync(),children:[e.jsx(Jr,{className:"size-4"}),"Publish kept candidates"]})}):null]})]})]}):e.jsxs("div",{className:"grid gap-5 lg:grid-cols-[minmax(0,1.15fr)_minmax(18rem,0.85fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:[{id:"files",label:"Files and ZIP",detail:"Drag many files or one archive.",icon:en},{id:"url",label:"URL",detail:"Pull a webpage or remote file.",icon:rh},{id:"text",label:"Paste text",detail:"Turn notes or transcripts into pages.",icon:Kn}].map(V=>{const D=V.icon,X=V.id===f;return e.jsxs("button",{type:"button",className:re("rounded-[24px] border px-4 py-4 text-left transition",X?"border-[rgba(192,193,255,0.24)] bg-[rgba(192,193,255,0.12)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07] hover:text-white"),onClick:()=>b(V.id),children:[e.jsx(D,{className:"size-4 text-[var(--secondary)]"}),e.jsx("div",{className:"mt-3 text-sm font-semibold",children:V.label}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/48",children:V.detail})]},V.id)})}),e.jsx("div",{className:"rounded-[28px] border border-white/8 bg-[rgba(9,14,26,0.72)] p-4 sm:p-5",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsx(ie,{value:p,onChange:V=>w(V.target.value),placeholder:"Optional title hint"}),f==="files"?e.jsxs("div",{className:re("rounded-[28px] border-2 border-dashed px-5 py-8 text-center transition",y?"border-[rgba(192,193,255,0.35)] bg-[rgba(192,193,255,0.08)]":"border-white/10 bg-white/[0.03]"),onDragEnter:V=>{V.preventDefault(),N(!0)},onDragLeave:V=>{V.preventDefault(),N(!1)},onDragOver:V=>{V.preventDefault(),N(!0)},onDrop:V=>{V.preventDefault(),N(!1);const D=Array.from(V.dataTransfer.files);P(X=>[...X,...D])},children:[e.jsx("div",{className:"mx-auto flex size-14 items-center justify-center rounded-full border border-white/10 bg-white/[0.05]",children:e.jsx(en,{className:"size-5 text-white/72"})}),e.jsx("div",{className:"mt-4 text-base font-semibold text-white",children:"Drop files, media, notes, or ZIP archives here"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/50",children:"Forge accepts many files at once and queues the ingest in the background so the UI stays responsive."}),e.jsxs("label",{className:"mt-5 inline-flex cursor-pointer items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm text-white/78 transition hover:bg-white/[0.08] hover:text-white",children:[e.jsx(en,{className:"size-4"}),"Choose files",e.jsx("input",{type:"file",multiple:!0,className:"hidden",onChange:V=>P(Array.from(V.target.files??[]))})]}),M.length>0?e.jsx("div",{className:"mt-5 grid gap-2 text-left",children:M.map(V=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 text-sm text-white/72",children:[e.jsx("span",{className:"truncate",children:V.name}),e.jsx("span",{className:"shrink-0 text-xs text-white/42",children:V.name.toLowerCase().endsWith(".zip")?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(lh,{className:"size-3.5"}),"ZIP"]}):`${Math.max(1,Math.round(V.size/1024))} KB`})]},`${V.name}-${V.size}-${V.lastModified}`))}):null]}):null,f==="url"?e.jsx(ie,{value:v,onChange:V=>I(V.target.value),placeholder:"https://example.com/source"}):null,f==="text"?e.jsx(Ce,{value:k,onChange:V=>S(V.target.value),placeholder:"Paste notes, transcripts, meeting writeups, or source material here…",className:"min-h-[18rem]"}):null]})})]}),e.jsxs("aside",{className:"grid h-fit gap-4",children:[C?null:e.jsxs("div",{className:"rounded-[30px] border border-amber-300/28 bg-[linear-gradient(180deg,rgba(120,74,14,0.28),rgba(37,22,8,0.42))] p-5 shadow-[0_24px_64px_rgba(12,6,0,0.22)]",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 flex size-10 shrink-0 items-center justify-center rounded-full border border-amber-200/20 bg-amber-300/12 text-amber-100",children:e.jsx(Vn,{className:"size-4.5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-amber-100/62",children:"OpenAI setup required for smart ingest"}),e.jsx("div",{className:"mt-2 text-lg font-semibold text-white",children:"Forge can only do a raw import without OpenAI"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/78",children:"Without an OpenAI ingest profile, Forge cannot extract key insights, split the source into draft wiki pages, or propose Forge entities. The fallback is just a direct text import or media reference with no structured synthesis."}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/62",children:"Set up the API key, model, thinking, and verbosity first, then come back here to build real draft pages and reviewable entity proposals."})]})]}),e.jsxs("div",{className:"mt-5 grid gap-3 sm:grid-cols-2",children:[e.jsxs(W,{className:"w-full",onClick:()=>{s(!1),o("/settings/wiki?setupLlm=1")},children:[e.jsx(vt,{className:"size-4"}),"Open OpenAI setup"]}),e.jsx(W,{variant:"secondary",className:"w-full",onClick:()=>{s(!1),o("/settings/wiki")},children:"Open Wiki settings"})]})]}),e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 text-left",onClick:()=>T(V=>!V),children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Advanced"}),e.jsx("div",{className:"mt-2 text-sm text-white/72",children:"Model, parse, and target controls."})]}),e.jsx(vt,{className:"size-4 text-white/58"})]}),A?e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"mb-2 text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Space"}),e.jsx("div",{className:"grid gap-2",children:i.map(V=>e.jsxs("button",{type:"button",className:re("rounded-[18px] border px-3 py-3 text-left text-sm transition",m===V.id?"border-[rgba(192,193,255,0.24)] bg-[rgba(192,193,255,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/68 hover:bg-white/[0.06] hover:text-white"),onClick:()=>h(V.id),children:[e.jsx("div",{children:V.label}),e.jsx("div",{className:"mt-1 text-xs text-white/45",children:V.description||`/${V.slug}`})]},V.id))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-2 text-[11px] uppercase tracking-[0.16em] text-white/42",children:"LLM profile"}),e.jsxs("div",{className:"grid gap-2",children:[F.map(V=>e.jsxs("button",{type:"button",className:re("rounded-[18px] border px-3 py-3 text-left text-sm transition",u===V.id?"border-[rgba(192,193,255,0.24)] bg-[rgba(192,193,255,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/68 hover:bg-white/[0.06] hover:text-white"),onClick:()=>j(V.id),children:[e.jsx("div",{children:V.label}),e.jsx("div",{className:"mt-1 text-xs text-white/45",children:V.model})]},V.id)),F.length===0?e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 px-4 py-4 text-sm text-white/48",children:"No enabled profile with a saved key yet."}):null]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-2 text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Parse mode"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-3",children:[{id:"auto",label:"Auto"},{id:"multimodal",label:"Multimodal"},{id:"text_only",label:"Text only"}].map(V=>e.jsx("button",{type:"button",className:re("rounded-[18px] border px-3 py-3 text-sm transition",L===V.id?"border-[rgba(192,193,255,0.24)] bg-[rgba(192,193,255,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/68 hover:bg-white/[0.06] hover:text-white"),onClick:()=>q(V.id),children:V.label},V.id))})]})]}):null]}),e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(192,193,255,0.12),rgba(192,193,255,0.05))] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[e.jsx(Jr,{className:"size-4 text-[var(--secondary)]"}),e.jsx("span",{className:"text-sm font-semibold",children:"Publish only what belongs"})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/62",children:"Forge stages candidate pages, proposed entity records, and page updates first. You review the output before anything is committed to the live memory graph."})]}),ne?e.jsx("div",{className:"rounded-[20px] border border-rose-300/22 bg-rose-400/10 px-4 py-3 text-sm text-rose-100",children:ne}):null,e.jsxs(W,{className:"min-h-12",pending:le.isPending,pendingLabel:"Starting ingest",disabled:!C,onClick:()=>void le.mutateAsync(),children:[e.jsx(vt,{className:"size-4"}),"Start background ingest"]})]})]})})]})]})})}function cv(t){return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",year:"numeric"}).format(new Date(t))}function Qc({nodes:t,activeSlug:s,spaceId:i,depth:n=0}){return e.jsx("ul",{className:re("grid gap-1",n>0&&"mt-1"),children:t.map(a=>{const r=a.page.slug===s;return e.jsxs("li",{className:"grid gap-1",children:[e.jsx(Le,{to:{pathname:a.page.slug==="index"?"/wiki":`/wiki/page/${encodeURIComponent(a.page.slug)}`,search:`?spaceId=${encodeURIComponent(i)}`},className:re("rounded-lg px-2 py-1.5 text-[12px] leading-5 transition",r?"bg-white/[0.08] text-white":"text-white/64 hover:bg-white/[0.04] hover:text-white"),style:{paddingLeft:`${.5+n*.7}rem`},children:a.page.title}),a.children.length>0?e.jsx(Qc,{nodes:a.children,activeSlug:s,spaceId:i,depth:n+1}):null]},a.page.id)})})}function mv({open:t,onOpenChange:s,spaces:i,activeSpaceId:n,onSelect:a}){return e.jsx(Lt,{open:t,onOpenChange:s,children:e.jsxs(Dt,{children:[e.jsx($t,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.72)] backdrop-blur-sm"}),e.jsxs(Ot,{className:"fixed left-1/2 top-[14vh] z-50 w-[min(28rem,calc(100vw-1.5rem))] -translate-x-1/2 rounded-[28px] border border-white/10 bg-[rgba(10,15,28,0.97)] p-4 shadow-[0_32px_90px_rgba(0,0,0,0.45)] sm:p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(Rt,{className:"font-display text-[1.2rem] tracking-[-0.04em] text-white",children:"Choose wiki space"}),e.jsx(Gt,{className:"mt-1 text-[13px] leading-6 text-white/56",children:"Switch the reading space without leaving the article surface."})]}),e.jsx(_t,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white","aria-label":"Close space picker",children:e.jsx(mt,{className:"size-4"})})})]}),e.jsx("div",{className:"mt-4 grid gap-2",children:i.map(r=>{const l=r.id===n;return e.jsxs("button",{type:"button",className:re("flex items-center justify-between gap-3 rounded-[22px] border px-4 py-3 text-left transition",l?"border-[rgba(192,193,255,0.22)] bg-[rgba(192,193,255,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/78 hover:bg-white/[0.06] hover:text-white"),onClick:()=>{a(r.id),s(!1)},children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[14px] font-semibold text-inherit",children:r.label}),e.jsx("span",{className:"mt-1 block text-[12px] leading-5 text-white/52",children:r.description||`/${r.slug}`})]}),l?e.jsx(ji,{className:"size-4 shrink-0 text-[var(--primary)]"}):null]},r.id)})})]})]})})}function $o(){var J,ee,le,oe,ue,me,$,ce,E;const t=ht(),{slug:s}=Hs(),[i,n]=ft(),[a,r]=c.useState(!1),[l,d]=c.useState(!1),[o,x]=c.useState(!1),[f,b]=c.useState("hybrid"),[m,h]=c.useState(""),[p,w]=c.useState(""),v=c.useRef(null),I=i.get("spaceId")??"",k=i.get("ingest")==="1",S=i.get("ingestJobId"),M=pe({queryKey:["forge-wiki-settings"],queryFn:Ua}),P=I||((ee=(J=M.data)==null?void 0:J.settings.spaces[0])==null?void 0:ee.id)||"",y=((le=M.data)==null?void 0:le.settings.embeddingProfiles.filter(z=>z.enabled))??[];c.useEffect(()=>{var z;!p&&((z=y[0])!=null&&z.id)&&w(y[0].id)},[y,p]),c.useEffect(()=>{var z,K;if(!I&&((K=(z=M.data)==null?void 0:z.settings.spaces[0])!=null&&K.id)){const je=new URLSearchParams(i);je.set("spaceId",M.data.settings.spaces[0].id),n(je,{replace:!0})}},[i,I,n,M.data]);const N=pe({queryKey:["forge-wiki-home",P],queryFn:()=>Ju({spaceId:P||void 0}),enabled:!!P&&!s}),A=pe({queryKey:["forge-wiki-page-by-slug",P,s],queryFn:()=>Yu({slug:s??"index",spaceId:P||void 0}),enabled:!!P&&!!s}),T=pe({queryKey:["forge-wiki-tree",P],queryFn:()=>Vu({spaceId:P||void 0,kind:"wiki"}),enabled:!!P}),F=pe({queryKey:["forge-wiki-modal-search",P,f,m,p],queryFn:()=>tp({spaceId:P||void 0,mode:f,query:m.trim(),profileId:(f==="semantic"||f==="hybrid")&&p||void 0,limit:30}),enabled:a&&!!P&&m.trim().length>0}),u=s?A.data??null:N.data??null,[j,L]=c.useState(null);c.useEffect(()=>{u&&L(u)},[u]);const q=!!P&&(s?A.isFetching:N.isFetching),G=u??(q?j:null),Q=(G==null?void 0:G.page)??null,ne=((oe=M.data)==null?void 0:oe.settings.spaces.find(z=>z.id===P))??null,H=c.useMemo(()=>((Q==null?void 0:Q.links)??[]).map(z=>({id:`${z.entityType}:${z.entityId}`,href:Es(z.entityType,z.entityId),label:`${z.entityType} · ${z.entityId}`})),[Q==null?void 0:Q.links]),_=(z,K=!1)=>{const je=new URLSearchParams(i);z(je),n(je,{replace:K})},U=z=>{_(K=>{K.set("ingest","1"),z?K.set("ingestJobId",z):K.delete("ingestJobId"),P&&K.set("spaceId",P)})},R=()=>{_(z=>{z.delete("ingest"),z.delete("ingestJobId")})},C=z=>{_(K=>{K.set("ingest","1"),z?K.set("ingestJobId",z):K.delete("ingestJobId"),P&&K.set("spaceId",P)})};return c.useEffect(()=>{if(!o)return;const z=je=>{var V;(V=v.current)!=null&&V.contains(je.target)||x(!1)},K=je=>{je.key==="Escape"&&x(!1)};return document.addEventListener("pointerdown",z),document.addEventListener("keydown",K),()=>{document.removeEventListener("pointerdown",z),document.removeEventListener("keydown",K)}},[o]),!Q&&(M.isLoading||T.isLoading||!s&&N.isLoading||s&&A.isLoading)?e.jsx(xt,{eyebrow:"Wiki",title:"Loading the article",description:"Preparing the current space, article, and wiki index."}):!Q&&(M.isError||N.isError||A.isError||T.isError)?e.jsx(Oe,{eyebrow:"Wiki",error:M.error??N.error??A.error??T.error,onRetry:()=>{M.refetch(),N.refetch(),A.refetch(),T.refetch()}}):Q?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-4 sm:px-5 lg:px-6",children:e.jsxs("div",{className:"mx-auto flex w-full max-w-[1680px] flex-col gap-4",children:[e.jsxs("section",{className:"wiki-frame px-3 py-3 sm:px-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] uppercase tracking-[0.16em] text-white/42",children:[e.jsx("span",{children:"Wiki"}),ne?e.jsx("span",{children:ne.label}):null,e.jsx("span",{children:cv(Q.updatedAt)})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row lg:items-center",children:[e.jsxs("button",{type:"button",className:"wiki-search-launch flex min-h-[2.9rem] w-full items-center gap-3 rounded-[18px] border border-white/8 bg-white/[0.04] px-4 text-left text-[14px] text-white/56 transition hover:bg-white/[0.06] hover:text-white lg:flex-1",onClick:()=>r(!0),children:[e.jsx(dt,{className:"size-4 shrink-0 text-white/44"}),e.jsx("span",{children:"Search this wiki"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 lg:shrink-0",children:[e.jsx("button",{type:"button",className:"wiki-space-trigger inline-flex min-h-[2.9rem] items-center gap-2 rounded-[18px] border border-white/8 bg-white/[0.04] px-4 text-[13px] font-medium text-white/78 transition hover:bg-white/[0.07] hover:text-white",onClick:()=>d(!0),children:e.jsx("span",{className:"max-w-[16rem] truncate",children:(ne==null?void 0:ne.label)??"Wiki space"})}),e.jsxs("div",{className:"relative",ref:v,children:[e.jsxs(W,{variant:"secondary",size:"sm",className:"min-h-[2.9rem]",onClick:()=>x(z=>!z),children:[e.jsx(vt,{className:"size-3.5"}),"Ingest",e.jsx(Si,{className:"size-3.5"})]}),o?e.jsxs("div",{className:"absolute right-0 top-[calc(100%+0.5rem)] z-20 grid min-w-[15rem] gap-2 rounded-[22px] border border-white/10 bg-[rgba(9,14,27,0.98)] p-2 shadow-[0_24px_60px_rgba(0,0,0,0.35)]",children:[e.jsxs("button",{type:"button",className:"flex items-start gap-3 rounded-[18px] px-3 py-3 text-left transition hover:bg-white/[0.06]",onClick:()=>{x(!1),U()},children:[e.jsx(vt,{className:"mt-0.5 size-4 shrink-0 text-[var(--primary)]"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-medium text-white",children:"New ingest"}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-white/48",children:"Start a fresh import from files, URLs, or pasted text."})]})]}),e.jsxs("button",{type:"button",className:"flex items-start gap-3 rounded-[18px] px-3 py-3 text-left transition hover:bg-white/[0.06]",onClick:()=>{x(!1),t(`/wiki/ingest-history${P?`?spaceId=${encodeURIComponent(P)}`:""}`)},children:[e.jsx(ed,{className:"mt-0.5 size-4 shrink-0 text-[var(--secondary)]"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-medium text-white",children:"History"}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-white/48",children:"Browse prior ingests, reopen reviews, and delete old ingest records."})]})]})]}):null]}),e.jsxs(W,{variant:"secondary",size:"sm",className:"min-h-[2.9rem]",onClick:()=>t(`/wiki/edit/${encodeURIComponent(Q.id)}?spaceId=${encodeURIComponent(P)}`,{state:{initialPage:Q}}),children:[e.jsx(oh,{className:"size-3.5"}),"Edit"]}),e.jsxs(W,{size:"sm",className:"min-h-[2.9rem]",onClick:()=>t(`/wiki/new?spaceId=${encodeURIComponent(P)}`),children:[e.jsx(Wt,{className:"size-3.5"}),"New page"]})]})]})]}),e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[15rem_minmax(0,1fr)] xl:grid-cols-[16rem_minmax(0,1fr)]",children:[e.jsxs("aside",{className:"wiki-frame h-fit px-2 py-3 sm:px-3 lg:sticky lg:top-[5.75rem]",children:[e.jsx("div",{className:"px-2 pb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-white/42",children:"Index"}),e.jsx(Qc,{nodes:((ue=T.data)==null?void 0:ue.tree)??[],activeSlug:Q.slug,spaceId:P})]}),e.jsxs("article",{"aria-busy":q,className:re("wiki-frame relative overflow-hidden px-4 py-5 transition-[opacity,transform] duration-200 sm:px-6 sm:py-6",q&&"opacity-[0.985]"),children:[q?e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-px bg-[linear-gradient(90deg,transparent,rgba(192,193,255,0.8),transparent)] opacity-90"}):null,e.jsxs("div",{className:"wiki-reading-copy wiki-reading-flow mx-auto max-w-[76rem]",children:[e.jsx(Kc,{markdown:Q.contentMarkdown,spaceId:P}),Q.summary.trim()?e.jsx("p",{className:"mt-5 border-t border-white/8 pt-4 text-[13px] leading-6 text-white/56",children:Q.summary}):null,H.length>0?e.jsxs("section",{className:"mt-8 border-t border-white/8 pt-4",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-white/42",children:"Forge links"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:H.map(z=>e.jsx("a",{href:z.href?Ws(z.href):void 0,className:"rounded-full bg-white/[0.05] px-3 py-1.5 text-[12px] text-white/76 transition hover:bg-white/[0.1] hover:text-white",children:z.label},z.id))})]}):null,G!=null&&G.backlinkSourceNotes.length?e.jsxs("section",{className:"mt-8 border-t border-white/8 pt-4",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-white/42",children:"Linked here"}),e.jsx("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:G.backlinkSourceNotes.map(z=>e.jsxs(Le,{to:{pathname:z.slug==="index"?"/wiki":`/wiki/page/${encodeURIComponent(z.slug)}`,search:`?spaceId=${encodeURIComponent(z.spaceId)}`},className:"rounded-xl border border-white/8 bg-white/[0.03] px-4 py-3 transition hover:bg-white/[0.06]",children:[e.jsx("div",{className:"text-[13px] font-semibold text-white",children:z.title}),z.summary?e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/56",children:z.summary}):null]},z.id))})]}):null]})]})]})]})}),e.jsx(Lt,{open:a,onOpenChange:r,children:e.jsxs(Dt,{children:[e.jsx($t,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.8)] backdrop-blur-sm"}),e.jsxs(Ot,{className:"fixed left-1/2 top-[8vh] z-50 w-[min(54rem,calc(100vw-1.5rem))] -translate-x-1/2 rounded-[28px] border border-white/10 bg-[rgba(10,15,28,0.96)] p-4 shadow-[0_30px_90px_rgba(0,0,0,0.45)] sm:p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsx("div",{children:e.jsx(Rt,{className:"font-display text-[1.35rem] tracking-[-0.04em] text-white",children:"Search the wiki"})}),e.jsx(_t,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white","aria-label":"Close search",children:e.jsx(mt,{className:"size-4"})})})]}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsx(ie,{autoFocus:!0,value:m,onChange:z=>h(z.target.value),placeholder:"Search wiki pages",className:"h-11 rounded-2xl border-white/10 bg-white/[0.04] text-[14px] text-white placeholder:text-white/28"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[["text","hybrid","semantic","entity"].map(z=>e.jsx("button",{type:"button",className:re("rounded-full px-3 py-1.5 text-[12px] font-medium uppercase tracking-[0.14em] transition",f===z?"bg-white/[0.12] text-white":"bg-white/[0.04] text-white/54 hover:bg-white/[0.08] hover:text-white"),onClick:()=>b(z),children:z},z)),(f==="semantic"||f==="hybrid")&&y.length>0?e.jsx("select",{className:"ml-auto rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-[12px] text-white",value:p,onChange:z=>w(z.target.value),children:y.map(z=>e.jsx("option",{value:z.id,children:z.label},z.id))}):null]})]}),e.jsx("div",{className:"mt-4 max-h-[60vh] overflow-y-auto",children:m.trim()?F.isLoading?e.jsx(xt,{eyebrow:"Wiki search",title:"Searching",description:"Ranking matching pages for this query."}):F.isError?e.jsx(Oe,{eyebrow:"Wiki search",error:F.error,onRetry:()=>void F.refetch()}):(me=F.data)!=null&&me.results.length?e.jsx("div",{className:"grid gap-2",children:F.data.results.map(z=>e.jsx("button",{type:"button",className:"rounded-2xl border border-white/8 bg-white/[0.03] px-4 py-3 text-left transition hover:bg-white/[0.06]",onClick:()=>{r(!1),t({pathname:z.page.slug==="index"?"/wiki":`/wiki/page/${encodeURIComponent(z.page.slug)}`,search:`?spaceId=${encodeURIComponent(z.page.spaceId)}`})},children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[14px] font-semibold text-white",children:z.page.title}),z.page.summary?e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/56",children:z.page.summary}):null]}),e.jsx(O,{size:"sm",tone:"meta",children:z.score.toFixed(2)})]})},z.page.id))}):e.jsx("div",{className:"rounded-2xl border border-dashed border-white/10 px-4 py-10 text-center text-[13px] leading-6 text-white/42",children:"No pages matched this search."}):e.jsx("div",{className:"rounded-2xl border border-dashed border-white/10 px-4 py-10 text-center text-[13px] leading-6 text-white/42",children:"Start typing to search the current wiki space."})})]})]})}),e.jsx(mv,{open:l,onOpenChange:d,spaces:(($=M.data)==null?void 0:$.settings.spaces)??[],activeSpaceId:P,onSelect:z=>{const K=new URLSearchParams(i);K.set("spaceId",z),n(K,{replace:!0}),t("/wiki",{replace:!0})}}),e.jsx(Uc,{open:k,onOpenChange:z=>{if(z){U(S);return}R()},spaces:((ce=M.data)==null?void 0:ce.settings.spaces)??[],llmProfiles:((E=M.data)==null?void 0:E.settings.llmProfiles)??[],initialSpaceId:P,selectedJobId:S,onJobSelected:C,linkedEntityHints:Q.links.map(z=>({entityType:z.entityType,entityId:z.entityId,anchorKey:null}))??[]})]}):e.jsx(gt,{eyebrow:"Wiki",title:"Article not found",description:"This page does not exist in the selected space."})}const hv=[{value:"all",label:"All"},{value:"queued",label:"Queued"},{value:"processing",label:"Processing"},{value:"completed",label:"Completed"},{value:"failed",label:"Failed"},{value:"review",label:"Review"},{value:"reviewed",label:"Reviewed"}];function uv(t){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(t))}function pv(t,s){return s==="all"?!0:t.job.status===s||t.job.phase===s}function xv(){var S,M,P,y,N,A;const t=ht(),s=We(),[i,n]=ft(),a=i.get("spaceId")||"",r=i.get("q")||"",l=i.get("tag")||"all",d=i.get("from")||"",o=i.get("to")||"",x=i.get("ingest")==="1",f=i.get("ingestJobId"),b=pe({queryKey:["forge-wiki-settings"],queryFn:Ua}),m=pe({queryKey:["forge-wiki-ingest-history",a],queryFn:()=>Td({spaceId:a||void 0,limit:200}),enabled:b.isSuccess}),h=ge({mutationFn:T=>Pd(T),onSuccess:async(T,F)=>{if(await s.invalidateQueries({queryKey:["forge-wiki-ingest-history"]}),await s.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),f===F){const u=new URLSearchParams(i);u.delete("ingest"),u.delete("ingestJobId"),n(u,{replace:!0})}}}),p=(T,F)=>{const u=new URLSearchParams(i);F.trim()?u.set(T,F.trim()):u.delete(T),n(u,{replace:!0})},w=c.useMemo(()=>{var u;const T=((u=m.data)==null?void 0:u.jobs)??[],F=r.trim().toLowerCase();return T.filter(j=>{if(!pv(j,l))return!1;const L=j.job.createdAt.slice(0,10);return d&&L<d||o&&L>o?!1:F?[j.job.titleHint,j.job.latestMessage,j.job.sourceLocator,j.job.status,j.job.phase,j.job.mimeType].join(" ").toLowerCase().includes(F):!0})},[d,(S=m.data)==null?void 0:S.jobs,r,l,o]),v=a||((P=(M=b.data)==null?void 0:M.settings.spaces[0])==null?void 0:P.id)||"",I=T=>{const F=new URLSearchParams(i);F.set("ingest","1"),T?F.set("ingestJobId",T):F.delete("ingestJobId"),n(F,{replace:!0})},k=()=>{const T=new URLSearchParams(i);T.delete("ingest"),T.delete("ingestJobId"),n(T,{replace:!0})};return b.isLoading||m.isLoading?e.jsx(It,{eyebrow:"Wiki",title:"Loading ingest history",description:"Gathering prior imports, statuses, and review state.",columns:1,blocks:6}):b.isError||m.isError?e.jsx(Oe,{eyebrow:"Wiki",error:b.error??m.error,onRetry:()=>{b.refetch(),m.refetch()}}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-4 sm:px-5 lg:px-6",children:e.jsxs("div",{className:"mx-auto grid w-full max-w-[1480px] gap-5",children:[e.jsx(Ke,{title:"Wiki Ingest History",description:"Search prior ingests, reopen a review, or clear ingest records without touching pages and entities that were already published.",badge:`${w.length} matching jobs`}),e.jsxs(se,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"History Filters"}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Narrow by free text, date range, space, or status tags."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(W,{variant:"secondary",onClick:()=>t(`/wiki${a?`?spaceId=${encodeURIComponent(a)}`:""}`),children:"Back to wiki"}),e.jsxs(W,{onClick:()=>I(),children:[e.jsx(vt,{className:"size-3.5"}),"New ingest"]})]})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1.4fr)_minmax(0,0.8fr)_minmax(0,0.8fr)_minmax(0,0.8fr)]",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Free text"}),e.jsx(ie,{value:r,onChange:T=>p("q",T.target.value),placeholder:"title, source, status, failure message…"})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"From"}),e.jsx(ie,{type:"date",value:d,onChange:T=>p("from",T.target.value)})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"To"}),e.jsx(ie,{type:"date",value:o,onChange:T=>p("to",T.target.value)})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Space"}),e.jsxs("select",{className:"h-11 rounded-[18px] border border-white/10 bg-white/[0.04] px-3 text-sm text-white",value:a,onChange:T=>p("spaceId",T.target.value),children:[e.jsx("option",{value:"",children:"All spaces"}),(((y=b.data)==null?void 0:y.settings.spaces)??[]).map(T=>e.jsx("option",{value:T.id,children:T.label},T.id))]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:hv.map(T=>e.jsx("button",{type:"button",className:re("rounded-full px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] transition",l===T.value?"bg-[var(--primary)]/[0.18] text-[var(--primary)]":"bg-white/[0.04] text-white/58 hover:bg-white/[0.08] hover:text-white"),onClick:()=>p("tag",T.value==="all"?"":T.value),children:T.label},T.value))})]}),w.length===0?e.jsx(gt,{eyebrow:"Wiki ingest",title:"No ingest jobs match these filters",description:"Try widening the dates or clearing a status tag."}):e.jsx("div",{className:"grid gap-3",children:w.map(T=>{const F=T.job.titleHint||T.job.latestMessage||T.job.sourceLocator||"Wiki ingest",u=!["queued","processing"].includes(T.job.status);return e.jsxs(se,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("button",{type:"button",className:"min-w-0 flex-1 text-left",onClick:()=>I(T.job.id),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Wiki ingest"}),e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] uppercase tracking-[0.16em] text-white/60",children:T.job.status}),e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] uppercase tracking-[0.16em] text-white/44",children:T.job.phase})]}),e.jsx("div",{className:"mt-3 text-lg font-semibold text-white",children:F}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-x-4 gap-y-1 text-sm text-white/56",children:[e.jsxs("span",{children:[T.job.progressPercent,"% · ",T.job.createdPageCount," pages ·"," ",T.job.createdEntityCount," entities"]}),e.jsx("span",{children:uv(T.job.createdAt)}),T.job.sourceLocator?e.jsx("span",{className:"truncate",children:T.job.sourceLocator}):null]})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx(W,{variant:"secondary",size:"sm",onClick:()=>I(T.job.id),children:"Open review"}),e.jsxs(W,{variant:"secondary",size:"sm",disabled:!u||h.isPending,pending:h.isPending&&h.variables===T.job.id,pendingLabel:"Deleting",onClick:()=>{!u||!window.confirm("Delete this ingest history entry? Published pages and entities will stay, but discarded or unreviewed ingest artifacts will be removed.")||h.mutateAsync(T.job.id)},children:[e.jsx(bt,{className:"size-3.5"}),"Delete"]})]})]}),T.job.errorMessage?e.jsx("div",{className:"rounded-[18px] border border-rose-400/18 bg-rose-500/[0.08] px-4 py-3 text-sm text-rose-100/86",children:T.job.errorMessage}):null,["queued","processing"].includes(T.job.status)?e.jsxs("div",{className:"inline-flex items-center gap-2 text-sm text-white/50",children:[e.jsx(sd,{className:"size-4 animate-spin"}),"This ingest is still active and cannot be deleted yet."]}):null]},T.job.id)})})]})}),e.jsx(Uc,{open:x,onOpenChange:T=>{T||k()},spaces:((N=b.data)==null?void 0:N.settings.spaces)??[],llmProfiles:((A=b.data)==null?void 0:A.settings.llmProfiles)??[],initialSpaceId:v,selectedJobId:f,onJobSelected:T=>I(T)})]})}const Ri={goal:"goal",project:"project",task:"task",strategy:"strategy",habit:"habit"};function gi(t,s){return`${t}:${s}`}function gv(t){const s=t.indexOf(":");return s<=0||s>=t.length-1?null:{entityType:t.slice(0,s),entityId:t.slice(s+1)}}function bv(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function ci(t){return Array.from(new Set(t.split(",").map(s=>s.trim()).filter(Boolean)))}function fv(t){if(!t.trim())return{};try{const s=JSON.parse(t);return s&&typeof s=="object"&&!Array.isArray(s)?s:{}}catch{return{}}}function wv(){return{pageId:null,kind:"wiki",title:"",slug:"",parentSlug:"index",indexOrder:0,showInIndex:!0,summary:"",aliasesText:"",contentMarkdown:`# Untitled
|
|
40
|
+
|
|
41
|
+
`,author:"",tagsText:"",frontmatterText:`{
|
|
42
|
+
"status": "draft"
|
|
43
|
+
}`,linkedValues:[]}}function Oo(t){return{pageId:t.id,kind:t.kind,title:t.title,slug:t.slug,parentSlug:t.parentSlug,indexOrder:t.indexOrder,showInIndex:t.showInIndex,summary:t.summary,aliasesText:t.aliases.join(", "),contentMarkdown:t.contentMarkdown,author:t.author??"",tagsText:(t.tags??[]).join(", "),frontmatterText:JSON.stringify(t.frontmatter??{},null,2),linkedValues:t.links.map(s=>gi(s.entityType,s.entityId))}}function mi({open:t,title:s,description:i,children:n,onOpenChange:a}){return e.jsx(Lt,{open:t,onOpenChange:a,children:e.jsxs(Dt,{children:[e.jsx($t,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.8)] backdrop-blur-sm"}),e.jsxs(Ot,{className:"fixed left-1/2 top-[12vh] z-50 w-[min(32rem,calc(100vw-1.5rem))] -translate-x-1/2 rounded-[24px] border border-white/10 bg-[rgba(10,15,28,0.96)] p-4 shadow-[0_24px_80px_rgba(0,0,0,0.45)] sm:p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(Rt,{className:"text-[1.05rem] font-semibold text-white",children:s}),e.jsx(Gt,{className:"mt-1 text-[13px] leading-6 text-white/56",children:i})]}),e.jsx(_t,{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",children:e.jsx(mt,{className:"size-4"})})})]}),e.jsx("div",{className:"mt-4",children:n})]})]})})}const vv="w-full rounded-[18px] border border-white/10 bg-[rgba(10,16,30,0.78)] px-3.5 py-3 text-[13px] text-white outline-none transition focus:border-[rgba(192,193,255,0.35)]";function Fo(t){return t.trim().toLowerCase()}function yv(t){const s=t.trim();return s?s.split(/\s+/).length:0}function jv({icon:t,label:s,onClick:i}){return e.jsxs("div",{className:"group relative",children:[e.jsx("button",{type:"button","aria-label":s,className:"inline-flex size-10 items-center justify-center rounded-[14px] border border-white/8 bg-white/[0.04] text-white/62 transition hover:bg-white/[0.08] hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[rgba(192,193,255,0.35)]",onClick:i,children:e.jsx(t,{className:"size-4"})}),e.jsx("div",{className:"pointer-events-none absolute left-1/2 top-[calc(100%+0.55rem)] z-20 -translate-x-1/2 rounded-[12px] border border-white/8 bg-[rgba(10,15,28,0.96)] px-2.5 py-1.5 text-[11px] font-medium text-white/76 opacity-0 shadow-[0_18px_40px_rgba(0,0,0,0.32)] transition group-hover:opacity-100 group-focus-within:opacity-100",children:s})]})}function Nv(t){return t.map(s=>({value:s.label,label:s.label,description:s.description,searchText:`${s.label} ${s.description}`,badge:e.jsx(O,{className:"bg-white/[0.08] text-white/80",style:s.color?{color:s.color}:void 0,children:s.label}),menuBadge:e.jsx(O,{className:"bg-white/[0.08] text-white/80",style:s.color?{color:s.color}:void 0,children:s.label})}))}function _o(){var oe,ue,me,$,ce,E,z,K,je,V;const t=Ye(),s=We(),i=ki(),n=ht(),{pageId:a}=Hs(),[r,l]=ft(),[d,o]=c.useState(()=>wv()),[x,f]=c.useState(null),[b,m]=c.useState(""),[h,p]=c.useState(""),[w,v]=c.useState(!1),[I,k]=c.useState(!1),[S,M]=c.useState(""),[P,y]=c.useState(""),N=c.useRef(null),A=((oe=i.state)==null?void 0:oe.initialPage)??null,T=pe({queryKey:["forge-wiki-settings"],queryFn:Ua}),F=pe({queryKey:["forge-wiki-page",a],queryFn:()=>Xu(a??""),enabled:!!a}),u=r.get("spaceId")||((ue=F.data)==null?void 0:ue.page.spaceId)||(A==null?void 0:A.spaceId)||(($=(me=T.data)==null?void 0:me.settings.spaces[0])==null?void 0:$.id)||"",j=((E=(ce=T.data)==null?void 0:ce.settings.spaces.find(D=>D.id===u))==null?void 0:E.label)??"Current space",L=pe({queryKey:["forge-wiki-pages",u],queryFn:()=>Hu({spaceId:u||void 0,limit:500}),enabled:!!u});c.useEffect(()=>{A&&(!a||A.id===a)&&o(Oo(A))},[a,A]),c.useEffect(()=>{var D;(D=F.data)!=null&&D.page&&o(Oo(F.data.page))},[F.data]);const q=c.useMemo(()=>{var D;return(((D=L.data)==null?void 0:D.pages)??[]).filter(X=>X.id!==d.pageId).sort((X,he)=>X.title.localeCompare(he.title))},[d.pageId,(z=L.data)==null?void 0:z.pages]),G=c.useMemo(()=>{var X;const D=new Map;for(const he of((X=L.data)==null?void 0:X.pages)??[])for(const ye of he.aliases??[]){const ze=ye.trim();ze&&D.set(ze.toLowerCase(),{value:ze,label:ze,description:`Alias on ${he.title}`,searchText:`${ze} ${he.title} ${he.slug}`,badge:e.jsx(O,{className:"bg-white/[0.08] text-white/80",children:ze}),menuBadge:e.jsx(O,{className:"bg-white/[0.08] text-white/80",children:ze})})}for(const he of ci(d.aliasesText))D.set(he.toLowerCase(),{value:he,label:he,description:"Wiki alias",searchText:he,badge:e.jsx(O,{className:"bg-white/[0.08] text-white/80",children:he}),menuBadge:e.jsx(O,{className:"bg-white/[0.08] text-white/80",children:he})});return Array.from(D.values()).sort((he,ye)=>he.label.localeCompare(ye.label))},[d.aliasesText,(K=L.data)==null?void 0:K.pages]),Q=c.useMemo(()=>[{value:"index",label:"Home",description:"Top-level index page",searchText:"home index top level root"},...q.map(D=>({value:D.slug,label:D.title,description:D.summary||D.slug,searchText:`${D.title} ${D.slug} ${D.summary}`}))],[q]),ne=c.useMemo(()=>{const D=Fo(S);return D?q.filter(X=>`${X.title} ${X.slug} ${X.summary}`.toLowerCase().includes(D)).slice(0,12):q.slice(0,12)},[S,q]),H=c.useMemo(()=>{const D=t.snapshot.goals.map(fe=>({value:gi("goal",fe.id),label:fe.title,description:fe.description,searchText:`${fe.title} ${fe.description}`,kind:Ri.goal})),X=t.snapshot.dashboard.projects.map(fe=>({value:gi("project",fe.id),label:fe.title,description:[fe.goalTitle,fe.description].filter(Boolean).join(" · "),searchText:`${fe.title} ${fe.goalTitle} ${fe.description}`,kind:Ri.project})),he=t.snapshot.tasks.map(fe=>({value:gi("task",fe.id),label:fe.title,description:fe.owner||fe.description,searchText:`${fe.title} ${fe.owner} ${fe.description}`,kind:Ri.task})),ye=t.snapshot.strategies.map(fe=>({value:gi("strategy",fe.id),label:fe.title,description:fe.overview,searchText:`${fe.title} ${fe.overview} ${fe.endStateDescription}`,kind:Ri.strategy})),ze=t.snapshot.habits.map(fe=>({value:gi("habit",fe.id),label:fe.title,description:fe.description,searchText:`${fe.title} ${fe.description}`,kind:Ri.habit}));return[...D,...X,...he,...ye,...ze].sort((fe,Pe)=>fe.label.localeCompare(Pe.label))},[t.snapshot.dashboard.projects,t.snapshot.goals,t.snapshot.habits,t.snapshot.strategies,t.snapshot.tasks]),_=c.useMemo(()=>{const D=Fo(P);return D?H.filter(X=>`${X.label} ${X.description??""} ${X.searchText??""}`.toLowerCase().includes(D)).slice(0,12):H.slice(0,12)},[H,P]),U=c.useMemo(()=>{const D=t.snapshot.tags.map(ye=>({label:ye.name,description:`Forge ${ye.kind} tag`,color:ye.color})),X=ci(d.tagsText).map(ye=>({label:ye,description:"Wiki tag"})),he=new Map;return[...D,...X].forEach(ye=>{he.set(ye.label.toLowerCase(),ye)}),Nv(Array.from(he.values()).sort((ye,ze)=>ye.label.localeCompare(ze.label)))},[d.tagsText,t.snapshot.tags]);function R(D){const X=N.current;o(he=>{const ye=he.contentMarkdown;if(!X)return{...he,contentMarkdown:`${ye}${ye.endsWith(`
|
|
44
|
+
`)?"":`
|
|
45
|
+
`}${D}`};const ze=X.selectionStart??ye.length,fe=X.selectionEnd??ye.length,Pe=`${ye.slice(0,ze)}${D}${ye.slice(fe)}`;return requestAnimationFrame(()=>{X.focus();const Ge=ze+D.length;X.setSelectionRange(Ge,Ge)}),{...he,contentMarkdown:Pe}})}const C=ge({mutationFn:async D=>{const X={kind:D.kind,title:D.title.trim(),slug:D.slug.trim()||bv(D.title),parentSlug:D.parentSlug&&D.parentSlug!=="none"?D.parentSlug:null,indexOrder:D.indexOrder,showInIndex:D.showInIndex,summary:D.summary.trim(),aliases:ci(D.aliasesText),contentMarkdown:D.contentMarkdown.trim(),author:D.author.trim()||null,tags:ci(D.tagsText),spaceId:u,frontmatter:fv(D.frontmatterText),links:D.linkedValues.map(he=>gv(he)).filter(he=>he!==null)};return D.pageId?ep(D.pageId,X):Zu(X)},onSuccess:async D=>{await Promise.all([s.invalidateQueries({queryKey:["forge-wiki-pages"]}),s.invalidateQueries({queryKey:["forge-wiki-page"]}),s.invalidateQueries({queryKey:["forge-wiki-home"]}),s.invalidateQueries({queryKey:["forge-wiki-page-by-slug"]}),s.invalidateQueries({queryKey:["forge-wiki-tree"]})]),n({pathname:D.page.slug==="index"?"/wiki":`/wiki/page/${encodeURIComponent(D.page.slug)}`,search:`?spaceId=${encodeURIComponent(D.page.spaceId)}`})}});if(T.isLoading||a&&F.isLoading&&!A)return e.jsx(xt,{eyebrow:"Wiki editor",title:"Preparing the editor",description:"Loading the draft, hierarchy, and link helpers."});if(T.isError||F.isError||L.isError)return e.jsx(Oe,{eyebrow:"Wiki editor",error:T.error??F.error??L.error,onRetry:()=>{T.refetch(),F.refetch(),L.refetch()}});if(a&&!((je=F.data)!=null&&je.page))return e.jsx(gt,{eyebrow:"Wiki editor",title:"Page not found",description:"This wiki entry does not exist anymore."});const J=[{kind:"wiki-link",icon:rs,label:"Wiki link"},{kind:"forge-link",icon:dh,label:"Forge link"},{kind:"infobox",icon:ch,label:"Infobox"},{kind:"admonition",icon:Vn,label:"Admonition"},{kind:"related",icon:mh,label:"Related"},{kind:"media",icon:hh,label:"Media"}],ee=yv(d.contentMarkdown),le=d.contentMarkdown.length;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-4 sm:px-5 lg:px-6",children:e.jsxs("div",{className:"mx-auto flex w-full max-w-[1720px] flex-col gap-4",children:[e.jsx("section",{className:"wiki-frame px-4 py-3 sm:px-5",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:"text-[11px] font-semibold uppercase tracking-[0.16em] text-white/42",children:"Wiki editor"}),e.jsx("h1",{className:"mt-1 text-[1.25rem] font-semibold tracking-[-0.04em] text-white",children:d.pageId?"Edit page":"New page"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(W,{variant:"secondary",size:"sm",className:"xl:hidden",onClick:()=>k(D=>!D),"aria-expanded":I,children:[I?e.jsx(_a,{className:"size-3.5"}):e.jsx(Si,{className:"size-3.5"}),"Metadata"]}),e.jsxs(W,{variant:"secondary",size:"sm",onClick:()=>n(-1),children:[e.jsx(qo,{className:"size-3.5"}),"Back"]}),e.jsxs(W,{size:"sm",pending:C.isPending,pendingLabel:"Saving",disabled:!d.title.trim()||!d.contentMarkdown.trim(),onClick:()=>void C.mutateAsync(d),children:[e.jsx(Zn,{className:"size-3.5"}),"Save page"]})]})]})}),e.jsxs("section",{className:"grid min-w-0 gap-4 xl:grid-cols-[minmax(19rem,23rem)_minmax(0,1fr)] xl:items-start",children:[e.jsx("aside",{className:re("order-2 min-w-0 xl:order-1 xl:block",I?"block":"hidden"),children:e.jsxs("section",{className:"wiki-frame px-4 py-4 sm:px-5 xl:sticky xl:top-[5.75rem]",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3 border-b border-white/8 pb-3",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-white/42",children:"Metadata"}),e.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-white/34",children:j})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Wiki space"}),e.jsxs("button",{type:"button",className:"flex min-h-[2.9rem] items-center justify-between gap-3 rounded-[18px] border border-white/8 bg-white/[0.04] px-3.5 text-[13px] text-white/82 transition hover:bg-white/[0.06] hover:text-white",onClick:()=>v(!0),children:[e.jsx("span",{className:"truncate",children:j}),e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Change"})]})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Title"}),e.jsx(ie,{value:d.title,onChange:D=>o(X=>({...X,title:D.target.value})),placeholder:"Page title"})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Slug"}),e.jsx(ie,{value:d.slug,onChange:D=>o(X=>({...X,slug:D.target.value})),placeholder:"page-slug"})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Summary"}),e.jsx(Ce,{value:d.summary,onChange:D=>o(X=>({...X,summary:D.target.value})),rows:4,placeholder:"Short summary"})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Tags"}),e.jsx(st,{options:U,selectedValues:ci(d.tagsText),onChange:D=>o(X=>({...X,tagsText:D.join(", ")})),placeholder:"Search or add tags",emptyMessage:"No tags yet.",createLabel:"Add tag",onCreate:async D=>{const X=D.trim();return{value:X,label:X,description:"Wiki tag",searchText:X,badge:e.jsx(O,{className:"bg-white/[0.08] text-white/80",children:X}),menuBadge:e.jsx(O,{className:"bg-white/[0.08] text-white/80",children:X})}}})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Forge entities"}),e.jsx(st,{options:H,selectedValues:d.linkedValues,onChange:D=>o(X=>({...X,linkedValues:D})),placeholder:"Search Forge entities"})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Aliases"}),e.jsx(st,{options:G,selectedValues:ci(d.aliasesText),onChange:D=>o(X=>({...X,aliasesText:D.join(", ")})),placeholder:"Search or add aliases",emptyMessage:"No aliases yet.",createLabel:"Add alias",onCreate:async D=>{const X=D.trim();return{value:X,label:X,description:"Wiki alias",searchText:X,badge:e.jsx(O,{className:"bg-white/[0.08] text-white/80",children:X}),menuBadge:e.jsx(O,{className:"bg-white/[0.08] text-white/80",children:X})}}})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Author"}),e.jsx(ie,{value:d.author,onChange:D=>o(X=>({...X,author:D.target.value})),placeholder:"Optional author"})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("label",{className:"grid gap-1.5",children:[e.jsxs("span",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.16em] text-white/42",children:[e.jsx("span",{children:"Parent"}),e.jsx(Xe,{content:"Choose the page that should own this page in the wiki tree.",label:"Explain parent page"})]}),e.jsx(st,{options:Q,selectedValues:d.parentSlug?[d.parentSlug]:[],onChange:D=>o(X=>({...X,parentSlug:D[0]??null})),placeholder:"Search parent page",emptyMessage:"No matching pages.",className:"[&_.max-w-\\\\[16rem\\\\]]:max-w-full"})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsxs("span",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.16em] text-white/42",children:[e.jsx("span",{children:"Order"}),e.jsx(Xe,{content:"Lower numbers appear earlier within the same parent page.",label:"Explain page order"})]}),e.jsx(ie,{type:"number",value:String(d.indexOrder),onChange:D=>o(X=>({...X,indexOrder:Number(D.target.value||0)}))})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-[18px] border border-white/8 bg-white/[0.03] px-3.5 py-3 text-[13px] text-white/74",children:[e.jsx("input",{type:"checkbox",className:"mt-0.5",checked:d.showInIndex,onChange:D=>o(X=>({...X,showInIndex:D.target.checked}))}),e.jsx("span",{children:"Show in index"})]})]})]})}),e.jsxs("div",{className:"order-1 grid min-w-0 gap-4 xl:order-2",children:[e.jsxs("section",{className:"wiki-frame overflow-hidden",children:[e.jsxs("div",{className:"flex min-h-12 w-full flex-wrap items-center justify-between gap-3 border-b border-white/8 bg-[rgba(10,16,30,0.5)] px-3 py-2 sm:px-4",children:[e.jsx("div",{className:"flex min-w-0 flex-wrap items-center justify-start gap-1.5",children:J.map(D=>e.jsx(jv,{icon:D.icon,label:D.label,onClick:()=>{f(D.kind),m(""),p(""),M(""),y("")}},D.kind))}),e.jsx("div",{className:"ml-auto flex min-w-0 flex-wrap items-center justify-end gap-3 pr-1",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-[11px] uppercase tracking-[0.14em] text-white/36",children:[e.jsxs("span",{children:[ee.toLocaleString()," words"]}),e.jsxs("span",{children:[le.toLocaleString()," chars"]})]})})]}),e.jsx("div",{className:"bg-[linear-gradient(180deg,rgba(8,13,24,0.98),rgba(9,14,26,0.94))]",children:e.jsx(Ce,{ref:N,value:d.contentMarkdown,onChange:D=>o(X=>({...X,contentMarkdown:D.target.value})),rows:26,className:"min-h-[38rem] resize-y rounded-none border-0 bg-transparent px-5 py-4 font-mono text-[13px] leading-6 text-white shadow-none outline-none focus-visible:ring-0 sm:min-h-[44rem] sm:px-6",placeholder:"Write the page in Markdown"})})]}),e.jsxs("section",{className:"wiki-frame overflow-hidden",children:[e.jsx("div",{className:"border-b border-white/8 px-4 py-3 sm:px-6",children:e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-white/42",children:"Preview"})}),e.jsx("div",{className:"px-4 py-5 sm:px-6",children:e.jsx("div",{className:"wiki-reading-copy wiki-reading-flow mx-auto max-w-[76rem]",children:e.jsx(Kc,{markdown:d.contentMarkdown,spaceId:u})})})]})]})]})]})}),e.jsx(mi,{open:x==="wiki-link",onOpenChange:D=>!D&&f(null),title:"Insert wiki link",description:"Search pages.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx(ie,{autoFocus:!0,value:S,onChange:D=>M(D.target.value),placeholder:"Search wiki pages",className:"h-11 rounded-2xl border-white/10 bg-white/[0.04] text-[14px] text-white placeholder:text-white/28"}),e.jsx("div",{className:"grid max-h-[22rem] gap-2 overflow-y-auto",children:ne.length>0?ne.map(D=>e.jsxs("button",{type:"button",className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-3 text-left transition hover:bg-white/[0.06]",onClick:()=>{R(`[[${D.slug}]]`),f(null),M("")},children:[e.jsx("div",{className:"text-[14px] font-semibold text-white",children:D.title}),e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/46",children:D.slug}),D.summary?e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/56",children:D.summary}):null]},D.id)):e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 px-4 py-8 text-center text-[13px] text-white/42",children:"No pages match this search."})})]})}),e.jsx(mi,{open:x==="forge-link",onOpenChange:D=>!D&&f(null),title:"Insert Forge link",description:"Search Forge entities.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx(ie,{autoFocus:!0,value:P,onChange:D=>y(D.target.value),placeholder:"Search Forge entities",className:"h-11 rounded-2xl border-white/10 bg-white/[0.04] text-[14px] text-white placeholder:text-white/28"}),e.jsx("div",{className:"grid max-h-[22rem] gap-2 overflow-y-auto",children:_.length>0?_.map(D=>e.jsxs("button",{type:"button",className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-3 text-left transition hover:bg-white/[0.06]",onClick:()=>{const[X,he]=D.value.split(":");R(`[[forge:${X}:${he}]]`),f(null),y("")},children:[e.jsx("div",{className:"text-[14px] font-semibold text-white",children:D.label}),D.description?e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/56",children:D.description}):null]},D.value)):e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 px-4 py-8 text-center text-[13px] text-white/42",children:"No entities match this search."})})]})}),e.jsx(mi,{open:x==="infobox",onOpenChange:D=>!D&&f(null),title:"Insert infobox",description:"Create the article metadata box rendered beside the intro.",children:e.jsx("div",{className:"grid gap-3",children:e.jsx(W,{onClick:()=>{R(`:::forge-infobox
|
|
46
|
+
Title: ${d.title||"Article title"}
|
|
47
|
+
Summary: ${d.summary||"Short summary"}
|
|
48
|
+
Tags: ${d.tagsText||"tag-one, tag-two"}
|
|
49
|
+
Related: [[index|Home]]
|
|
50
|
+
:::
|
|
51
|
+
`),f(null)},children:"Insert infobox"})})}),e.jsx(mi,{open:x==="admonition",onOpenChange:D=>!D&&f(null),title:"Insert admonition",description:"Add a callout block inside the article.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("select",{className:vv,value:b,onChange:D=>m(D.target.value),children:[e.jsx("option",{value:"",children:"Select type"}),e.jsx("option",{value:"note",children:"Note"}),e.jsx("option",{value:"tip",children:"Tip"}),e.jsx("option",{value:"warning",children:"Warning"}),e.jsx("option",{value:"danger",children:"Danger"})]}),e.jsx(Ce,{value:h,onChange:D=>p(D.target.value),rows:4,placeholder:"Admonition text"}),e.jsx(W,{disabled:!b||!h.trim(),onClick:()=>{R(`:::${b}
|
|
52
|
+
${h.trim()}
|
|
53
|
+
:::
|
|
54
|
+
`),f(null)},children:"Insert admonition"})]})}),e.jsx(mi,{open:x==="related",onOpenChange:D=>!D&&f(null),title:"Insert related block",description:"Add an explicit related-pages block.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx(Ce,{value:h,onChange:D=>p(D.target.value),rows:5,placeholder:`[[page-one]]
|
|
55
|
+
[[page-two|Readable label]]`}),e.jsx(W,{disabled:!h.trim(),onClick:()=>{R(`:::forge-related
|
|
56
|
+
${h.trim()}
|
|
57
|
+
:::
|
|
58
|
+
`),f(null)},children:"Insert related block"})]})}),e.jsx(mi,{open:x==="media",onOpenChange:D=>!D&&f(null),title:"Insert media block",description:"Reference media or assets in a structured block.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx(Ce,{value:h,onChange:D=>p(D.target.value),rows:5,placeholder:`Image: /path/to/file.png
|
|
59
|
+
Caption: Inspiration frame`}),e.jsx(W,{disabled:!h.trim(),onClick:()=>{R(`:::forge-media
|
|
60
|
+
${h.trim()}
|
|
61
|
+
:::
|
|
62
|
+
`),f(null)},children:"Insert media block"})]})}),e.jsx(Lt,{open:w,onOpenChange:v,children:e.jsxs(Dt,{children:[e.jsx($t,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.72)] backdrop-blur-sm"}),e.jsxs(Ot,{className:"fixed left-1/2 top-[14vh] z-50 w-[min(28rem,calc(100vw-1.5rem))] -translate-x-1/2 rounded-[28px] border border-white/10 bg-[rgba(10,15,28,0.97)] p-4 shadow-[0_32px_90px_rgba(0,0,0,0.45)] sm:p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(Rt,{className:"font-display text-[1.2rem] tracking-[-0.04em] text-white",children:"Choose wiki space"}),e.jsx(Gt,{className:"mt-1 text-[13px] leading-6 text-white/56",children:"Save this page into a different wiki space."})]}),e.jsx(_t,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white","aria-label":"Close space picker",children:e.jsx(mt,{className:"size-4"})})})]}),e.jsx("div",{className:"mt-4 grid gap-2",children:(V=T.data)==null?void 0:V.settings.spaces.map(D=>{const X=D.id===u;return e.jsxs("button",{type:"button",className:X?"flex items-center justify-between gap-3 rounded-[22px] border border-[rgba(192,193,255,0.22)] bg-[rgba(192,193,255,0.12)] px-4 py-3 text-left text-white transition":"flex items-center justify-between gap-3 rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-3 text-left text-white/78 transition hover:bg-white/[0.06] hover:text-white",onClick:()=>{const he=new URLSearchParams(r);he.set("spaceId",D.id),l(he,{replace:!0}),v(!1)},children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[14px] font-semibold",children:D.label}),e.jsx("span",{className:"mt-1 block text-[12px] leading-5 text-white/52",children:D.description||`/${D.slug}`})]}),X?e.jsx(ji,{className:"size-4 shrink-0 text-[var(--primary)]"}):null]},D.id)})})]})]})})]})}function kv(){var x;const{t}=at(),s=We(),i=pe({queryKey:["forge-weekly-review"],queryFn:xp}),n=ge({mutationFn:gp,onSuccess:async()=>{await Promise.all([s.invalidateQueries({queryKey:["forge-weekly-review"]}),s.invalidateQueries({queryKey:["forge-xp-metrics"]}),s.invalidateQueries({queryKey:["forge-reward-ledger"]}),s.invalidateQueries({queryKey:["forge-snapshot"]}),s.invalidateQueries({queryKey:["activity-archive"]})])}}),a=(x=i.data)==null?void 0:x.review;if(i.isLoading)return e.jsx(It,{});if(i.isError)return e.jsx(Oe,{eyebrow:t("common.weeklyReview.heroEyebrow"),error:i.error,onRetry:()=>void i.refetch()});if(!a)return e.jsx(Oe,{eyebrow:t("common.weeklyReview.heroEyebrow"),error:new Error("Forge returned an empty weekly review payload."),onRetry:()=>void i.refetch()});const r=a.wins[0]??null,l=a.calibration.find(f=>f.mode==="recover")??a.calibration[0]??null,d=a.calibration.find(f=>f.mode==="accelerate")??a.calibration[0]??null,o=[{id:"week",label:"This week",title:`${a.momentumSummary.totalXp} XP with ${a.momentumSummary.focusHours} focus hours`,detail:`Peak window: ${a.momentumSummary.peakWindow}. Efficiency score is holding at ${a.momentumSummary.efficiencyScore}.`,badge:a.windowLabel},{id:"wins",label:"Wins",title:(r==null?void 0:r.title)??t("common.weeklyReview.noWin"),detail:(r==null?void 0:r.summary)??t("common.weeklyReview.noWinDetail"),badge:r?`+${r.rewardXp} xp`:`${a.wins.length} wins`},{id:"recovery",label:"Recovery",title:(l==null?void 0:l.title)??t("common.weeklyReview.noRecovery"),detail:(l==null?void 0:l.note)??t("common.weeklyReview.noRecoveryDetail"),badge:(l==null?void 0:l.mode)??"maintain"},{id:"next-intent",label:"Next intent",title:(d==null?void 0:d.title)??a.reward.title,detail:(d==null?void 0:d.note)??a.reward.summary,badge:`+${a.reward.rewardXp} xp`}];return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ke,{title:"Weekly Review",description:`${a.windowLabel}. ${t("common.weeklyReview.heroDescription")}`,badge:`${a.momentumSummary.totalXp} xp`}),e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.weeklyReview.sectionMomentum")}),e.jsx("div",{className:"mt-4 h-64",children:e.jsx(id,{width:"100%",height:"100%",children:e.jsxs(Sh,{data:a.chart,children:[e.jsx(ad,{dataKey:"label",tick:{fill:"rgba(255,255,255,0.42)",fontSize:11}}),e.jsx(nd,{hide:!0}),e.jsx(Ch,{dataKey:"xp",fill:"#c0c1ff",radius:[8,8,0,0]})]})})}),e.jsxs("div",{className:"mt-4 grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/40",children:"XP"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:a.momentumSummary.totalXp})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Focus hours"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:a.momentumSummary.focusHours})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Peak window"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:a.momentumSummary.peakWindow})]})]})]}),e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.weeklyReview.sectionGoals")}),e.jsx("div",{className:"mt-4 grid gap-3",children:a.calibration.map(f=>e.jsxs("div",{className:"overflow-hidden rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0 flex-1 font-medium text-white",children:f.title}),e.jsx(O,{className:"max-w-[9rem] shrink-0 self-start",children:f.mode})]}),e.jsx("div",{className:"mt-3 text-sm text-white/58",children:f.note})]},f.id))})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(se,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.weeklyReview.sectionWins")}),e.jsx("div",{className:"mt-4 grid gap-3",children:a.wins.map(f=>e.jsxs("div",{className:"overflow-hidden rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0 flex-1 font-medium text-white",children:f.title}),e.jsxs(O,{className:"max-w-[8rem] shrink-0 self-start text-emerald-300",children:["+",f.rewardXp," xp"]})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:f.summary})]},f.id))})]}),e.jsxs(se,{children:[e.jsx("h2",{className:"font-display text-3xl text-white",children:a.reward.title}),e.jsx("p",{className:"mt-3 text-sm leading-7 text-white/60",children:a.reward.summary}),e.jsxs("div",{className:"mt-4 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/40",children:t("common.weeklyReview.completionBonus")}),e.jsxs("div",{className:"mt-2 text-3xl text-[var(--primary)]",children:["+",a.reward.rewardXp," XP"]})]}),e.jsx(W,{className:"mt-4 w-full",disabled:a.completion.finalized,pending:n.isPending,pendingLabel:t("common.weeklyReview.finalizePending"),onClick:async()=>{await n.mutateAsync()},children:a.completion.finalized?t("common.weeklyReview.finalized"):t("common.weeklyReview.finalize")}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:a.completion.finalized?`${t("common.weeklyReview.finalizedDetail")} ${a.completion.finalizedBy?`By ${a.completion.finalizedBy}. `:""}${a.completion.finalizedAt?new Date(a.completion.finalizedAt).toLocaleString():""}`.trim():a.reward.summary})]})]})]}),e.jsx(pc,{eyebrow:t("common.weeklyReview.summaryEyebrow"),title:t("common.weeklyReview.summaryTitle"),description:t("common.weeklyReview.summaryDescription"),items:o})]})}function Sv(){const t=ki();return c.useEffect(()=>{const s=`${t.pathname}${t.search}${t.hash}`,i=hu({scope:"frontend_runtime",route:s}),n=r=>{i({level:"error",eventKey:"window_error",message:r.message||"Unhandled browser error",functionName:"window.onerror",details:{fileName:r.filename||null,line:r.lineno||null,column:r.colno||null,error:r.error??null}})},a=r=>{i({level:"error",eventKey:"unhandled_rejection",message:"Unhandled promise rejection",functionName:"window.onunhandledrejection",details:{reason:r.reason??null}})};return window.addEventListener("error",n),window.addEventListener("unhandledrejection",a),()=>{window.removeEventListener("error",n),window.removeEventListener("unhandledrejection",a)}},[t.hash,t.pathname,t.search]),c.useEffect(()=>{const s=`${t.pathname}${t.search}${t.hash}`;Ma({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 Cv(){return e.jsxs(e.Fragment,{children:[e.jsx(Sv,{}),e.jsxs(uh,{children:[e.jsxs(De,{element:e.jsx(Qx,{}),children:[e.jsx(De,{index:!0,element:e.jsx(tn,{to:"/overview",replace:!0})}),e.jsx(De,{path:"overview",element:e.jsx(db,{})}),e.jsx(De,{path:"goals",element:e.jsx(bg,{})}),e.jsx(De,{path:"habits",element:e.jsx(Mg,{})}),e.jsx(De,{path:"goals/:goalId",element:e.jsx(xg,{})}),e.jsx(De,{path:"projects",element:e.jsx(yb,{})}),e.jsx(De,{path:"projects/:projectId",element:e.jsx(gb,{})}),e.jsx(De,{path:"strategies",element:e.jsx(Fb,{})}),e.jsx(De,{path:"strategies/:strategyId",element:e.jsx(Ub,{})}),e.jsx(De,{path:"preferences",element:e.jsx(Vb,{})}),e.jsx(De,{path:"campaigns",element:e.jsx(tn,{to:"/projects",replace:!0})}),e.jsx(De,{path:"calendar",element:e.jsx(lg,{})}),e.jsx(De,{path:"sleep",element:e.jsx(_w,{})}),e.jsx(De,{path:"sports",element:e.jsx(zw,{})}),e.jsx(De,{path:"psyche",element:e.jsx(cf,{})}),e.jsx(De,{path:"psyche/values",element:e.jsx(Yf,{})}),e.jsx(De,{path:"psyche/patterns",element:e.jsx(Ff,{})}),e.jsx(De,{path:"psyche/behaviors",element:e.jsx(Nf,{})}),e.jsx(De,{path:"psyche/reports",element:e.jsx(Gf,{})}),e.jsx(De,{path:"psyche/reports/:reportId",element:e.jsx(Wf,{})}),e.jsx(De,{path:"psyche/goal-map",element:e.jsx(kf,{})}),e.jsx(De,{path:"psyche/schemas-beliefs",element:e.jsx(Xf,{})}),e.jsx(De,{path:"psyche/modes",element:e.jsx(Af,{})}),e.jsx(De,{path:"psyche/modes/guide",element:e.jsx(Tf,{})}),e.jsx(De,{path:"kanban",element:e.jsx(Vg,{})}),e.jsx(De,{path:"notes",element:e.jsx(rb,{})}),e.jsx(De,{path:"wiki",element:e.jsx($o,{})}),e.jsx(De,{path:"wiki/ingest-history",element:e.jsx(xv,{})}),e.jsx(De,{path:"wiki/page/:slug",element:e.jsx($o,{})}),e.jsx(De,{path:"wiki/new",element:e.jsx(_o,{})}),e.jsx(De,{path:"wiki/edit/:pageId",element:e.jsx(_o,{})}),e.jsx(De,{path:"today",element:e.jsx(Xw,{})}),e.jsx(De,{path:"activity",element:e.jsx(Hx,{})}),e.jsx(De,{path:"insights",element:e.jsx(Qg,{})}),e.jsx(De,{path:"review/weekly",element:e.jsx(kv,{})}),e.jsx(De,{path:"settings",element:e.jsx(Vf,{})}),e.jsx(De,{path:"settings/users",element:e.jsx(Fw,{})}),e.jsx(De,{path:"settings/calendar",element:e.jsx(pw,{})}),e.jsx(De,{path:"settings/mobile",element:e.jsx(bw,{})}),e.jsx(De,{path:"settings/agents",element:e.jsx(iw,{})}),e.jsx(De,{path:"settings/rewards",element:e.jsx(Iw,{})}),e.jsx(De,{path:"settings/wiki",element:e.jsx(Tb,{})}),e.jsx(De,{path:"settings/logs",element:e.jsx(Sw,{})}),e.jsx(De,{path:"settings/bin",element:e.jsx(rw,{})}),e.jsx(De,{path:"tasks/:taskId",element:e.jsx(qw,{})})]}),e.jsx(De,{path:"*",element:e.jsx(tn,{to:"/overview",replace:!0})})]})]})}const Iv=new ph({defaultOptions:{queries:{staleTime:2e4,refetchOnWindowFocus:!1}}});xh.createRoot(document.getElementById("root")).render(e.jsx(gh.StrictMode,{children:e.jsx(bh,{client:Iv,children:e.jsx(fh,{basename:ou("/forge/"),children:e.jsx(Cv,{})})})}));
|
|
63
|
+
//# sourceMappingURL=index-B4A6TooJ.js.map
|