forge-openclaw-plugin 0.2.15 → 0.2.19

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.
Files changed (67) hide show
  1. package/README.md +39 -4
  2. package/dist/assets/{board-C_m78kvK.js → board-8L3uX7_O.js} +2 -2
  3. package/dist/assets/{board-C_m78kvK.js.map → board-8L3uX7_O.js.map} +1 -1
  4. package/dist/assets/index-Cj1IBH_w.js +36 -0
  5. package/dist/assets/index-Cj1IBH_w.js.map +1 -0
  6. package/dist/assets/index-DQT6EbuS.css +1 -0
  7. package/dist/assets/{motion-CpZvZumD.js → motion-1GAqqi8M.js} +2 -2
  8. package/dist/assets/{motion-CpZvZumD.js.map → motion-1GAqqi8M.js.map} +1 -1
  9. package/dist/assets/{table-DtyXTw03.js → table-DBGlgRjk.js} +2 -2
  10. package/dist/assets/{table-DtyXTw03.js.map → table-DBGlgRjk.js.map} +1 -1
  11. package/dist/assets/{ui-BXbpiKyS.js → ui-iTluWjC4.js} +2 -2
  12. package/dist/assets/{ui-BXbpiKyS.js.map → ui-iTluWjC4.js.map} +1 -1
  13. package/dist/assets/{vendor-QBH6qVEe.js → vendor-BvM2F9Dp.js} +151 -81
  14. package/dist/assets/vendor-BvM2F9Dp.js.map +1 -0
  15. package/dist/assets/{viz-w-IMeueL.js → viz-CNeunkfu.js} +2 -2
  16. package/dist/assets/{viz-w-IMeueL.js.map → viz-CNeunkfu.js.map} +1 -1
  17. package/dist/index.html +8 -8
  18. package/dist/openclaw/local-runtime.js +142 -9
  19. package/dist/openclaw/parity.js +1 -0
  20. package/dist/openclaw/plugin-entry-shared.js +7 -1
  21. package/dist/openclaw/routes.js +7 -0
  22. package/dist/openclaw/tools.js +198 -16
  23. package/dist/server/app.js +2615 -251
  24. package/dist/server/managers/platform/secrets-manager.js +44 -1
  25. package/dist/server/managers/runtime.js +3 -1
  26. package/dist/server/openapi.js +2212 -170
  27. package/dist/server/repositories/calendar.js +1101 -0
  28. package/dist/server/repositories/deleted-entities.js +10 -2
  29. package/dist/server/repositories/habits.js +358 -0
  30. package/dist/server/repositories/notes.js +161 -28
  31. package/dist/server/repositories/projects.js +45 -13
  32. package/dist/server/repositories/rewards.js +176 -6
  33. package/dist/server/repositories/settings.js +47 -5
  34. package/dist/server/repositories/task-runs.js +46 -10
  35. package/dist/server/repositories/tasks.js +25 -9
  36. package/dist/server/repositories/weekly-reviews.js +109 -0
  37. package/dist/server/repositories/work-adjustments.js +105 -0
  38. package/dist/server/services/calendar-runtime.js +1301 -0
  39. package/dist/server/services/context.js +16 -6
  40. package/dist/server/services/dashboard.js +6 -3
  41. package/dist/server/services/entity-crud.js +116 -3
  42. package/dist/server/services/gamification.js +66 -18
  43. package/dist/server/services/insights.js +2 -1
  44. package/dist/server/services/projects.js +32 -8
  45. package/dist/server/services/reviews.js +17 -2
  46. package/dist/server/services/work-time.js +27 -0
  47. package/dist/server/types.js +1069 -45
  48. package/openclaw.plugin.json +1 -1
  49. package/package.json +1 -1
  50. package/server/migrations/003_habits.sql +30 -0
  51. package/server/migrations/004_habit_links.sql +8 -0
  52. package/server/migrations/005_habit_psyche_links.sql +24 -0
  53. package/server/migrations/006_work_adjustments.sql +14 -0
  54. package/server/migrations/007_weekly_review_closures.sql +17 -0
  55. package/server/migrations/008_calendar_execution.sql +147 -0
  56. package/server/migrations/009_true_calendar_events.sql +195 -0
  57. package/server/migrations/010_calendar_selection_state.sql +6 -0
  58. package/server/migrations/011_calendar_timezone_backfill.sql +11 -0
  59. package/server/migrations/012_work_block_ranges.sql +7 -0
  60. package/server/migrations/013_microsoft_local_auth_settings.sql +8 -0
  61. package/server/migrations/014_note_tags_and_ephemeral.sql +8 -0
  62. package/skills/forge-openclaw/SKILL.md +130 -10
  63. package/skills/forge-openclaw/cron_jobs.md +395 -0
  64. package/dist/assets/index-BWtLtXwb.js +0 -36
  65. package/dist/assets/index-BWtLtXwb.js.map +0 -1
  66. package/dist/assets/index-Dp5GXY_z.css +0 -1
  67. package/dist/assets/vendor-QBH6qVEe.js.map +0 -1
@@ -0,0 +1,36 @@
1
+ var al=Object.defineProperty;var il=(t,s,a)=>s in t?al(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var ps=(t,s,a)=>il(t,typeof s!="symbol"?s+"":s,a);import{J as nl,g as rl,j as e,r as g,K as Fr,S as ol,Q as ll,L as dl,M as oi,N as cl,O as ml,T as hl,U as ul,V as ga,W as ht,X as Tt,Y as Or,Z as ds,$ as Cs,a0 as li,a1 as di,a2 as Rr,a3 as Ct,a4 as ci,a5 as Jt,a6 as pl,a7 as xl,a8 as yt,a9 as gl,aa as mi,ab as Ge,ac as Re,ad as re,ae as be,af as Nt,ag as Ea,ah as hi,ai as fl,aj as Gt,a as _r,ak as oa,al as bl,am as Et,an as vl,ao as yl,ap as ui,aq as ns,ar as Qe,as as oe,at as ue,au as wl,av as jl,aw as pi,ax as Is,ay as kl,az as Nl,aA as Cl,aB as Sl,aC as Tl,aD as Il,aE as Ne,aF as Pl,aG as Ml,aH as Wt,aI as ut,aJ as Ht,aK as Al,aL as $r,aM as Qt,aN as na,aO as Dl,aP as bt,aQ as Br,aR as El,aS as ra,aT as rs,aU as bn,aV as Ss,aW as fa,aX as zr,aY as qr,aZ as Kr,a_ as vn,a$ as Ll,b0 as Fl,b1 as Ol,b2 as Rl,b3 as _l,b4 as $l,b5 as Bl,b6 as zl,b7 as ql,b8 as Kl,b9 as la,ba as Ul,bb as Ql,bc as Ur,bd as Xl,be as Gl,bf as ai,bg as Ts,bh as Wl,bi as da,bj as Hl,bk as Qr,bl as Yl,bm as yn,bn as Jl,bo as Ee,bp as La,bq as Vl,br as Zl,H as ed,bs as td,bt as sd}from"./vendor-BvM2F9Dp.js";import{m as Ve,A as Yt,u as ad}from"./motion-1GAqqi8M.js";import{R as Ps,P as Ms,O as As,C as Ds,T as ba,D as va,a as ca}from"./ui-iTluWjC4.js";import{c as id,u as nd,f as wn,g as rd}from"./table-DBGlgRjk.js";import{R as Xr,A as od,X as Gr,Y as Wr,a as jn,B as ld,b as dd}from"./viz-CNeunkfu.js";import{u as cd,a as md,D as hd,S as kn,v as Nn,b as ud,p as pd,c as xd,P as gd,d as fd,e as bd,C as vd}from"./board-8L3uX7_O.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const n of i)if(n.type==="childList")for(const o of n.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function a(i){const n={};return i.integrity&&(n.integrity=i.integrity),i.referrerPolicy&&(n.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?n.credentials="include":i.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function r(i){if(i.ep)return;i.ep=!0;const n=a(i);fetch(i.href,n)}})();function te(...t){return nl(rl(t))}function xi(t){return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(t))}function gi({className:t,tone:s="primary"}){return e.jsx("span",{"aria-hidden":"true",className:te("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 yd(){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",calendar:"Calendar",kanban:"Kanban",today:"Today",notes:"Notes",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.",calendar:"Sync provider calendars, define work blocks, and plan real timeboxes.",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.",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."},commandPalette:{searchPlaceholder:"Jump to a route, goal, project, 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.",routePsyche:"Open Psyche.",routeGoals:"Open your life goals.",routeHabits:"Open your habits.",routeProjects:"Open your projects.",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."},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",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",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 wd=yd(),jd={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",calendar:"Calendrier",kanban:"Kanban",today:"Aujourd'hui",notes:"Notes",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.",calendar:"Synchronisez les calendriers, définissez les blocs de travail et planifiez des timeboxes réelles.",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é.",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."},commandPalette:{searchPlaceholder:"Aller à une vue, un objectif, un projet 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.",routePsyche:"Ouvrir Psyche.",routeGoals:"Ouvrir vos objectifs de vie.",routeHabits:"Ouvrir vos habitudes.",routeProjects:"Ouvrir vos projets.",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."},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",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",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."}}},Cn={en:wd,fr:jd};function Sn(t,s){const a=s.split(".");let r=t;for(const i of a){if(!r||typeof r=="string")return;r=r[i]}return typeof r=="string"?r:void 0}function kd(t,s){return s?t.replace(/\{(\w+)\}/g,(a,r)=>{const i=s[r];return i==null?"":String(i)}):t}function ma(t,s,a){const r=Sn(Cn[t],s),i=Sn(Cn.en,s);return kd(r??i??s,a)}const Nd={locale:"en",t:(t,s)=>ma("en",t,s),formatDate:t=>t?new Intl.DateTimeFormat("en",{month:"short",day:"numeric"}).format(new Date(`${t}T00:00:00.000Z`)):ma("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)},Hr=g.createContext(null);function Cd({children:t,locale:s}){const a=g.useMemo(()=>({locale:s,t:(r,i)=>ma(s,r,i),formatDate:r=>r?new Intl.DateTimeFormat(s,{month:"short",day:"numeric"}).format(new Date(`${r}T00:00:00.000Z`)):ma(s,"common.labels.noDate"),formatDateTime:r=>new Intl.DateTimeFormat(s,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(r)),formatNumber:r=>new Intl.NumberFormat(s).format(r)}),[s]);return e.jsx(Hr.Provider,{value:a,children:t})}function qe(){return g.useContext(Hr)??Nd}function Tn({active:t,label:s,className:a}){const{t:r}=qe();return e.jsxs(Ve.div,{initial:!1,animate:{opacity:t?1:.55,y:0,scale:t?1:.98},transition:{duration:.24,ease:"easeOut"},className:te("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",a),"aria-live":"polite",children:[e.jsx(gi,{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:r("common.labels.backgroundActivity")}),e.jsx("span",{className:"text-white/30",children:"•"}),e.jsx("span",{className:"truncate text-sm text-white/80",children:s})]})]})}function _({className:t,tone:s="default",size:a="md",wrap:r=!1,...i}){return e.jsx("span",{className:te("inline-flex max-w-full items-center rounded-full border border-white/8 bg-white/6 font-medium text-white/78",r?"whitespace-normal break-words [overflow-wrap:anywhere]":"overflow-hidden text-ellipsis whitespace-nowrap",a==="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),...i})}const Sd={goal:{kind:"goal",label:"Goal",icon:ga,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:ul,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:hl,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)]"},habit:{kind:"habit",label:"Habit",icon:ml,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:cl,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:oi,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:dl,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:ll,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:ol,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:Fr,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 Ft(t){return Sd[t]}function ws(t,s){const a=Ft(t);return s?`border ${a.buttonClassName}`:"border border-white/8 bg-white/[0.05] text-white/62 hover:bg-white/[0.08] hover:text-white"}function xe({kind:t,label:s,compact:a=!1,showIcon:r=!0,iconOnly:i=!1,gradient:n=!0,wrap:o=!1,className:d,...c}){const b=Ft(t),p=b.icon;return e.jsxs(_,{size:a?"sm":"md",wrap:o,className:te("max-w-full min-w-0 gap-1.5 border font-medium",n?b.badgeClassName:b.subtleBadgeClassName,a&&!i&&"px-2.5",i&&"px-2.5",d),...c,children:[r?e.jsx(p,{className:te("size-3.5 shrink-0",b.iconClassName)}):null,i?null:e.jsx("span",{className:te("min-w-0 max-w-full",o?"whitespace-normal break-words [overflow-wrap:anywhere]":"truncate"),children:s??b.label})]})}const Td={sm:"text-base",md:"text-lg",lg:"text-2xl",xl:"text-3xl"},Fa={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 Te({kind:t,label:s,variant:a="inline",size:r="md",showKind:i=!1,showIcon:n=!0,showBadge:o=!1,badgeLabel:d,badgeCompact:c=!0,badgeGradient:b=!1,lines:p=1,labelClassName:f,className:m,...x}){const v=Ft(t),w=v.icon;return a==="pill"?e.jsxs("span",{className:te("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)]",v.badgeClassName,m),...x,children:[n?e.jsx(w,{className:te("size-4 shrink-0",v.iconClassName)}):null,e.jsx("span",{className:te("min-w-0 max-w-full",Fa[p],f),children:s})]}):a==="heading"?e.jsxs("span",{className:te("inline-flex max-w-full min-w-0 items-center gap-3",m),...x,children:[o?e.jsx(xe,{kind:t,label:d??v.label,compact:c,gradient:b,className:"shrink-0"}):null,i&&!o?e.jsx(xe,{kind:t,label:d??v.label,compact:!0,gradient:!1,className:"shrink-0"}):null,e.jsx("span",{className:te("min-w-0 max-w-full font-display leading-tight",Td[r],Fa[p],v.nameClassName,f),children:s})]}):e.jsxs("span",{className:te("inline-flex max-w-full min-w-0 items-center gap-2",m),...x,children:[n?e.jsx(w,{className:te("size-4 shrink-0",v.iconClassName)}):null,o?e.jsx(xe,{kind:t,label:d??v.label,compact:c,gradient:b,className:"shrink-0"}):null,i?e.jsx("span",{className:te("text-sm font-medium",v.nameClassName),children:v.label}):null,e.jsx("span",{className:te("min-w-0 max-w-full",Fa[p],v.nameClassName,f),children:s})]})}function se({className:t,size:s,...a}){return e.jsx("input",{...a,className:te("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 Id({open:t,onOpenChange:s,snapshot:a}){const r=ht(),{t:i}=qe(),[n,o]=g.useState("");g.useEffect(()=>{t||o("")},[t]);const d=g.useMemo(()=>[...[{id:"route-overview",title:i("common.routeLabels.overview"),detail:i("common.commandPalette.routeOverview"),href:"/overview",category:i("common.commandPalette.categoryRoute")},{id:"route-today",title:i("common.routeLabels.today"),detail:i("common.commandPalette.routeToday"),href:"/today",category:i("common.commandPalette.categoryRoute")},{id:"route-kanban",title:i("common.routeLabels.kanban"),detail:i("common.commandPalette.routeKanban"),href:"/kanban",category:i("common.commandPalette.categoryRoute")},{id:"route-psyche",title:i("common.routeLabels.psyche"),detail:i("common.commandPalette.routePsyche"),href:"/psyche",category:i("common.commandPalette.categoryRoute")},{id:"route-notes",title:i("common.routeLabels.notes"),detail:i("common.commandPalette.routeNotes"),href:"/notes",category:i("common.commandPalette.categoryRoute")},{id:"route-goals",title:i("common.routeLabels.goals"),detail:i("common.commandPalette.routeGoals"),href:"/goals",category:i("common.commandPalette.categoryRoute")},{id:"route-habits",title:i("common.routeLabels.habits"),detail:i("common.commandPalette.routeHabits"),href:"/habits",category:i("common.commandPalette.categoryRoute")},{id:"route-projects",title:i("common.routeLabels.projects"),detail:i("common.commandPalette.routeProjects"),href:"/projects",category:i("common.commandPalette.categoryRoute")},{id:"route-calendar",title:i("common.routeLabels.calendar"),detail:i("common.commandPalette.routeCalendar"),href:"/calendar",category:i("common.commandPalette.categoryRoute")},{id:"route-review",title:i("common.routeLabels.review"),detail:i("common.commandPalette.routeReview"),href:"/review/weekly",category:i("common.commandPalette.categoryRoute")},{id:"route-settings",title:i("common.routeLabels.settings"),detail:i("common.commandPalette.routeSettings"),href:"/settings",category:i("common.commandPalette.categoryRoute")}],...a.dashboard.goals.slice(0,6).map(p=>({id:`goal-${p.id}`,title:p.title,detail:i("common.commandPalette.openLifeGoal"),href:`/goals/${p.id}`,category:i("common.commandPalette.categoryGoal"),kind:"goal"})),...a.dashboard.projects.slice(0,6).map(p=>({id:`project-${p.id}`,title:p.title,detail:p.goalTitle,href:`/projects/${p.id}`,category:i("common.commandPalette.categoryProject"),kind:"project"})),...a.overview.topTasks.slice(0,8).map(p=>({id:`task-${p.id}`,title:p.title,detail:i("common.commandPalette.openFocusTask"),href:`/tasks/${p.id}`,category:i("common.commandPalette.categoryTask"),kind:"task"}))],[a,i]),c=g.useMemo(()=>{const b=n.trim().toLowerCase();return b?d.filter(p=>`${p.title} ${p.detail} ${p.category}`.toLowerCase().includes(b)).slice(0,12):d.slice(0,12)},[d,n]);return e.jsx(Ps,{open:t,onOpenChange:s,children:e.jsxs(Ms,{children:[e.jsx(As,{className:"fixed inset-0 z-40 bg-[rgba(5,10,18,0.68)] backdrop-blur-xl"}),e.jsxs(Ds,{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(Tt,{className:"size-4 text-white/42"}),e.jsx(se,{autoFocus:!0,value:n,onChange:b=>o(b.target.value),placeholder:i("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:i("common.routeLabels.overview"),icon:Or},{label:i("common.routeLabels.today"),icon:ds},{label:i("common.routeLabels.kanban"),icon:Cs},{label:i("common.routeLabels.notes"),icon:li},{label:i("common.routeLabels.psyche"),icon:di},{label:i("common.routeLabels.goals"),icon:ga},{label:i("common.routeLabels.habits"),icon:oi},{label:i("common.routeLabels.projects"),icon:Rr},{label:i("common.routeLabels.calendar"),icon:Ct},{label:i("common.routeLabels.settings"),icon:ci}].map(b=>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(b.icon,{className:"size-3.5"}),b.label]},b.label))})]}),e.jsx("div",{className:"max-h-[60vh] overflow-y-auto p-3",children:e.jsxs("div",{className:"grid gap-2",children:[c.map(b=>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),r(b.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:b.category}),e.jsx("div",{className:"mt-1 type-title-md text-white",children:b.kind?e.jsx(Te,{kind:b.kind,label:b.title}):b.title}),e.jsx("div",{className:"mt-1 text-sm text-white/58",children:b.detail})]}),e.jsx(Jt,{className:"size-4 text-white/35"})]})},b.id)),c.length===0?e.jsx("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-5 text-sm text-white/56",children:i("common.commandPalette.noResults")}):null]})})]})]})})}function In({routeKey:t,tone:s="core",children:a}){const r=s==="psyche"?10:18,i=s==="psyche"?.26:.2;return e.jsx(Yt,{mode:"wait",initial:!1,children:e.jsx(Ve.div,{className:"w-full max-w-full min-w-0",initial:{opacity:0,y:r},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},transition:{duration:i,ease:"easeOut"},children:a},t)})}const Pd=pl("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 K({className:t,variant:s,size:a,pending:r=!1,pendingLabel:i,children:n,disabled:o,...d}){return e.jsxs("button",{className:te(Pd({variant:s,size:a}),t),disabled:o||r,"aria-busy":r,...d,children:[r?e.jsx(gi,{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:r&&i?i:n})]})}function ya({open:t,onOpenChange:s,eyebrow:a,title:r,description:i,children:n}){const{t:o}=qe();return e.jsx(Ps,{open:t,onOpenChange:s,children:e.jsxs(Ms,{children:[e.jsx(As,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.72)] backdrop-blur-xl"}),e.jsxs(Ds,{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:a}),e.jsx(ba,{className:"mt-2 type-display-section text-white",children:r}),i?e.jsx(va,{className:"mt-3 type-body text-white/64",children:i}):null]}),e.jsx(K,{variant:"secondary",onClick:()=>s(!1),children:o("common.actions.close")})]})}),e.jsx("div",{className:"min-h-0 flex-1 overflow-x-hidden overflow-y-auto p-4",children:n})]})]})})}function Ot({children:t,className:s}){return e.jsx("div",{className:te("text-sm leading-6 text-white/50",s),children:t})}function Oe({content:t,label:s="Explain this field",className:a}){const[r,i]=g.useState(!1),n=g.useRef(null),o=g.useId();return g.useEffect(()=>{if(!r)return;const d=c=>{var b;(b=n.current)!=null&&b.contains(c.target)||i(!1)};return document.addEventListener("pointerdown",d),()=>document.removeEventListener("pointerdown",d)},[r]),e.jsxs("span",{ref:n,className:te("relative inline-flex items-center",a),onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":r?o:void 0,"aria-expanded":r,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:()=>i(!0),onBlur:()=>i(!1),onClick:()=>i(d=>!d),children:e.jsx(xl,{className:"size-3.5"})}),e.jsx("span",{id:o,role:"tooltip",className:te("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",r?"translate-y-0 opacity-100":"translate-y-1 opacity-0"),children:t})]})}const Pn="(max-width: 1023px)";function Md(){const[t,s]=g.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(Pn).matches);return g.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const a=window.matchMedia(Pn),r=i=>{s(i.matches)};return s(a.matches),typeof a.addEventListener=="function"?(a.addEventListener("change",r),()=>a.removeEventListener("change",r)):(a.addListener(r),()=>a.removeListener(r))},[]),t}function B({label:t,description:s,labelHelp:a,hint:r,error:i,children:n}){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}),a?e.jsx(Oe,{content:a,label:`Explain ${t}`}):null]}),s?e.jsx("span",{className:"text-sm leading-6 text-white/54",children:s}):null,n,r?e.jsx(Ot,{children:r}):null,i?e.jsx("span",{className:"text-sm text-rose-300",children:i}):null]})}function Ke({options:t,value:s,onChange:a,columns:r=2}){return e.jsx("div",{className:te("grid gap-3",r===3?"md:grid-cols-3":"md:grid-cols-2"),children:t.map(i=>{const n=i.value===s;return e.jsxs("button",{type:"button",className:te("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 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:()=>a(i.value),children:[e.jsx("div",{className:"font-medium",children:i.label}),i.description?e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:i.description}):null]},i.value)})})}function He({open:t,onOpenChange:s,eyebrow:a,title:r,description:i,value:n,onChange:o,steps:d,onSubmit:c,submitLabel:b,pending:p=!1,pendingLabel:f,error:m,initialStepId:x}){const{t:v}=qe(),w=Md(),[h,P]=g.useState(0),T=d[h];g.useEffect(()=>{if(!t){P(0);return}if(x){const l=d.findIndex(N=>N.id===x);P(l>=0?l:0);return}P(0)},[x,t,d]);const O=l=>{o({...n,...l})},y=d.length,C=y===0?0:(h+1)/y*100;return e.jsx(Ps,{open:t,onOpenChange:s,children:e.jsxs(Ms,{children:[e.jsx(As,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.72)] backdrop-blur-xl"}),e.jsxs(Ds,{"data-testid":"question-flow-dialog",className:te("fixed z-50 flex flex-col overflow-y-auto 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)]",w?"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]"),children:[e.jsx(ba,{className:"sr-only",children:r}),e.jsx(va,{className:"sr-only",children:i}),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:a}),e.jsxs("span",{className:"whitespace-nowrap",children:["Step ",h+1," of ",y]})]}),e.jsx("div",{className:"mt-2 h-1.5 rounded-full bg-white/[0.06]",children:e.jsx(Ve.div,{className:"h-full rounded-full bg-[linear-gradient(90deg,rgba(192,193,255,0.9),rgba(125,211,252,0.82))]",animate:{width:`${C}%`},transition:{duration:.35,ease:"easeOut"}})})]}),e.jsx(ca,{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(yt,{className:"size-4"})})})]})}),e.jsx("div",{"data-testid":"question-flow-canvas",className:"flex-1 px-4 py-4 md:px-6 md:py-5",children:e.jsx(Yt,{mode:"wait",children:e.jsxs(Ve.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 flex-col gap-5",children:[e.jsxs("div",{className:"flex min-h-full flex-col justify-start",children:[T.eyebrow?e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-[var(--secondary)]",children:T.eyebrow}):null,e.jsx("h3",{className:"mt-1.5 font-display text-[clamp(1.45rem,2.15vw,2rem)] leading-tight text-white",children:T.title}),T.description?e.jsx("p",{className:"mt-1.5 max-w-3xl text-sm leading-6 text-white/58",children:T.description}):null,e.jsx("div",{className:"mt-5 grid flex-1 content-start gap-5",children:T.render(n,O)})]}),m?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:m}):null]},T.id)})}),e.jsx("div",{className:"sticky bottom-0 border-t border-white/8 bg-[rgba(12,17,30,0.92)] px-4 py-2.5 backdrop-blur-xl md:px-6",children:e.jsxs("div",{className:"flex 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 ",h+1,"/",y]})}),e.jsxs("div",{className:"flex shrink-0 flex-nowrap items-center gap-1.5 overflow-x-auto sm:gap-2",children:[h>0?e.jsxs(K,{type:"button",variant:"secondary",className:"min-w-max px-3 text-[12px]",onClick:()=>P(l=>Math.max(0,l-1)),children:[e.jsx(gl,{className:"size-4"}),"Back"]}):e.jsx(ca,{asChild:!0,children:e.jsx(K,{type:"button",variant:"secondary",className:"min-w-max px-3 text-[12px]",children:v("common.actions.cancel")})}),h<y-1?e.jsxs(K,{type:"button",className:"min-w-max px-3 text-[12px]",onClick:()=>P(l=>Math.min(y-1,l+1)),children:["Continue",e.jsx(Jt,{className:"size-4"})]}):e.jsxs(K,{type:"button",className:"min-w-max px-3 text-[12px]",pending:p,pendingLabel:f,onClick:()=>void c(),children:[e.jsx(mi,{className:"size-4"}),b]})]})]})})]})]})})}function ve({className:t,...s}){return e.jsx("textarea",{...s,className:te("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)]",t)})}const Ad={contentMarkdown:"",author:""};function Dd(){return{...Ad}}function fi({notes:t,onChange:s,entityLabel:a}){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 ",a," should start with context, evidence, or a clear handoff summary."]}):null,t.map((r,i)=>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 ",i+1]}),e.jsx(K,{type:"button",variant:"ghost",size:"sm",onClick:()=>s(t.filter((n,o)=>o!==i)),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(se,{value:r.author,placeholder:"Albert",onChange:n=>s(t.map((o,d)=>d===i?{...o,author:n.target.value}:o))})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Markdown note"}),e.jsx(ve,{className:"min-h-28",value:r.contentMarkdown,placeholder:"Capture why this was created now, what changed, or what the next person should know.",onChange:n=>s(t.map((o,d)=>d===i?{...o,contentMarkdown:n.target.value}:o))})]})]})]},i)),e.jsx("div",{children:e.jsx(K,{type:"button",variant:"secondary",onClick:()=>s([...t,Dd()]),children:"Add creation note"})})]})}const Ed=Ge(["en","fr"]),bi=Re({contentMarkdown:re().trim().min(1,"Note content is required"),author:re().trim()}),Yr=Re({title:re().trim().min(1,"Title is required"),description:re().trim(),horizon:Ge(["quarter","year","lifetime"]),status:Ge(["active","paused","completed"]),targetPoints:Nt.number().int().min(25).max(1e4),themeColor:re().trim().regex(/^#[0-9a-fA-F]{6}$/,"Theme color must be a valid hex value"),tagIds:be(re()),notes:be(bi)}),Jr=Re({goalId:re().trim().min(1,"Life goal is required"),title:re().trim().min(1,"Title is required"),description:re().trim(),status:Ge(["active","paused","completed"]),targetPoints:Nt.number().int().min(25).max(1e4),themeColor:re().trim().regex(/^#[0-9a-fA-F]{6}$/,"Theme color must be a valid hex value"),notes:be(bi)}),Ld=Re({profile:Re({operatorName:re().trim().min(1,"Name is required"),operatorEmail:re().trim().min(1,"Email is required"),operatorTitle:re().trim().min(1,"Title is required")}),notifications:Re({goalDriftAlerts:Ea(),dailyQuestReminders:Ea(),achievementCelebrations:Ea()}),execution:Re({maxActiveTasks:Nt.number().int().min(1).max(8),timeAccountingMode:Ge(["split","parallel","primary_only"])}),themePreference:Ge(["obsidian","solar","system"]),localePreference:Ed,calendarProviders:Re({microsoft:Re({clientId:re().trim(),tenantId:re().trim(),redirectUri:re().trim()}).optional()}).optional()}),Fd=Re({label:re().trim().min(1,"Label is required"),agentLabel:re().trim().min(1,"Agent name is required"),agentType:re().trim().min(1,"Agent type is required"),description:re().trim(),trustLevel:Ge(["standard","trusted","autonomous"]),autonomyMode:Ge(["approval_required","scoped_write","autonomous"]),approvalMode:Ge(["approval_by_default","high_impact_only","none"]),scopes:be(re().trim().min(1)).min(1)}),Od=Re({originType:Ge(["system","user","agent"]),originAgentId:re().trim(),originLabel:re().trim(),entityType:re().trim(),entityId:re().trim(),timeframeLabel:re().trim(),title:re().trim().min(1,"Title is required"),summary:re().trim().min(1,"Summary is required"),recommendation:re().trim().min(1,"Recommendation is required"),rationale:re().trim(),confidence:Nt.number().min(0).max(1),ctaLabel:re().trim().min(1,"CTA label is required")}),Vr=Re({title:re().trim().min(1,"Title is required"),description:re().trim(),owner:re().trim().min(1,"Owner is required"),goalId:re().trim(),projectId:re().trim().min(1,"Project is required"),priority:Ge(["low","medium","high","critical"]),status:Ge(["backlog","focus","in_progress","blocked","done"]),effort:Ge(["light","deep","marathon"]),energy:Ge(["low","steady","high"]),dueDate:re().trim(),points:Nt.number().int().min(5).max(500),tagIds:be(re()),notes:be(bi)}),Rd=Re({title:re().trim().min(1,"Title is required"),description:re().trim(),status:Ge(["active","paused","archived"]),polarity:Ge(["positive","negative"]),frequency:Ge(["daily","weekly"]),targetCount:Nt.number().int().min(1).max(14),weekDays:be(hi().int().min(0).max(6)).max(7),linkedGoalIds:be(re().trim().min(1)),linkedProjectIds:be(re().trim().min(1)),linkedTaskIds:be(re().trim().min(1)),linkedValueIds:be(re().trim().min(1)),linkedPatternIds:be(re().trim().min(1)),linkedBehaviorIds:be(re().trim().min(1)),linkedBeliefIds:be(re().trim().min(1)),linkedModeIds:be(re().trim().min(1)),linkedReportIds:be(re().trim().min(1)),linkedBehaviorId:re().trim(),rewardXp:Nt.number().int().min(1).max(100),penaltyXp:Nt.number().int().min(1).max(100)}).superRefine((t,s)=>{t.frequency==="weekly"&&t.weekDays.length===0&&s.addIssue({code:fl.custom,path:["weekDays"],message:"Pick at least one weekday"})}),_d=Re({entityType:Ge(["task","project"]),entityId:re().trim().min(1,"A target is required"),deltaMinutes:Nt.number().int().refine(t=>t!==0,"Minutes must not be zero"),note:re().trim()});Re({name:re().trim().min(1,"Name is required"),kind:Ge(["value","category","execution"]),color:re().trim().regex(/^#[0-9a-fA-F]{6}$/,"Color must be a valid hex value"),description:re().trim()});const Oa={title:"",description:"",horizon:"year",status:"active",targetPoints:400,themeColor:"#c8a46b",tagIds:[],notes:[]};function $d(t){return{title:t.title,description:t.description,horizon:t.horizon,status:t.status,targetPoints:t.targetPoints,themeColor:t.themeColor,tagIds:t.tagIds,notes:[]}}function vi({open:t,pending:s=!1,editingGoal:a,tags:r,onOpenChange:i,onSubmit:n}){const{t:o}=qe(),[d,c]=g.useState(Oa),[b,p]=g.useState(null),[f,m]=g.useState({}),x=w=>{m(Object.fromEntries(Object.entries(w).map(([h,P])=>[h,P==null?void 0:P[0]])))};g.useEffect(()=>{t&&(p(null),m({}),c(a?$d(a):Oa))},[a,t]);const v=[{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:(w,h)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:o("common.dialogs.goal.title"),error:f.title??null,children:e.jsx(se,{value:w.title,onChange:P=>h({title:P.target.value}),placeholder:"Build a durable body and calm energy"})}),e.jsx(B,{label:o("common.dialogs.goal.descriptionLabel"),children:e.jsx(ve,{value:w.description,onChange:P=>h({description:P.target.value}),placeholder:"Write the goal description in Markdown. This can stay short or grow into a long strategic page."})})]})},{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:(w,h)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:o("common.dialogs.goal.horizon"),children:e.jsx(Ke,{value:w.horizon,onChange:P=>h({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(B,{label:o("common.dialogs.goal.status"),children:e.jsx(Ke,{value:w.status,onChange:P=>h({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:(w,h)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:o("common.dialogs.goal.targetXp"),error:f.targetPoints??null,children:e.jsx(se,{type:"number",value:w.targetPoints,onChange:P=>h({targetPoints:Number(P.target.value)||0})})}),e.jsx(B,{label:o("common.dialogs.goal.themeColor"),error:f.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:w.themeColor,onChange:P=>h({themeColor:P.target.value})}),e.jsx(se,{className:"border-none bg-transparent px-0 py-0",value:w.themeColor,onChange:P=>h({themeColor:P.target.value})})]})}),e.jsx(B,{label:o("common.dialogs.goal.tags"),children:e.jsx("div",{className:"flex flex-wrap gap-2",children:r.map(P=>{const T=w.tagIds.includes(P.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${T?"bg-white/16 text-white":"bg-white/6 text-white/58 hover:bg-white/10 hover:text-white"}`,onClick:()=>h({tagIds:T?w.tagIds.filter(O=>O!==P.id):[...w.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:(w,h)=>e.jsx(B,{label:"Creation notes",children:e.jsx(fi,{notes:w.notes,onChange:P=>h({notes:P}),entityLabel:"goal"})})}];return e.jsx(He,{open:t,onOpenChange:i,eyebrow:o("common.dialogs.goal.eyebrow"),title:o(a?"common.dialogs.goal.editTitle":"common.dialogs.goal.createTitle"),description:o("common.dialogs.goal.description"),value:d,onChange:c,steps:v,pending:s,pendingLabel:o(a?"common.dialogs.goal.save":"common.dialogs.goal.create"),submitLabel:o(a?"common.dialogs.goal.save":"common.dialogs.goal.create"),error:b,onSubmit:async()=>{p(null);const w=Yr.safeParse(d);if(!w.success){x(w.error.flatten().fieldErrors),p("Some answers still need attention before this goal arc can be saved.");return}m({});try{await n(w.data,a==null?void 0:a.id),c(Oa),i(!1)}catch(h){p(h instanceof Error?h.message:o("common.dialogs.goal.submitError"))}}})}const Mn={goalId:"",title:"",description:"",status:"active",targetPoints:240,themeColor:"#c0c1ff",notes:[]};function Bd(t){return{goalId:t.goalId,title:t.title,description:t.description,status:t.status,targetPoints:t.targetPoints,themeColor:t.themeColor,notes:[]}}function yi({open:t,goals:s,editingProject:a,initialGoalId:r,onOpenChange:i,onSubmit:n}){const{t:o}=qe(),[d,c]=g.useState(Mn),[b,p]=g.useState(null),[f,m]=g.useState({}),x=w=>{m(Object.fromEntries(Object.entries(w).map(([h,P])=>[h,P==null?void 0:P[0]])))};g.useEffect(()=>{t&&(p(null),m({}),c(a?Bd(a):{...Mn,goalId:r??""}))},[a,r,t]);const v=[{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:(w,h)=>e.jsx(B,{label:o("common.dialogs.project.goal"),error:f.goalId??null,children:e.jsx("div",{className:"grid gap-3",children:s.map(P=>{const T=P.id===w.goalId;return e.jsxs("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${T?"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:()=>h({goalId:P.id}),children:[e.jsx(Te,{kind:"goal",label:P.title,className:"max-w-full"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:P.description||"No strategic note attached yet."})]},P.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:(w,h)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:o("common.dialogs.project.title"),error:f.title??null,children:e.jsx(se,{value:w.title,onChange:P=>h({title:P.target.value}),placeholder:"Launch the new creative practice system"})}),e.jsx(B,{label:o("common.dialogs.project.descriptionLabel"),children:e.jsx(ve,{value:w.description,onChange:P=>h({description:P.target.value}),placeholder:"Write the project description in Markdown. Use as much detail as the workstream needs."})})]})},{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:(w,h)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:o("common.dialogs.project.status"),children:e.jsx(Ke,{value:w.status,onChange:P=>h({status:P}),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(B,{label:o("common.dialogs.project.targetXp"),error:f.targetPoints??null,children:e.jsx(se,{type:"number",value:w.targetPoints,onChange:P=>h({targetPoints:Number(P.target.value)||0})})}),e.jsx(B,{label:o("common.dialogs.project.themeColor"),error:f.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:w.themeColor,onChange:P=>h({themeColor:P.target.value})}),e.jsx(se,{className:"border-none bg-transparent px-0 py-0",value:w.themeColor,onChange:P=>h({themeColor:P.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:(w,h)=>e.jsx(B,{label:"Creation notes",children:e.jsx(fi,{notes:w.notes,onChange:P=>h({notes:P}),entityLabel:"project"})})}];return e.jsx(He,{open:t,onOpenChange:i,eyebrow:o("common.dialogs.project.eyebrow"),title:o(a?"common.dialogs.project.editTitle":"common.dialogs.project.createTitle"),description:o("common.dialogs.project.description"),value:d,onChange:c,steps:v,submitLabel:o(a?"common.dialogs.project.save":"common.dialogs.project.create"),error:b,onSubmit:async()=>{p(null);const w=Jr.safeParse(d);if(!w.success){x(w.error.flatten().fieldErrors),p("A couple of answers still need attention before this project can be saved.");return}m({});try{await n(w.data,a==null?void 0:a.id),i(!1)}catch(h){p(h instanceof Error?h.message:o("common.dialogs.project.submitError"))}}})}const An={title:"",description:"",owner:"Albert",goalId:"",projectId:"",priority:"medium",status:"focus",effort:"deep",energy:"steady",dueDate:"",points:60,tagIds:[],notes:[]};function zd(t){return{title:t.title,description:t.description,owner:t.owner,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 wa({open:t,goals:s,projects:a,tags:r,editingTask:i,initialProjectId:n,onOpenChange:o,onSubmit:d}){const{t:c}=qe(),b=s??[],p=a??[],f=r??[],[m,x]=g.useState(An),[v,w]=g.useState(null),[h,P]=g.useState({}),T=C=>{P(Object.fromEntries(Object.entries(C).map(([l,N])=>[l,N==null?void 0:N[0]])))};g.useEffect(()=>{var C;t&&(w(null),P({}),x(i?zd(i):{...An,projectId:n??"",goalId:((C=p.find(l=>l.id===n))==null?void 0:C.goalId)??""}))},[i,n,t,p]);const O=g.useMemo(()=>p.find(C=>C.id===m.projectId)??null,[m.projectId,p]);g.useEffect(()=>{O&&m.goalId!==O.goalId&&x(C=>({...C,goalId:O.goalId}))},[m.goalId,O]);const y=[{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:(C,l)=>{var N;return e.jsxs(e.Fragment,{children:[e.jsx(B,{label:c("common.dialogs.task.project"),labelHelp:"Projects are the main home for tasks. Pick the stream of work this task belongs to.",error:h.projectId??null,children:e.jsx("div",{className:"grid gap-3",children:p.map(u=>{const M=u.id===C.projectId;return e.jsxs("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${M?"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:()=>l({projectId:u.id,goalId:u.goalId}),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(Te,{kind:"project",label:u.title,className:"min-w-0",showIcon:!1}),e.jsx(xe,{kind:"goal",label:u.goalTitle,compact:!0,gradient:!1})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:u.description})]},u.id)})})}),e.jsx(B,{label:c("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(se,{readOnly:!0,value:O?((N=b.find(u=>u.id===O.goalId))==null?void 0:N.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:(C,l)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:c("common.dialogs.task.title"),error:h.title??null,children:e.jsx(se,{value:C.title,onChange:N=>l({title:N.target.value}),placeholder:"Draft the first mode atlas sketch"})}),e.jsx(B,{label:c("common.dialogs.task.descriptionLabel"),children:e.jsx(ve,{value:C.description,onChange:N=>l({description:N.target.value}),placeholder:"Write the task description in Markdown. Keep it short or turn it into a full acceptance doc."})}),e.jsx(B,{label:c("common.dialogs.task.owner"),labelHelp:"The owner is the person or role expected to carry this task.",error:h.owner??null,children:e.jsx(se,{value:C.owner,onChange:N=>l({owner:N.target.value}),placeholder:"Albert"})})]})},{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:(C,l)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:c("common.dialogs.task.priority"),labelHelp:"Priority controls how strongly Forge should surface this task in the board and daily views.",children:e.jsx(Ke,{value:C.priority,onChange:N=>l({priority:N}),options:[{value:"low",label:c("common.enums.priority.low")},{value:"medium",label:c("common.enums.priority.medium")},{value:"high",label:c("common.enums.priority.high")},{value:"critical",label:c("common.enums.priority.critical")}]})}),e.jsx(B,{label:c("common.dialogs.task.status"),labelHelp:"Status tells Forge whether the task is waiting, ready for focus, active, blocked, or done.",children:e.jsx(Ke,{value:C.status,onChange:N=>l({status:N}),options:[{value:"backlog",label:c("common.enums.taskStatus.backlog")},{value:"focus",label:c("common.enums.taskStatus.focus")},{value:"in_progress",label:c("common.enums.taskStatus.in_progress")},{value:"blocked",label:c("common.enums.taskStatus.blocked")}]})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(B,{label:c("common.dialogs.task.effort"),labelHelp:"Effort describes how much concentration and time this task usually needs.",children:e.jsx(Ke,{value:C.effort,onChange:N=>l({effort:N}),options:[{value:"light",label:c("common.enums.effort.light")},{value:"deep",label:c("common.enums.effort.deep")},{value:"marathon",label:c("common.enums.effort.marathon")}]})}),e.jsx(B,{label:c("common.dialogs.task.energy"),labelHelp:"Energy helps you match this task to a low-energy, steady, or high-energy moment.",children:e.jsx(Ke,{value:C.energy,onChange:N=>l({energy:N}),options:[{value:"low",label:c("common.enums.energy.low")},{value:"steady",label:c("common.enums.energy.steady")},{value:"high",label:c("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:(C,l)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(B,{label:c("common.dialogs.task.xp"),labelHelp:"XP is the reward weight for finishing this task. Higher XP should mean more meaningful work.",error:h.points??null,children:e.jsx(se,{type:"number",value:C.points,onChange:N=>l({points:Number(N.target.value)||0}),placeholder:"60"})}),e.jsx(B,{label:c("common.dialogs.task.dueDate"),labelHelp:"Only add a due date when timing really matters for this task.",children:e.jsx(se,{type:"date",value:C.dueDate,onChange:N=>l({dueDate:N.target.value})})})]}),e.jsx(B,{label:c("common.dialogs.task.tags"),children:e.jsx("div",{className:"flex flex-wrap gap-2",children:f.map(N=>{const u=C.tagIds.includes(N.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${u?"bg-white/16 text-white":"bg-white/6 text-white/58 hover:bg-white/10 hover:text-white"}`,onClick:()=>l({tagIds:u?C.tagIds.filter(M=>M!==N.id):[...C.tagIds,N.id]}),children:N.name},N.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:(C,l)=>e.jsx(B,{label:"Creation notes",children:e.jsx(fi,{notes:C.notes,onChange:N=>l({notes:N}),entityLabel:"task"})})}];return e.jsx(He,{open:t,onOpenChange:o,eyebrow:c("common.dialogs.task.eyebrow"),title:c(i?"common.dialogs.task.editTitle":"common.dialogs.task.createTitle"),description:c("common.dialogs.task.description"),value:m,onChange:x,steps:y,submitLabel:c(i?"common.dialogs.task.save":"common.dialogs.task.create"),error:v,onSubmit:async()=>{w(null);const C=Vr.safeParse(m);if(!C.success){T(C.error.flatten().fieldErrors),w("A few task details still need attention before this move can be saved.");return}P({});try{await d(C.data,i==null?void 0:i.id),o(!1)}catch(l){w(l instanceof Error?l.message:"Unable to save this task right now.")}}})}const Dn="(max-width: 1023px)";function qd(){const[t,s]=g.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(Dn).matches);return g.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const a=window.matchMedia(Dn),r=i=>{s(i.matches)};return s(a.matches),typeof a.addEventListener=="function"?(a.addEventListener("change",r),()=>a.removeEventListener("change",r)):(a.addListener(r),()=>a.removeListener(r))},[]),t}function En({kind:t,title:s,description:a,onClick:r}){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:r,children:[e.jsx(xe,{kind:t,label:s,compact:!0,gradient:!1,className:"max-w-full"}),e.jsx("div",{className:"mt-1 text-sm text-white/55",children:a})]})}function Kd({goals:t,projects:s,tags:a,onCreateGoal:r,onCreateProject:i,onCreateTask:n,className:o}){const{t:d}=qe(),c=ht(),b=t??[],p=s??[],f=a??[],[m,x]=g.useState(!1),[v,w]=g.useState(!1),[h,P]=g.useState(!1),[T,O]=g.useState(!1),[y,C]=g.useState(null),l=qd(),N=g.useRef(null),u=g.useRef(null);g.useEffect(()=>{if(!m||l)return;const A=()=>{var E;const S=(E=N.current)==null?void 0:E.getBoundingClientRect();S&&C({top:Math.max(24,S.top-18),right:Math.max(24,window.innerWidth-S.right)})};A();const I=S=>{var E,X;(E=N.current)!=null&&E.contains(S.target)||(X=u.current)!=null&&X.contains(S.target)||x(!1)},j=S=>{S.key==="Escape"&&x(!1)};return document.addEventListener("pointerdown",I),document.addEventListener("keydown",j),window.addEventListener("resize",A),window.addEventListener("scroll",A,!0),()=>{document.removeEventListener("pointerdown",I),document.removeEventListener("keydown",j),window.removeEventListener("resize",A),window.removeEventListener("scroll",A,!0)}},[l,m]);const M=[{id:"goal",kind:"goal",group:"Execution",title:d("common.navigation.newGoal"),description:d("common.navigation.newGoalDescription"),onSelect:()=>{x(!1),w(!0)}},{id:"project",kind:"project",group:"Execution",title:d("common.navigation.newProject"),description:d("common.navigation.newProjectDescription"),onSelect:()=>{x(!1),P(!0)}},{id:"task",kind:"task",group:"Execution",title:d("common.navigation.newTask"),description:d("common.navigation.newTaskDescription"),onSelect:()=>{x(!1),O(!0)}},{id:"habit",kind:"habit",group:"Execution",title:"Habit",description:"Track a recurring commitment or recurring slip with explicit XP logic.",onSelect:()=>{x(!1),c("/habits?create=1")}},{id:"value",kind:"value",group:"Psyche",title:"Value",description:"Place one value into the goal, project, and task constellation.",onSelect:()=>{x(!1),c("/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:()=>{x(!1),c("/psyche/patterns?create=1")}},{id:"behavior",kind:"behavior",group:"Psyche",title:"Behavior",description:"Describe the move first, then classify it and link it.",onSelect:()=>{x(!1),c("/psyche/behaviors?create=1")}},{id:"report",kind:"report",group:"Psyche",title:"Report",description:"Start a Spark-to-Pivot reflective chain.",onSelect:()=>{x(!1),c("/psyche/reports?create=1")}}];return e.jsxs(e.Fragment,{children:[e.jsx("div",{ref:N,className:o,style:l?{right:"max(1rem, calc(var(--forge-safe-area-right) + 1rem))",bottom:"var(--forge-mobile-create-bottom)"}:void 0,children:e.jsxs(K,{type:"button","data-testid":"create-floating-trigger","aria-expanded":m,"aria-haspopup":"dialog",onClick:()=>x(A=>l?!0:!A),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)] ${m?"bg-[linear-gradient(135deg,rgba(192,193,255,0.52),rgba(125,211,252,0.24))] text-white":""}`,children:[e.jsx(Gt,{className:`size-4 transition ${m?"text-white":"text-white/72"}`}),d("common.navigation.create")]})}),m&&!l&&typeof document<"u"&&y?_r.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:`${y.top}px`,right:`${y.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(A=>e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:A}),e.jsx("div",{className:"mt-2 grid gap-2",children:M.filter(I=>I.group===A).map(I=>e.jsx(En,{kind:I.kind,title:I.title,description:I.description,onClick:I.onSelect},I.id))})]},A))]}),document.body):null,e.jsx(Ps,{open:m&&l,onOpenChange:x,children:e.jsxs(Ms,{children:[e.jsx(As,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.72)] backdrop-blur-xl lg:hidden"}),e.jsxs(Ds,{"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:d("common.navigation.create")}),e.jsx(ba,{className:"mt-2 font-display text-2xl text-white",children:d("common.navigation.createTitle")}),e.jsx(va,{className:"mt-2 text-sm leading-6 text-white/60",children:d("common.navigation.createDescription")})]}),e.jsx(ca,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":d("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(yt,{className:"size-4"})})})]}),e.jsx("div",{className:"overflow-y-auto p-4 overscroll-contain",children:["Execution","Psyche"].map(A=>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:A}),M.filter(I=>I.group===A).map(I=>e.jsx(En,{kind:I.kind,title:I.title,description:I.description,onClick:I.onSelect},I.id))]},A))})]})]})}),e.jsx(vi,{open:v,editingGoal:null,tags:f,onOpenChange:w,onSubmit:async A=>{await r(A)}}),e.jsx(yi,{open:h,goals:b,editingProject:null,onOpenChange:P,onSubmit:async A=>{await i(A)}}),e.jsx(wa,{open:T,goals:b,projects:p,tags:f,editingTask:null,onOpenChange:O,onSubmit:async A=>{await n(A)}})]})}function Ud(t){return t===null?"20":String(Math.max(1,Math.round(t/60)))}function Qd({tasks:t,projects:s,activeRunCount:a,maxActiveTasks:r,timeAccountingMode:i,pending:n,errorMessage:o,initialTaskId:d,defaultProjectId:c,onCancel:b,onStartExisting:p,onCreateAndStart:f}){const[m,x]=g.useState("existing"),[v,w]=g.useState(""),[h,P]=g.useState(d??null),[T,O]=g.useState(""),[y,C]=g.useState(""),[l,N]=g.useState(c??""),[u,M]=g.useState("planned"),[A,I]=g.useState("20");g.useEffect(()=>{x(d?"existing":"new"),w(""),P(d??null),O(""),C(""),N(c??""),M("planned"),I("20")},[c,d]);const j=g.useMemo(()=>t.filter(D=>D.status!=="done").sort((D,F)=>D.time.hasCurrentRun!==F.time.hasCurrentRun?Number(F.time.hasCurrentRun)-Number(D.time.hasCurrentRun):D.status!==F.status?D.status.localeCompare(F.status):D.title.localeCompare(F.title)),[t]),S=g.useMemo(()=>{const D=v.trim().toLowerCase();return D?j.filter(F=>{const q=s.find(Y=>Y.id===F.projectId);return[F.title,F.description,(q==null?void 0:q.title)??""].some(Y=>Y.toLowerCase().includes(D))}):j},[s,j,v]),E=g.useMemo(()=>s.find(D=>D.id===l)??null,[l,s]),X=u==="planned"?Math.max(60,(Number.parseInt(A,10)||20)*60):null,G=m==="existing"?!!h:!!(T.trim()&&l),z=i==="split"?"Split time":i==="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(_,{className:"bg-white/[0.08] text-white/72",children:[a,"/",r," live"]}),e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:z})]})]}),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(D=>{const F=m===D.value;return e.jsxs("button",{type:"button",className:te("rounded-[18px] border px-4 py-4 text-left transition",F?"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:()=>x(D.value),children:[e.jsx("div",{className:"font-medium",children:D.label}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-inherit/80",children:D.detail})]},D.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(Tt,{className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-white/32"}),e.jsx(se,{value:v,onChange:D=>w(D.target.value),placeholder:"Search task title or project",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:S.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."}):S.slice(0,16).map(D=>{const F=h===D.id,q=s.find(Y=>Y.id===D.projectId);return e.jsx("button",{type:"button",className:te("rounded-[16px] border px-4 py-3 text-left transition",F?"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(D.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(Te,{kind:"task",label:D.title,className:"max-w-full"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[q?e.jsx(xe,{kind:"project",label:q.title,compact:!0,gradient:!1}):null,e.jsx(_,{className:"bg-white/[0.08] text-white/70",children:D.status.replaceAll("_"," ")}),D.time.activeRunCount>0?e.jsxs(_,{className:"bg-emerald-500/12 text-emerald-200",children:[D.time.activeRunCount," live"]}):null]})]}),e.jsxs("span",{className:"text-[12px] text-white/45",children:[D.points," xp"]})]})},D.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(se,{value:T,onChange:D=>O(D.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(ve,{value:y,onChange:D=>C(D.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:l,onChange:D=>N(D.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(D=>e.jsx("option",{value:D.id,children:D.title},D.id))]})]}),E?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:E.title})," 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(D=>{const F=u===D.value;return e.jsxs("button",{type:"button",className:te("rounded-[18px] border px-4 py-3 text-left transition",F?"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:()=>M(D.value),children:[e.jsx("div",{className:"font-medium",children:D.label}),e.jsx("div",{className:"mt-1.5 text-sm leading-6 text-inherit/80",children:D.detail})]},D.value)}),e.jsxs("label",{className:te("grid gap-2",u!=="planned"&&"opacity-50"),children:[e.jsx("span",{className:"type-label text-white/45",children:"Minutes"}),e.jsx(se,{type:"number",min:1,max:240,disabled:u!=="planned",value:A,onChange:D=>I(D.target.value)})]})]})]}),o?e.jsx("div",{className:"rounded-[18px] bg-rose-500/10 px-4 py-3 text-sm leading-6 text-rose-200",children:o}):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:u==="planned"?`${Ud(X)} min target`:"Unlimited timer"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(K,{variant:"secondary",size:"lg",onClick:b,children:"Cancel"}),e.jsxs(K,{size:"lg",pending:n,pendingLabel:"Starting",disabled:!G,onClick:async()=>{if(G){if(m==="existing"&&h){await p(h,{timerMode:u,plannedDurationSeconds:X});return}await f({title:T.trim(),description:y.trim(),projectId:l,timerMode:u,plannedDurationSeconds:X})}},children:[m==="existing"?e.jsx(oa,{className:"size-4"}):e.jsx(bl,{className:"size-4"}),"Start work",e.jsx(Et,{className:"size-4"})]})]})]})]})}function Ln({open:t,onOpenChange:s,presentation:a="responsive",...r}){const i=e.jsx(Qd,{...r,onCancel:()=>s(!1)});return e.jsxs(e.Fragment,{children:[t&&a!=="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(K,{variant:"ghost",size:"sm",className:"px-3",onClick:()=>s(!1),children:[e.jsx(yt,{className:"size-4"}),"Close"]})}),i]})}):null,a!=="desktop_inline"?e.jsx("div",{className:a==="responsive"?"lg:hidden":"",children:e.jsx(ya,{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:i})}):null]})}const wi=g.createContext({expanded:!1,setExpanded:()=>{}});function Fn({children:t}){const[s,a]=g.useState(!1),r=g.useRef(0);return g.useEffect(()=>{if(!s)return;r.current=performance.now();let i=window.scrollY;const n=()=>{if(performance.now()-r.current<280){i=window.scrollY;return}window.scrollY-i>16&&a(!1),i=window.scrollY};return window.addEventListener("scroll",n,{passive:!0}),()=>window.removeEventListener("scroll",n)},[s]),e.jsx(wi.Provider,{value:{expanded:s,setExpanded:a},children:t})}function is(t){const s=Math.max(0,Math.floor(t)),a=Math.floor(s/3600),r=Math.floor(s%3600/60),i=s%60;return a>0?`${a}:${String(r).padStart(2,"0")}:${String(i).padStart(2,"0")}`:`${String(r).padStart(2,"0")}:${String(i).padStart(2,"0")}`}function Xd(t,s,a,r,i){const n=Math.max(1,t.length),o=Date.parse(a),d=Number.isFinite(o)?Math.max(0,Math.floor((i-o)/1e3)):0;return t.map(c=>{const b=s.find(w=>w.id===c.taskId),p=c.status==="active"?c.elapsedWallSeconds+d:c.elapsedWallSeconds,f=c.status!=="active"?0:r==="parallel"?d:r==="split"?d/n:c.isCurrent?d:0,m=c.creditedSeconds+f,x=c.timerMode==="planned"&&c.plannedDurationSeconds!==null?Math.max(0,c.plannedDurationSeconds-p):null,v=c.timerMode==="planned"&&c.plannedDurationSeconds!==null?Math.max(0,p-c.plannedDurationSeconds):0;return{run:c,title:(b==null?void 0:b.title)??c.taskTitle,wallSeconds:p,creditedSeconds:m,remainingSeconds:x,overtimeSeconds:v}}).sort((c,b)=>Number(b.run.isCurrent)-Number(c.run.isCurrent))}function Zr(t,s,a,r){const[i,n]=g.useState(()=>Date.now());return g.useEffect(()=>{if(t.length===0)return;const o=window.setInterval(()=>n(Date.now()),1e3);return()=>window.clearInterval(o)},[t.length]),g.useMemo(()=>Xd(t,s,a,r,i),[a,i,t,s,r])}function On({runs:t,tasks:s,generatedAt:a,timeAccountingMode:r,pending:i,onOpenStartWork:n,onPause:o,onFocus:d}){const{expanded:c,setExpanded:b}=g.useContext(wi),p=Zr(t,s,a,r),f=p.find(x=>x.run.isCurrent)??p[0]??null,m=f?p.filter(x=>x.run.id!==f.run.id):[];return f?e.jsxs("div",{className:te("flex min-h-[2.125rem] min-w-0 items-center rounded-full border border-white/8 bg-white/[0.04] transition-colors",c&&"border-[var(--primary)]/25 bg-[var(--primary)]/[0.06]"),children:[e.jsxs("button",{type:"button","aria-expanded":c,"aria-label":c?"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:()=>b(x=>!x),children:[e.jsx(oa,{className:"size-3.5 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"truncate text-[12px] font-medium text-white",children:f.title}),e.jsx("span",{className:"shrink-0 text-[11px] tabular-nums text-white/44",children:is(f.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:i,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:p.length}):null,e.jsx("button",{type:"button",title:"Stop",disabled:i,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 o(f.run.id),children:e.jsx(vl,{className:"size-2.5 fill-current"})}),e.jsx("button",{type:"button",title:"Start new work",disabled:i,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:()=>n(),children:e.jsx(Et,{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(oa,{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:n,children:"Start work"})]})}function Rn({runs:t,tasks:s,generatedAt:a,timeAccountingMode:r,pending:i,onOpenStartWork:n,onFocus:o,onPause:d,onComplete:c}){const{expanded:b}=g.useContext(wi),p=Zr(t,s,a,r),f=p.find(v=>v.run.isCurrent)??p[0]??null,m=f?p.filter(v=>v.run.id!==f.run.id):[],x=r==="split"&&p.length>1?`Split across ${p.length} active tasks`:r==="parallel"&&p.length>1?`Parallel time across ${p.length} active tasks`:r==="primary_only"&&p.length>1?"Only the current task is earning credited time":null;return f?e.jsx(Yt,{initial:!1,children:b?e.jsx(Ve.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(_,{tone:"signal",className:"text-white/82",children:"Current task"}),e.jsx(_,{tone:"meta",children:f.run.timerMode==="planned"?"Planned timer":"Unlimited timer"}),x?e.jsx(_,{tone:"meta",children:x}):null]}),e.jsx("div",{className:"mt-3 text-xl font-medium text-white md:text-2xl",children:f.title}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-4 text-sm text-white/62",children:[e.jsxs("span",{children:[is(f.creditedSeconds)," credited"]}),e.jsxs("span",{children:[is(f.wallSeconds)," wall time"]}),f.run.timerMode==="planned"?f.overtimeSeconds>0?e.jsxs("span",{className:"text-amber-200",children:["+",is(f.overtimeSeconds)," overtime"]}):e.jsxs("span",{children:[is(f.remainingSeconds??0)," remaining"]}):e.jsx("span",{children:"Unlimited session"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(K,{variant:"secondary",pending:i,pendingLabel:"Opening",onClick:n,children:[e.jsx(oa,{className:"size-4"}),"Start work"]}),e.jsxs(K,{variant:"secondary",pending:i,pendingLabel:"Pausing",onClick:()=>void d(f.run.id),children:[e.jsx(yl,{className:"size-4"}),"Pause"]}),e.jsxs(K,{pending:i,pendingLabel:"Completing",onClick:()=>void c(f.run.id),children:[e.jsx(ui,{className:"size-4"}),"Complete"]})]})]}),m.length>0?e.jsx("div",{className:"mt-4 grid gap-2 lg:grid-cols-2",children:m.map(v=>e.jsxs("button",{type:"button",className:te("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]",i&&"pointer-events-none opacity-70"),onClick:()=>void o(v.run.id),children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white/88",children:v.title}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-3 text-[12px] text-white/48",children:[e.jsxs("span",{children:[is(v.creditedSeconds)," credited"]}),e.jsx("span",{children:v.run.timerMode==="planned"?"planned":"unlimited"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-[12px] text-white/42",children:[e.jsx(ds,{className:"size-3.5"}),"Switch"]})]},v.run.id))}):null]})},"timer-rail-detail"):null}):null}function Z({className:t,...s}){return e.jsx("div",{className:te("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 ja extends Error{constructor(a){super(a.message);ps(this,"status");ps(this,"code");ps(this,"details");ps(this,"requestPath");this.name="ForgeApiError",this.status=a.status,this.code=a.code,this.details=a.details??[],this.requestPath=a.requestPath}}function Gd(t){return t instanceof ja?{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 pt({eyebrow:t,title:s,description:a}){const{t:r}=qe();return e.jsxs(Z,{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??r("common.labels.loading")}),e.jsx("div",{className:"type-display-section text-white",children:s??r("common.pageState.loadingTitle")}),e.jsx("p",{className:"type-body mx-auto max-w-xl text-white/60",children:a??r("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(gi,{tone:"subtle",className:"size-3.5"}),e.jsx("span",{className:"type-meta",children:r("common.labels.syncInProgress")})]})]})}function Le({error:t,onRetry:s,eyebrow:a}){const{t:r}=qe(),{title:i,description:n,code:o}=Gd(t);return e.jsxs(Z,{className:"mx-auto grid max-w-2xl gap-4",children:[e.jsx("div",{className:"type-label text-rose-200/72",children:a??r("common.labels.connectionState")}),e.jsx("div",{className:"type-display-section text-white",children:i}),e.jsx("p",{className:"type-body text-white/62",children:n}),e.jsx("div",{className:"type-meta text-white/40",children:r("common.labels.errorCode",{code:o})}),s?e.jsx("div",{className:"flex flex-wrap gap-3",children:e.jsxs(K,{type:"button",variant:"secondary",onClick:s,children:[e.jsx(ns,{className:"mr-2 size-4"}),r("common.actions.retry")]})}):null]})}function rt({eyebrow:t,title:s,description:a,action:r}){const{t:i}=qe();return e.jsxs(Z,{className:"mx-auto grid max-w-2xl gap-4 text-center",children:[e.jsx("div",{className:"type-label text-white/38",children:t??i("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:a}),r?e.jsx("div",{className:"flex justify-center",children:r}):null]})}function eo(t){const s=t.startsWith("/")?t:`/${t}`;return s.endsWith("/")?s:`${s}/`}function Wd(t){const s=eo(t);return s==="/"?"/":s.endsWith("/")?s.slice(0,-1):s}function Hd(){return new URL(eo("/forge/"),window.location.origin)}function to(t){if(t.startsWith("/api/"))return t;const s=t.startsWith("/")?t.slice(1):t;return new URL(s,Hd()).pathname}function Yd(){const t=Qe();g.useEffect(()=>{const s=new EventSource(to("/api/v1/events/stream")),a=()=>{Promise.all([t.invalidateQueries({queryKey:["forge-snapshot"]}),t.invalidateQueries({queryKey:["task-context"]})])};return s.addEventListener("snapshot",a),s.addEventListener("activity",a),s.onerror=()=>{s.close()},()=>{s.removeEventListener("snapshot",a),s.removeEventListener("activity",a),s.close()}},[t])}const Jd={allowWorkBlockKinds:[],blockWorkBlockKinds:[],allowCalendarIds:[],blockCalendarIds:[],allowEventTypes:[],blockEventTypes:[],allowEventKeywords:[],blockEventKeywords:[],allowAvailability:[],blockAvailability:[]};function Mt(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)??[],time:(t==null?void 0:t.time)??{totalTrackedSeconds:0,totalCreditedSeconds:0,liveTrackedSeconds:0,liveCreditedSeconds:0,manualAdjustedSeconds:0,activeRunCount:0,hasCurrentRun:!1,currentRunId:null}}}function Ra(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)??Jd,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",time:(t==null?void 0:t.time)??{totalTrackedSeconds:0,totalCreditedSeconds:0,liveTrackedSeconds:0,liveCreditedSeconds:0,manualAdjustedSeconds:0,activeRunCount:0,hasCurrentRun:!1,currentRunId:null}}}function Ks(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,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,checkIns:(t==null?void 0:t.checkIns)??[]}}function Vd(t){var n,o,d,c,b,p,f,m,x,v,w,h,P,T,O,y,C,l,N,u,M,A,I,j,S,E,X,G,z,D,F,q,Y,L,V,le,ce,he,je,W,$,k,R,Q,Ce,ie,_e,J,H,pe,Ie,Ye,fe,ye,$e,ae,ot,st,Je,lt,It,Pt,U,de,ge,Be,ze,ne,Pe,me,Ae,Me,we,it,De,jt,ke,qs,Oi,Ri,_i,$i,Bi,zi,qi,Ki,Ui,Qi,Xi,Gi,Wi,Hi,Yi,Ji,Vi,Zi,en,tn,sn,an,nn,rn,on,ln,dn,cn,mn,hn,un,pn,xn,gn,fn;const s=t,a=(s.projects??s.campaigns??[]).map(Ra),r=(((n=s.dashboard)==null?void 0:n.projects)??((o=s.dashboard)==null?void 0:o.campaigns)??a).map(Ra),i=(((d=s.overview)==null?void 0:d.projects)??((c=s.overview)==null?void 0:c.campaigns)??r).map(Ra);return{...t,meta:{apiVersion:"v1",transport:"rest+sse",generatedAt:((b=t.meta)==null?void 0:b.generatedAt)??new Date().toISOString(),backend:((p=t.meta)==null?void 0:p.backend)??"forge-node-runtime",mode:((f=t.meta)==null?void 0:f.mode)??"transitional-node"},metrics:{totalXp:((m=t.metrics)==null?void 0:m.totalXp)??0,level:((x=t.metrics)==null?void 0:x.level)??1,currentLevelXp:((v=t.metrics)==null?void 0:v.currentLevelXp)??0,nextLevelXp:((w=t.metrics)==null?void 0:w.nextLevelXp)??120,weeklyXp:((h=t.metrics)==null?void 0:h.weeklyXp)??0,streakDays:((P=t.metrics)==null?void 0:P.streakDays)??0,comboMultiplier:((T=t.metrics)==null?void 0:T.comboMultiplier)??1,momentumScore:((O=t.metrics)==null?void 0:O.momentumScore)??0,topGoalId:((y=t.metrics)==null?void 0:y.topGoalId)??null,topGoalTitle:((C=t.metrics)==null?void 0:C.topGoalTitle)??null},dashboard:{stats:{totalPoints:((N=(l=t.dashboard)==null?void 0:l.stats)==null?void 0:N.totalPoints)??0,completedThisWeek:((M=(u=t.dashboard)==null?void 0:u.stats)==null?void 0:M.completedThisWeek)??0,activeGoals:((I=(A=t.dashboard)==null?void 0:A.stats)==null?void 0:I.activeGoals)??0,alignmentScore:((S=(j=t.dashboard)==null?void 0:j.stats)==null?void 0:S.alignmentScore)??0,focusTasks:((X=(E=t.dashboard)==null?void 0:E.stats)==null?void 0:X.focusTasks)??0,overdueTasks:((z=(G=t.dashboard)==null?void 0:G.stats)==null?void 0:z.overdueTasks)??0,dueThisWeek:((F=(D=t.dashboard)==null?void 0:D.stats)==null?void 0:F.dueThisWeek)??0},goals:((q=t.dashboard)==null?void 0:q.goals)??[],projects:r,tasks:(((Y=t.dashboard)==null?void 0:Y.tasks)??[]).map(Mt),habits:(((L=t.dashboard)==null?void 0:L.habits)??t.habits??[]).map(Ks),tags:((V=t.dashboard)==null?void 0:V.tags)??[],suggestedTags:((le=t.dashboard)==null?void 0:le.suggestedTags)??[],owners:((ce=t.dashboard)==null?void 0:ce.owners)??[],executionBuckets:(((he=t.dashboard)==null?void 0:he.executionBuckets)??[]).map(us=>({...us,tasks:(us.tasks??[]).map(Mt)})),gamification:((je=t.dashboard)==null?void 0:je.gamification)??{totalXp:((W=t.metrics)==null?void 0:W.totalXp)??0,level:(($=t.metrics)==null?void 0:$.level)??1,currentLevelXp:((k=t.metrics)==null?void 0:k.currentLevelXp)??0,nextLevelXp:((R=t.metrics)==null?void 0:R.nextLevelXp)??120,weeklyXp:((Q=t.metrics)==null?void 0:Q.weeklyXp)??0,streakDays:((Ce=t.metrics)==null?void 0:Ce.streakDays)??0,comboMultiplier:((ie=t.metrics)==null?void 0:ie.comboMultiplier)??1,momentumScore:((_e=t.metrics)==null?void 0:_e.momentumScore)??0,topGoalId:((J=t.metrics)==null?void 0:J.topGoalId)??null,topGoalTitle:((H=t.metrics)==null?void 0:H.topGoalTitle)??null},achievements:((pe=t.dashboard)==null?void 0:pe.achievements)??[],milestoneRewards:((Ie=t.dashboard)==null?void 0:Ie.milestoneRewards)??[],recentActivity:((Ye=t.dashboard)==null?void 0:Ye.recentActivity)??[],notesSummaryByEntity:((fe=t.dashboard)==null?void 0:fe.notesSummaryByEntity)??{}},overview:{generatedAt:((ye=t.overview)==null?void 0:ye.generatedAt)??new Date().toISOString(),strategicHeader:{streakDays:((ae=($e=t.overview)==null?void 0:$e.strategicHeader)==null?void 0:ae.streakDays)??((ot=t.metrics)==null?void 0:ot.streakDays)??0,level:((Je=(st=t.overview)==null?void 0:st.strategicHeader)==null?void 0:Je.level)??((lt=t.metrics)==null?void 0:lt.level)??1,totalXp:((Pt=(It=t.overview)==null?void 0:It.strategicHeader)==null?void 0:Pt.totalXp)??((U=t.metrics)==null?void 0:U.totalXp)??0,currentLevelXp:((ge=(de=t.overview)==null?void 0:de.strategicHeader)==null?void 0:ge.currentLevelXp)??((Be=t.metrics)==null?void 0:Be.currentLevelXp)??0,nextLevelXp:((ne=(ze=t.overview)==null?void 0:ze.strategicHeader)==null?void 0:ne.nextLevelXp)??((Pe=t.metrics)==null?void 0:Pe.nextLevelXp)??120,momentumScore:((Ae=(me=t.overview)==null?void 0:me.strategicHeader)==null?void 0:Ae.momentumScore)??((Me=t.metrics)==null?void 0:Me.momentumScore)??0,focusTasks:((it=(we=t.overview)==null?void 0:we.strategicHeader)==null?void 0:it.focusTasks)??0,overdueTasks:((jt=(De=t.overview)==null?void 0:De.strategicHeader)==null?void 0:jt.overdueTasks)??0},projects:i,activeGoals:((ke=t.overview)==null?void 0:ke.activeGoals)??[],topTasks:(((qs=t.overview)==null?void 0:qs.topTasks)??[]).map(Mt),dueHabits:(((Oi=t.overview)==null?void 0:Oi.dueHabits)??((Ri=t.today)==null?void 0:Ri.dueHabits)??((_i=t.dashboard)==null?void 0:_i.habits)??[]).map(Ks),recentEvidence:(($i=t.overview)==null?void 0:$i.recentEvidence)??[],achievements:((Bi=t.overview)==null?void 0:Bi.achievements)??[],domainBalance:((zi=t.overview)==null?void 0:zi.domainBalance)??[],neglectedGoals:((qi=t.overview)==null?void 0:qi.neglectedGoals)??[]},today:{generatedAt:((Ki=t.today)==null?void 0:Ki.generatedAt)??new Date().toISOString(),directive:{task:(Qi=(Ui=t.today)==null?void 0:Ui.directive)!=null&&Qi.task?Mt(t.today.directive.task):null,goalTitle:((Gi=(Xi=t.today)==null?void 0:Xi.directive)==null?void 0:Gi.goalTitle)??null,rewardXp:((Hi=(Wi=t.today)==null?void 0:Wi.directive)==null?void 0:Hi.rewardXp)??0,sessionLabel:((Ji=(Yi=t.today)==null?void 0:Yi.directive)==null?void 0:Ji.sessionLabel)??"No active session"},timeline:(((Vi=t.today)==null?void 0:Vi.timeline)??[]).map(us=>({...us,tasks:(us.tasks??[]).map(Mt)})),dueHabits:(((Zi=t.today)==null?void 0:Zi.dueHabits)??((en=t.overview)==null?void 0:en.dueHabits)??((tn=t.dashboard)==null?void 0:tn.habits)??[]).map(Ks),dailyQuests:((sn=t.today)==null?void 0:sn.dailyQuests)??[],milestoneRewards:((an=t.today)==null?void 0:an.milestoneRewards)??[],recentHabitRewards:((nn=t.today)==null?void 0:nn.recentHabitRewards)??[],momentum:{streakDays:((on=(rn=t.today)==null?void 0:rn.momentum)==null?void 0:on.streakDays)??0,momentumScore:((dn=(ln=t.today)==null?void 0:ln.momentum)==null?void 0:dn.momentumScore)??0,recoveryHint:((mn=(cn=t.today)==null?void 0:cn.momentum)==null?void 0:mn.recoveryHint)??""}},risk:{generatedAt:((hn=t.risk)==null?void 0:hn.generatedAt)??new Date().toISOString(),overdueTasks:(((un=t.risk)==null?void 0:un.overdueTasks)??[]).map(Mt),blockedTasks:(((pn=t.risk)==null?void 0:pn.blockedTasks)??[]).map(Mt),neglectedGoals:((xn=t.risk)==null?void 0:xn.neglectedGoals)??[],summary:((gn=t.risk)==null?void 0:gn.summary)??""},goals:t.goals??[],projects:a,tags:t.tags??[],tasks:(t.tasks??[]).map(Mt),habits:(t.habits??((fn=t.dashboard)==null?void 0:fn.habits)??[]).map(Ks),activity:t.activity??[],activeTaskRuns:t.activeTaskRuns??[]}}async function Zd(t){const s=await t.text();if(!s)return null;try{return JSON.parse(s)}catch{return s}}async function ee(t,s){const a=new Headers(s==null?void 0:s.headers);a.set("x-forge-source","ui"),(s==null?void 0:s.body)!==void 0&&!a.has("content-type")&&a.set("content-type","application/json");const r=await fetch(to(t),{credentials:"same-origin",headers:a,...s}),i=await Zd(r);if(!r.ok){const n=typeof i=="object"&&i!==null?i:null,o=Array.isArray(n==null?void 0:n.details)?n.details:[];throw new ja({status:r.status,code:typeof(n==null?void 0:n.code)=="string"?n.code:typeof(n==null?void 0:n.error)=="string"?n.error:"request_failed",message:typeof(n==null?void 0:n.error)=="string"?n.error:typeof(n==null?void 0:n.message)=="string"?n.message:typeof i=="string"?i:`Request failed: ${r.status}`,requestPath:t,details:o})}return i}function ji(t){return t.map(s=>({contentMarkdown:s.contentMarkdown.trim(),author:s.author.trim()||null})).filter(s=>s.contentMarkdown.length>0)}function cs(){return ee("/api/v1/auth/operator-session")}function ec(){return ee("/api/v1/auth/operator-session",{method:"DELETE"})}function tc(){return ee("/api/v1/context").then(Vd)}function sc(){return ee("/api/v1/insights")}function ka(){return ee("/api/v1/psyche/overview")}function $t(){return ee("/api/v1/psyche/values")}function ms(t){return ee("/api/v1/psyche/values",{method:"POST",body:JSON.stringify(t)})}function ac(t,s){return ee(`/api/v1/psyche/values/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Es(){return ee("/api/v1/psyche/patterns")}function ki(t){return ee("/api/v1/psyche/patterns",{method:"POST",body:JSON.stringify(t)})}function ic(t,s){return ee(`/api/v1/psyche/patterns/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Bt(){return ee("/api/v1/psyche/behaviors")}function Na(t){return ee("/api/v1/psyche/behaviors",{method:"POST",body:JSON.stringify(t)})}function nc(t,s){return ee(`/api/v1/psyche/behaviors/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Ls(){return ee("/api/v1/psyche/schema-catalog")}function hs(){return ee("/api/v1/psyche/beliefs")}function Ni(t){return ee("/api/v1/psyche/beliefs",{method:"POST",body:JSON.stringify(t)})}function rc(t,s){return ee(`/api/v1/psyche/beliefs/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function zt(){return ee("/api/v1/psyche/modes")}function Fs(t){return ee("/api/v1/psyche/modes",{method:"POST",body:JSON.stringify(t)})}function oc(t,s){return ee(`/api/v1/psyche/modes/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function lc(){return ee("/api/v1/psyche/mode-guides")}function dc(t){return ee("/api/v1/psyche/mode-guides",{method:"POST",body:JSON.stringify(t)})}function so(){return ee("/api/v1/psyche/event-types")}function ao(){return ee("/api/v1/psyche/emotions")}function Ca(){return ee("/api/v1/psyche/reports")}function io(t){return ee("/api/v1/psyche/reports",{method:"POST",body:JSON.stringify(t)})}function cc(t){return ee(`/api/v1/psyche/reports/${t}`)}function mc(t,s){return ee(`/api/v1/psyche/reports/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function no(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 r of t.linkedTo??[])s.append("linkedTo",`${r.entityType}:${r.entityId}`);for(const r of t.tags??[])r.trim()&&s.append("tags",r.trim());for(const r of t.textTerms??[])r.trim()&&s.append("textTerms",r.trim());t.author&&s.set("author",t.author),t.query&&s.set("query",t.query),t.updatedFrom&&s.set("updatedFrom",t.updatedFrom),t.updatedTo&&s.set("updatedTo",t.updatedTo),t.limit&&s.set("limit",String(t.limit));const a=s.size>0?`?${s.toString()}`:"";return ee(`/api/v1/notes${a}`)}function Ci(t){return ee("/api/v1/notes",{method:"POST",body:JSON.stringify(t)})}function ro(t,s){return ee(`/api/v1/notes/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function oo(t,s="soft"){const a=s==="soft"?"":`?mode=${s}`;return ee(`/api/v1/notes/${t}${a}`,{method:"DELETE"})}function lo(t){return ee("/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 hc(t){return ee(`/api/v1/insights/${t}`,{method:"DELETE"})}function _n(t,s,a=""){return ee(`/api/v1/insights/${t}/feedback`,{method:"POST",body:JSON.stringify({feedbackType:s,note:a})})}function uc(){return ee("/api/v1/reviews/weekly")}function pc(){return ee("/api/v1/reviews/weekly/finalize",{method:"POST"})}function Sa(t={}){const s=new URLSearchParams;t.from&&s.set("from",t.from),t.to&&s.set("to",t.to);const a=s.size>0?`?${s.toString()}`:"";return ee(`/api/v1/calendar/overview${a}`)}function xc(){return ee("/api/v1/calendar/connections")}function _a(t){return ee("/api/v1/calendar/discovery",{method:"POST",body:JSON.stringify(t)})}function gc(t){return ee("/api/v1/calendar/oauth/microsoft/start",{method:"POST",body:JSON.stringify(t)})}function fc(t){return ee("/api/v1/calendar/oauth/microsoft/test-config",{method:"POST",body:JSON.stringify(t)})}function bc(t){return ee(`/api/v1/calendar/oauth/microsoft/session/${t}`)}function vc(t){return ee(`/api/v1/calendar/connections/${t}/discovery`)}function yc(t){return ee("/api/v1/calendar/connections",{method:"POST",body:JSON.stringify(t)})}function wc(t){return ee(`/api/v1/calendar/connections/${t}/sync`,{method:"POST"})}function jc(t,s){return ee(`/api/v1/calendar/connections/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function kc(t){return ee(`/api/v1/calendar/connections/${t}`,{method:"DELETE"})}function Nc(){return ee("/api/v1/calendar/calendars")}function Cc(t){return ee("/api/v1/calendar/work-block-templates",{method:"POST",body:JSON.stringify(t)})}function Sc(t,s){return ee(`/api/v1/calendar/work-block-templates/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Tc(t){return ee(`/api/v1/calendar/work-block-templates/${t}`,{method:"DELETE"})}function Ic(t){return ee("/api/v1/calendar/events",{method:"POST",body:JSON.stringify(t)})}function Pc(t,s){return ee(`/api/v1/calendar/events/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Mc(t){return ee(`/api/v1/calendar/events/${t}`,{method:"DELETE"})}function Ac(t){return ee("/api/v1/calendar/timeboxes",{method:"POST",body:JSON.stringify(t)})}function Dc(t,s){return ee(`/api/v1/calendar/timeboxes/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Ec(t){return ee("/api/v1/calendar/timeboxes/recommend",{method:"POST",body:JSON.stringify(t)})}function Lc(t={}){const s=new URLSearchParams;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 a=s.size>0?`?${s.toString()}`:"";return ee(`/api/v1/habits${a}`)}function Fc(t){return ee("/api/v1/habits",{method:"POST",body:JSON.stringify({...t,linkedBehaviorId:t.linkedBehaviorId||null})})}function Oc(t,s){return ee(`/api/v1/habits/${t}`,{method:"PATCH",body:JSON.stringify({...s,linkedBehaviorId:s.linkedBehaviorId===""?null:s.linkedBehaviorId})})}function Rc(t){return ee(`/api/v1/habits/${t}`,{method:"DELETE"})}function _c(t,s){return ee(`/api/v1/habits/${t}/check-ins`,{method:"POST",body:JSON.stringify(s)})}function $c(t){return ee(`/api/v1/projects/${t}/board`)}function Bc(){return ee("/api/v1/operator/context")}function Ta(){return ee("/api/v1/settings")}function zc(){return ee("/api/v1/settings/bin")}function qc(){return ee("/api/v1/agents/onboarding")}function Kc(){return ee("/api/v1/approval-requests")}function Uc(t,s=""){return ee(`/api/v1/approval-requests/${t}/approve`,{method:"POST",body:JSON.stringify({note:s})})}function Qc(t,s=""){return ee(`/api/v1/approval-requests/${t}/reject`,{method:"POST",body:JSON.stringify({note:s})})}function Xc(){return ee("/api/v1/rewards/rules")}function Gc(t,s){return ee(`/api/v1/rewards/rules/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Wc(t){return ee("/api/v1/rewards/bonus",{method:"POST",body:JSON.stringify(t)})}function Hc(t=50){return ee(`/api/v1/rewards/ledger?limit=${t}`)}function co(){return ee("/api/v1/metrics/xp")}function mo(t){return ee("/api/v1/settings",{method:"PATCH",body:JSON.stringify(t)})}function $n(t){return ee("/api/v1/entities/delete",{method:"POST",body:JSON.stringify(t)})}function Bn(t){return ee("/api/v1/entities/restore",{method:"POST",body:JSON.stringify(t)})}function Yc(t){return ee("/api/v1/settings/tokens",{method:"POST",body:JSON.stringify(t)})}function Jc(t){return ee(`/api/v1/settings/tokens/${t}/rotate`,{method:"POST"})}function Vc(t){return ee(`/api/v1/settings/tokens/${t}/revoke`,{method:"POST"})}function Zc(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"),ee(`/api/v1/activity?${s.toString()}`)}function ho(t){return ee("/api/v1/goals",{method:"POST",body:JSON.stringify({...t,notes:ji(t.notes)})})}function uo(t){return ee("/api/v1/projects",{method:"POST",body:JSON.stringify({...t,notes:ji(t.notes)})})}function po(t,s){return ee(`/api/v1/projects/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function em(t,s="soft"){return ee(`/api/v1/projects/${t}${s==="hard"?"?mode=hard":""}`,{method:"DELETE"})}function tm(t,s){return ee(`/api/v1/goals/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function ii(t){const s={...t,goalId:t.goalId||null,projectId:t.projectId||null,dueDate:t.dueDate||null,notes:ji(t.notes)};return ee("/api/v1/tasks",{method:"POST",body:JSON.stringify(s)})}function Os(t,s){return ee(`/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 Si(t){return ee(`/api/v1/tasks/${t}/uncomplete`,{method:"POST",body:JSON.stringify({})})}function sm(t){return ee(`/api/v1/tasks/${t}/context`)}function am(t){return ee("/api/v1/operator/log-work",{method:"POST",body:JSON.stringify(t)})}function xo(t){return ee("/api/v1/work-adjustments",{method:"POST",body:JSON.stringify(t)})}function go(t,s="Removed from the visible archive."){return ee(`/api/v1/activity/${t}/remove`,{method:"POST",body:JSON.stringify({reason:s})})}function im(t){return ee("/api/v1/session-events",{method:"POST",body:JSON.stringify(t)})}function nm(t,s){return ee(`/api/v1/tasks/${t}/runs`,{method:"POST",body:JSON.stringify(s)})}function rm(t,s){return ee(`/api/v1/task-runs/${t}/heartbeat`,{method:"POST",body:JSON.stringify(s)})}function om(t,s={}){return ee(`/api/v1/task-runs/${t}/focus`,{method:"POST",body:JSON.stringify(s)})}function fo(t,s){return ee(`/api/v1/task-runs/${t}/complete`,{method:"POST",body:JSON.stringify(s)})}function bo(t,s){return ee(`/api/v1/task-runs/${t}/release`,{method:"POST",body:JSON.stringify(s)})}const vo=g.createContext(null),tt=[{to:"/overview",labelKey:"common.routeLabels.overview",detailKey:"common.routeDetails.overview",icon:Or},{to:"/goals",labelKey:"common.routeLabels.goals",detailKey:"common.routeDetails.goals",icon:ga},{to:"/habits",labelKey:"common.routeLabels.habits",detailKey:"common.routeDetails.habits",icon:oi},{to:"/projects",labelKey:"common.routeLabels.projects",detailKey:"common.routeDetails.projects",icon:Rr},{to:"/calendar",labelKey:"common.routeLabels.calendar",detailKey:"common.routeDetails.calendar",icon:Ct},{to:"/kanban",labelKey:"common.routeLabels.kanban",detailKey:"common.routeDetails.kanban",icon:Cs},{to:"/today",labelKey:"common.routeLabels.today",detailKey:"common.routeDetails.today",icon:ds},{to:"/notes",labelKey:"common.routeLabels.notes",detailKey:"common.routeDetails.notes",icon:li},{to:"/psyche",labelKey:"common.routeLabels.psyche",detailKey:"common.routeDetails.psyche",icon:di},{to:"/activity",labelKey:"common.routeLabels.activity",detailKey:"common.routeDetails.activity",icon:Is},{to:"/insights",labelKey:"common.routeLabels.insights",detailKey:"common.routeDetails.insights",icon:kl},{to:"/review/weekly",labelKey:"common.routeLabels.review",detailKey:"common.routeDetails.review",icon:Nl},{to:"/settings",labelKey:"common.routeLabels.settings",detailKey:"common.routeDetails.settings",icon:ci}],lm=[tt[0],tt[6],tt[5],tt[8]],dm=[tt[1],tt[2],tt[3],tt[4],tt[7],tt[9],tt[10],tt[11],tt[12]];function yo(t){return new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:t>=1e3?1:0}).format(t)}function cm({to:t,labelKey:s,icon:a,compact:r=!1}){const{t:i}=qe(),n=i(s);return e.jsxs(Wt,{to:t,title:r?n:void 0,"aria-label":n,className:({isActive:o})=>`interactive-tap flex items-center rounded-[18px] text-sm transition ${o?"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"} ${r?"justify-center px-3 py-3.5":"gap-3 px-4 py-3"}`,children:[e.jsx(a,{className:"size-4 shrink-0"}),r?null:e.jsx("span",{children:n})]})}function mm(){const[t,s]=g.useState(!1),{t:a}=qe();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:[lm.map(r=>e.jsxs(Wt,{to:r.to,className:({isActive:i})=>`flex min-h-11 flex-col items-center justify-center gap-1 rounded-2xl px-2 py-2 text-[12px] ${i?"bg-white/[0.08] text-[var(--primary)]":"text-white/55"}`,children:[e.jsx(r.icon,{className:"size-4"}),e.jsx("span",{children:a(r.labelKey)})]},r.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(ci,{className:"size-4"}),e.jsx("span",{children:a("common.shell.more")})]})]})}),e.jsx(ya,{open:t,onOpenChange:s,eyebrow:a("common.shell.moreRoutesEyebrow"),title:a("common.shell.moreRoutesTitle"),description:a("common.shell.moreRoutesDescription"),children:e.jsx("div",{className:"grid gap-3",children:dm.map(r=>e.jsxs(Wt,{to:r.to,onClick:()=>s(!1),className:({isActive:i})=>`interactive-tap flex items-center justify-between rounded-[24px] px-4 py-4 ${i?"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(r.icon,{className:"size-4 text-[var(--primary)]"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-base font-medium",children:a(r.labelKey)}),e.jsx("span",{className:"mt-1 block text-sm text-white/54",children:a(r.detailKey)})]})]}),e.jsx(Is,{className:"size-4 text-white/35"})]},r.to))})})]})}function hm({onClick:t}){const{t:s}=qe();return e.jsxs(K,{variant:"secondary",size:"sm",className:"min-w-[8.25rem] px-3.5",onClick:t,children:[e.jsx(Tt,{className:"size-4"}),s("common.shell.command"),e.jsx(_,{size:"sm",tone:"meta",className:"ml-1 hidden bg-white/[0.06] text-white/52 xl:inline-flex",children:"⌘K"})]})}function um({children:t,settings:s,timerPending:a,startWorkOpen:r,startWorkPending:i,startWorkError:n,startWorkDefaults:o,onOpenStartWork:d,onCloseStartWork:c,onStartExistingTask:b,onCreateAndStartTask:p,onFocusRun:f,onPauseRun:m,onCompleteRun:x}){const v=pi(),w=Xe(),{t:h}=qe(),P=tt.find(G=>v.pathname.startsWith(G.to))??tt[0],[T,O]=g.useState(!1),[y,C]=g.useState(!1),[l,N]=g.useState(!1),u=v.pathname.startsWith("/psyche"),M=Cl(),A=Sl(),I=ad(),j=M+A,S=[{id:"streak",label:h("common.shell.momentum.streak"),compactValue:String(w.snapshot.metrics.streakDays),expandedValue:h(w.snapshot.metrics.streakDays===1?"common.shell.momentum.streakBadgeOne":"common.shell.momentum.streakBadgeOther",{count:w.snapshot.metrics.streakDays}),icon:Tl},{id:"xp",label:h("common.shell.momentum.xp"),compactValue:String(w.snapshot.metrics.totalXp),expandedValue:`${w.snapshot.metrics.totalXp} XP`,icon:Cs},{id:"momentum",label:h("common.shell.momentum.momentum"),compactValue:`${w.snapshot.metrics.momentumScore}%`,expandedValue:h("common.shell.momentum.liveMomentum",{count:w.snapshot.metrics.momentumScore}),icon:Il}],E=A>0?h(A===1?"common.shell.savingOne":"common.shell.savingOther",{count:A}):M>0?h(M===1?"common.shell.refreshingOne":"common.shell.refreshingOther",{count:M}):h("common.shell.settled"),X=g.useMemo(()=>v.pathname.startsWith("/tasks/")?[{to:"/kanban",label:h("common.shell.rail.taskBackToKanban")},{to:"/today",label:h("common.shell.rail.taskOpenToday")}]:v.pathname.startsWith("/projects/")?[{to:"/projects",label:h("common.shell.rail.projectAll")},{to:"/goals",label:h("common.shell.rail.projectGoals")}]:v.pathname.startsWith("/goals/")?[{to:"/goals",label:h("common.shell.rail.goalAll")},{to:"/projects",label:h("common.shell.rail.goalProjects")}]:v.pathname.startsWith("/psyche")?[{to:"/psyche",label:h("common.shell.rail.psycheHub")},{to:"/psyche/reports",label:h("common.shell.rail.psycheReports")}]:[{to:"/overview",label:h("common.shell.rail.overview")},{to:"/today",label:h("common.shell.rail.today")}],[v.pathname,h]);return g.useEffect(()=>{const G=z=>{(z.metaKey||z.ctrlKey)&&z.key.toLowerCase()==="k"&&(z.preventDefault(),O(D=>!D))};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[]),g.useEffect(()=>{try{window.localStorage.getItem("forge.desktop-nav-collapsed")==="true"&&N(!0)}catch{return}},[]),g.useEffect(()=>{try{window.localStorage.setItem("forge.desktop-nav-collapsed",String(l))}catch{return}},[l]),g.useEffect(()=>{const G=window.innerWidth>=1024?52:32,z=()=>{C(window.scrollY>G)};return z(),window.addEventListener("scroll",z,{passive:!0}),window.addEventListener("resize",z),()=>{window.removeEventListener("scroll",z),window.removeEventListener("resize",z)}},[]),e.jsxs("div",{className:`min-h-screen ${w.snapshot.meta.mode==="transitional-node"?"theme-forge-obsidian":""}`,children:[e.jsx(Id,{open:T,onOpenChange:O,snapshot:w.snapshot}),e.jsxs("div",{className:"hidden lg:grid lg:min-h-screen",style:{gridTemplateColumns:l?"5.75rem minmax(0,1fr)":"17.75rem minmax(0,1fr)"},children:[e.jsxs("aside",{className:te("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]",l?"px-3":"px-5"),children:[e.jsxs("div",{className:te("flex items-start",l?"flex-col items-center gap-3":"justify-between gap-3"),children:[e.jsxs(Ne,{to:"/overview",className:te("block min-w-0",l&&"text-center"),children:[e.jsx("div",{className:te("font-display text-[var(--primary)]",l?"text-2xl":"text-3xl"),children:h("common.shell.appMark")}),l?null:e.jsxs("div",{className:"type-meta mt-2 text-white/40",children:["Level ",w.snapshot.metrics.level]})]}),e.jsx(K,{type:"button",variant:"secondary",size:"sm",className:"mt-0.5 px-2.5",onClick:()=>N(G=>!G),"aria-label":h(l?"common.shell.expandSidebar":"common.shell.collapseSidebar"),title:h(l?"common.shell.expandSidebar":"common.shell.collapseSidebar"),children:l?e.jsx(Pl,{className:"size-4"}):e.jsx(Ml,{className:"size-4"})})]}),e.jsx("div",{className:te("grid gap-2",l?"mt-6":"mt-8"),children:tt.map(G=>e.jsx(cm,{to:G.to,labelKey:G.labelKey,icon:G.icon,compact:l},G.to))}),e.jsx("div",{className:te(l?"mt-4":"mt-6"),children:e.jsxs("div",{className:te("rounded-[24px] bg-white/[0.04]",l?"px-2 py-2.5":"p-4"),children:[l?null:e.jsx("div",{className:"type-label text-white/40",children:h("common.shell.momentum.title")}),e.jsx("div",{className:te("grid",l?"gap-1.5":"mt-3 gap-3"),children:S.map(G=>{const z=G.icon;return l?e.jsxs("div",{title:`${G.label}: ${G.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(z,{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:G.compactValue})]},G.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:G.label}),e.jsx("div",{className:"mt-1 text-lg font-semibold leading-tight text-white",children:G.expandedValue})]},G.id)})})]})})]}),e.jsxs("div",{className:"min-h-screen",children:[e.jsx(Fn,{children:e.jsxs(Ve.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:I?void 0:{paddingTop:y?6:10,paddingBottom:y?6:9},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(Ve.div,{className:"shrink-0 font-display text-white",animate:I?void 0:{fontSize:y?"1rem":"1.12rem",lineHeight:1},transition:{duration:.35,ease:"easeOut"},children:h(P.labelKey)}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(On,{runs:w.snapshot.activeTaskRuns,tasks:w.snapshot.tasks,generatedAt:w.snapshot.meta.generatedAt,timeAccountingMode:s.execution.timeAccountingMode,pending:a,onOpenStartWork:()=>d(),onPause:m,onFocus:f})})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-2",children:[e.jsx(Tn,{active:j>0,label:E}),e.jsx(hm,{onClick:()=>O(!0)}),e.jsxs(K,{variant:"secondary",size:"sm",className:"min-w-[7.25rem] px-3.5",onClick:()=>void w.refresh(),children:[e.jsx(ns,{className:"size-4"}),h("common.actions.refresh")]})]})]}),e.jsx(Rn,{runs:w.snapshot.activeTaskRuns,tasks:w.snapshot.tasks,generatedAt:w.snapshot.meta.generatedAt,timeAccountingMode:s.execution.timeAccountingMode,pending:a,onOpenStartWork:()=>d(),onFocus:f,onPause:m,onComplete:x}),e.jsx(Yt,{initial:!1,children:y?null:e.jsxs(Ve.div,{className:"mt-3 flex items-center justify-between gap-4 border-t border-white/6 pt-3",initial:I?void 0:{opacity:0,height:0,marginTop:0,paddingTop:0},animate:I?void 0:{opacity:1,height:"auto",marginTop:12,paddingTop:12},exit:I?void 0:{opacity:0,height:0,marginTop:0,paddingTop:0},transition:{duration:.28,ease:"easeOut"},children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:X.map(G=>e.jsx(Ne,{to:G.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:G.label},G.to))}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(_,{tone:"meta",children:h(w.snapshot.metrics.streakDays===1?"common.shell.momentum.streakBadgeOne":"common.shell.momentum.streakBadgeOther",{count:w.snapshot.metrics.streakDays})}),e.jsx(_,{tone:"meta",children:h("common.shell.momentum.weeklyXp",{count:w.snapshot.metrics.weeklyXp})}),e.jsx(_,{tone:u?"signal":"meta",children:u?h("common.shell.momentum.psycheMode"):h("common.shell.momentum.liveMomentum",{count:w.snapshot.metrics.momentumScore})})]})]},"desktop-shell-secondary-row")})]})}),e.jsx("div",{className:"px-6 pt-3",children:e.jsx(Ln,{open:r,onOpenChange:G=>{G||c()},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:i,errorMessage:n,initialTaskId:o.taskId??null,defaultProjectId:o.projectId??null,onStartExisting:b,onCreateAndStart:p})}),e.jsx("main",{className:"px-6 py-3",children:e.jsx(In,{routeKey:v.pathname,tone:u?"psyche":"core",children:t})})]})]}),e.jsxs("div",{className:"min-h-[100dvh] overflow-x-clip lg:hidden",children:[e.jsx(Fn,{children:e.jsxs(Ve.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:I?void 0:{paddingTop:y?6:9,paddingBottom:y?6:8},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:te("shrink-0 font-display text-white transition",y?"text-[0.95rem]":"text-base"),children:h(P.labelKey)}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(On,{runs:w.snapshot.activeTaskRuns,tasks:w.snapshot.tasks,generatedAt:w.snapshot.meta.generatedAt,timeAccountingMode:s.execution.timeAccountingMode,pending:a,onOpenStartWork:()=>d(),onPause:m,onFocus:f})})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsx(K,{variant:"secondary",size:"sm",className:"min-h-[2.125rem] px-2.5",onClick:()=>O(!0),children:e.jsx(Tt,{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(Cs,{className:"size-3.5 shrink-0"}),e.jsxs("span",{children:[yo(w.snapshot.metrics.totalXp)," XP"]})]})]})]}),e.jsx(Rn,{runs:w.snapshot.activeTaskRuns,tasks:w.snapshot.tasks,generatedAt:w.snapshot.meta.generatedAt,timeAccountingMode:s.execution.timeAccountingMode,pending:a,onOpenStartWork:()=>d(),onFocus:f,onPause:m,onComplete:x}),y?null:e.jsxs(e.Fragment,{children:[e.jsx(Yt,{initial:!1,children:e.jsx(Ve.div,{initial:I?void 0:{opacity:0,height:0},animate:I?void 0:{opacity:1,height:"auto"},exit:I?void 0:{opacity:0,height:0},transition:{duration:.28,ease:"easeOut"},className:"overflow-hidden",children:e.jsx("div",{className:"mt-2 text-[13px] leading-5 text-white/52",children:h(P.detailKey)})},"mobile-shell-copy")}),e.jsx("div",{className:"mt-2",children:e.jsx(Tn,{active:j>0,label:E})})]})]})}),e.jsx(Ln,{open:r,onOpenChange:G=>{G||c()},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:i,errorMessage:n,initialTaskId:o.taskId??null,defaultProjectId:o.projectId??null,onStartExisting:b,onCreateAndStart:p}),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(In,{routeKey:v.pathname,tone:u?"psyche":"core",children:t})}),e.jsx(mm,{})]}),e.jsx(Kd,{className:"fixed z-40 lg:bottom-6 lg:right-6",goals:w.snapshot.dashboard.goals,projects:w.snapshot.dashboard.projects,tags:w.snapshot.tags,onCreateGoal:w.createGoal,onCreateProject:w.createProject,onCreateTask:w.createTask})]})}function pm(){var j;Yd();const t=g.useRef(`forge_session_${Math.random().toString(36).slice(2,10)}`),s=g.useRef(null),a=g.useRef(null),r=Qe(),[i,n]=g.useState(!1),[o,d]=g.useState({}),[c,b]=g.useState(null),[p,f]=g.useState(null),m=oe({queryKey:["forge-shell-operator-session"],queryFn:cs}),x=oe({queryKey:["forge-snapshot"],queryFn:tc,enabled:m.isSuccess}),v=oe({queryKey:["forge-settings"],queryFn:Ta,enabled:m.isSuccess});g.useEffect(()=>{var X;const S=(X=x.data)==null?void 0:X.metrics.totalXp;if(typeof S!="number")return;if(a.current===null){a.current=S;return}const E=S-a.current;a.current=S,E!==0&&(f({deltaXp:E,totalXp:S}),s.current!==null&&window.clearTimeout(s.current),s.current=window.setTimeout(()=>{f(null),s.current=null},2600))},[(j=x.data)==null?void 0:j.metrics.totalXp]),g.useEffect(()=>()=>{s.current!==null&&window.clearTimeout(s.current)},[]),g.useEffect(()=>{if(!m.isSuccess)return;let S=!1,E=!1,X=!1;const G=()=>{S=!0},z=(q,Y)=>im({sessionId:t.current,eventType:q,metrics:Y}).catch(()=>{});z("session_started",{visible:document.visibilityState==="visible",interacted:!1});const D=window.setTimeout(()=>{document.visibilityState==="visible"&&S&&!E&&(E=!0,z("dwell_120_seconds",{visible:!0,interacted:!0}))},12e4),F=()=>{const q=Math.max(1,document.documentElement.scrollHeight-window.innerHeight),Y=Math.round(window.scrollY/q*100);Y>=75&&S&&!X&&(X=!0,z("scroll_depth_75",{visible:document.visibilityState==="visible",interacted:!0,scrollDepth:Y}))};return window.addEventListener("pointerdown",G),window.addEventListener("keydown",G),window.addEventListener("scroll",F,{passive:!0}),()=>{window.clearTimeout(D),window.removeEventListener("pointerdown",G),window.removeEventListener("keydown",G),window.removeEventListener("scroll",F)}},[m.isSuccess]);const w=ue({mutationFn:S=>ii(S),onSuccess:async()=>{await r.invalidateQueries({queryKey:["forge-snapshot"]})}}),h=ue({mutationFn:S=>ho(S),onSuccess:async()=>{await r.invalidateQueries({queryKey:["forge-snapshot"]})}}),P=ue({mutationFn:S=>uo(S),onSuccess:async()=>{await r.invalidateQueries({queryKey:["forge-snapshot"]})}}),T=ue({mutationFn:({goalId:S,patch:E})=>tm(S,E),onSuccess:async()=>{await r.invalidateQueries({queryKey:["forge-snapshot"]})}}),O=ue({mutationFn:({projectId:S,patch:E})=>po(S,E),onSuccess:async()=>{await r.invalidateQueries({queryKey:["forge-snapshot"]})}}),y=ue({mutationFn:({taskId:S,status:E})=>Os(S,{status:E}),onSuccess:async()=>{await r.invalidateQueries({queryKey:["forge-snapshot"]})}}),C=ue({mutationFn:({taskId:S,input:E})=>nm(S,E),onSuccess:async()=>{await r.invalidateQueries({queryKey:["forge-snapshot"]})}}),l=ue({mutationFn:S=>om(S),onSuccess:async()=>{await r.invalidateQueries({queryKey:["forge-snapshot"]})}}),N=ue({mutationFn:({runId:S,actor:E,note:X})=>bo(S,{actor:E,note:X??""}),onSuccess:async()=>{await r.invalidateQueries({queryKey:["forge-snapshot"]})}}),u=ue({mutationFn:({runId:S,actor:E,note:X})=>fo(S,{actor:E,note:X??""}),onSuccess:async()=>{await r.invalidateQueries({queryKey:["forge-snapshot"]})}}),M=ue({mutationFn:async S=>{var D,F;const E=(D=x.data)==null?void 0:D.dashboard.projects.find(q=>q.id===S.projectId);if(!E)throw new Error("Select a project before starting work.");const X=((F=v.data)==null?void 0:F.settings.profile.operatorName)??"Albert",G=await ii({title:S.title,description:S.description,owner:X,goalId:E.goalId,projectId:E.id,priority:"medium",status:"in_progress",effort:"deep",energy:"steady",dueDate:"",points:60,tagIds:[],notes:[]});if(!await A(G.task.id,{actor:X,timerMode:S.timerMode,plannedDurationSeconds:S.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 G.task},onSuccess:async()=>{await r.invalidateQueries({queryKey:["forge-snapshot"]})}}),A=async(S,E)=>{try{return await C.mutateAsync({taskId:S,input:E}),!0}catch(X){if(X instanceof ja&&X.code==="task_run_calendar_blocked"&&typeof window<"u"){const G=window.prompt("Calendar rules block this task right now. Add a reason to override and start anyway.");return!G||G.trim().length===0?!1:(await C.mutateAsync({taskId:S,input:{...E,overrideReason:G.trim()}}),!0)}throw X}};if(g.useEffect(()=>{const S=x.data;if(!S||S.activeTaskRuns.length===0)return;const E=window.setInterval(()=>{if(document.visibilityState==="visible"){for(const X of S.activeTaskRuns)rm(X.id,{actor:X.actor,leaseTtlSeconds:X.leaseTtlSeconds,note:X.note}).catch(()=>{});r.invalidateQueries({queryKey:["forge-snapshot"]})}},3e4);return()=>window.clearInterval(E)},[r,x.data]),m.isLoading||x.isLoading||v.isLoading)return e.jsx("div",{className:"grid min-h-screen place-items-center p-6",children:e.jsx(pt,{eyebrow:"Forge shell",title:"Loading Forge",description:"Checking your operator session and loading your latest snapshot."})});if(m.isError)return e.jsx("div",{className:"grid min-h-screen place-items-center p-6",children:e.jsx(Le,{eyebrow:"Forge operator session",error:m.error,onRetry:()=>void r.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(Le,{eyebrow:"Forge settings",error:v.error,onRetry:()=>void r.invalidateQueries({queryKey:["forge-settings"]})})});if(x.isError||!x.data||!v.data)return e.jsx("div",{className:"grid min-h-screen place-items-center p-6",children:e.jsx(Le,{eyebrow:"Forge state",error:x.error,onRetry:()=>void r.invalidateQueries({queryKey:["forge-snapshot"]})})});const I={snapshot:x.data,refresh:async()=>{await r.invalidateQueries({queryKey:["forge-snapshot"]})},createTask:async S=>{await w.mutateAsync(S)},startTaskNow:async(S,E={})=>{const X=v.data.settings.profile.operatorName;await A(S,{actor:X,timerMode:E.timerMode??"planned",plannedDurationSeconds:E.plannedDurationSeconds===void 0?1200:E.plannedDurationSeconds,isCurrent:!0,leaseTtlSeconds:1800,note:""})},createGoal:async S=>{await h.mutateAsync(S)},createProject:async S=>{await P.mutateAsync(S)},patchGoal:async(S,E)=>{await T.mutateAsync({goalId:S,patch:E})},patchProject:async(S,E)=>{await O.mutateAsync({projectId:S,patch:E})},patchTaskStatus:async(S,E)=>{await y.mutateAsync({taskId:S,status:E})},openStartWork:(S={})=>{d(S),b(null),n(!0)}};return e.jsx(Cd,{locale:v.data.settings.localePreference,children:e.jsx(vo.Provider,{value:I,children:e.jsxs(e.Fragment,{children:[e.jsx(um,{settings:v.data.settings,timerPending:l.isPending||N.isPending||u.isPending,startWorkOpen:i,startWorkPending:C.isPending||M.isPending,startWorkError:c,startWorkDefaults:o,onOpenStartWork:S=>{d(S??{}),b(null),n(!0)},onCloseStartWork:()=>{n(!1),b(null)},onStartExistingTask:async(S,E)=>{try{const X=v.data.settings.profile.operatorName;await A(S,{actor:X,timerMode:E.timerMode,plannedDurationSeconds:E.plannedDurationSeconds,isCurrent:!0,leaseTtlSeconds:1800,note:""})&&(n(!1),b(null))}catch(X){b(X instanceof Error?X.message:"Could not start work.")}},onCreateAndStartTask:async S=>{try{await M.mutateAsync(S),n(!1),b(null)}catch(E){b(E instanceof Error?E.message:"Could not create and start the task.")}},onFocusRun:async S=>{await l.mutateAsync(S)},onPauseRun:async S=>{const E=x.data.activeTaskRuns.find(X=>X.id===S);await N.mutateAsync({runId:S,actor:E==null?void 0:E.actor,note:E==null?void 0:E.note})},onCompleteRun:async S=>{const E=x.data.activeTaskRuns.find(X=>X.id===S);await u.mutateAsync({runId:S,actor:E==null?void 0:E.actor,note:E==null?void 0:E.note})},children:e.jsx(wl,{context:I})}),p?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:te("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",p.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(Cs,{className:"size-4 shrink-0"}),e.jsxs("span",{children:[p.deltaXp>0?`XP +${p.deltaXp}`:`XP ${p.deltaXp}`," ","· ",yo(p.totalXp)," total"]})]})}):null]})})})}function Xe(){return g.useContext(vo)??jl()}function $a(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g," ")}function xm({eyebrow:t,titleText:s,entityKind:a,copyMode:r}){if(!t||r==="title_only"||typeof t!="string")return null;const i=$a(t),n=s?$a(s):null,o=a?$a(Ft(a).label):null;return!i||n&&(i===n||n.includes(i)||i.includes(n))||o&&i===o?null:t}function Fe({eyebrow:t,entityKind:s,title:a,titleText:r,description:i,badge:n,actions:o,copyMode:d="title_only"}){const c=s?Ft(s):null,b=c==null?void 0:c.icon,p=xm({eyebrow:t,titleText:r,entityKind:s,copyMode:d}),f=!!(c||p||n);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:[f?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[c&&b?e.jsx("div",{className:te("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)]",c.subtleBadgeClassName),"aria-label":c.label,title:c.label,children:e.jsx(b,{className:te("size-4",c.iconClassName)})}):null,p?e.jsx("div",{className:"type-label text-[var(--secondary)]",children:p}):null,n?e.jsx(_,{tone:"signal",className:"bg-white/[0.08] text-white/78",children:n}):null]}):null,e.jsx("div",{className:te("max-w-4xl text-[clamp(1.2rem,1.85vw,1.7rem)] leading-[1] text-white",f?"mt-1.5":""),children:a}),e.jsx("div",{className:"mt-1 hidden max-w-3xl text-[13px] leading-5 text-white/54 sm:block",children:i})]}),o?e.jsx("div",{className:"flex min-w-0 flex-wrap items-start gap-2 lg:justify-end",children:o}):null]})}function Rt(t){return t.entityType==="goal"?`/goals/${t.entityId}`:t.entityType==="project"?`/projects/${t.entityId}`:t.entityType==="task"?`/tasks/${t.entityId}`:t.entityType==="task_run"&&typeof t.metadata.taskId=="string"?`/tasks/${t.metadata.taskId}`:null}function ha(t){return t.entityType==="goal"?"Open goal":t.entityType==="project"?"Open project":t.entityType==="task"||t.entityType==="task_run"?"Open task":null}const vs=id(),zn=[vs.accessor("title",{header:"Event",cell:t=>{const s=Rt(t.row.original);return s?e.jsx(Ne,{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()})}}),vs.accessor("source",{header:"Source",cell:t=>e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/50",children:t.getValue()})}),vs.accessor("createdAt",{header:"When",cell:t=>e.jsx("div",{className:"text-sm text-white/55",children:xi(t.getValue())})}),vs.display({id:"actions",header:"Open",cell:t=>{const s=Rt(t.row.original);return s?e.jsx(Ne,{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 gm({rows:t,onRemove:s}){const a=s?[...zn,vs.display({id:"remove",header:"Correct",cell:i=>e.jsx(K,{variant:"ghost",className:"h-auto px-0 py-0 text-[11px] uppercase tracking-[0.16em] text-white/55",onClick:()=>{s(i.row.original.id)},children:"Remove log"})})]:zn,r=nd({columns:a,data:t,getCoreRowModel:rd()});return e.jsx(Z,{className:"overflow-hidden p-0",children:e.jsxs("table",{className:"w-full border-collapse",children:[e.jsx("thead",{children:r.getHeaderGroups().map(i=>e.jsx("tr",{className:"bg-white/[0.03]",children:i.headers.map(n=>e.jsx("th",{className:"px-5 py-4 text-left font-label text-[11px] uppercase tracking-[0.18em] text-white/40",children:n.isPlaceholder?null:wn(n.column.columnDef.header,n.getContext())},n.id))},i.id))}),e.jsx("tbody",{children:r.getRowModel().rows.map(i=>e.jsx("tr",{className:"bg-white/[0.015] transition hover:bg-white/[0.035]",children:i.getVisibleCells().map(n=>e.jsx("td",{className:"px-5 py-4 align-top",children:wn(n.column.columnDef.cell,n.getContext())},n.id))},i.id))})]})})}function fm(){var b;const[t]=ut(),s=Qe(),a=t.get("entityId")??void 0,r=t.get("entityType")??void 0,i=t.get("eventId"),n=oe({queryKey:["activity-archive",r,a],queryFn:()=>Zc({limit:100,entityType:r,entityId:a})}),o=ue({mutationFn:p=>go(p),onSuccess:async()=>{await Promise.all([s.invalidateQueries({queryKey:["activity-archive"]}),s.invalidateQueries({queryKey:["forge-snapshot"]}),s.invalidateQueries({queryKey:["task-context"]}),s.invalidateQueries({queryKey:["project-board"]})])}}),d=((b=n.data)==null?void 0:b.activity)??[];if(n.isLoading)return e.jsx(pt,{eyebrow:"Evidence archive",title:"Loading activity",description:"Pulling the visible audit trail, grouped evidence, and correction history."});if(n.isError)return e.jsx(Le,{eyebrow:"Evidence archive",error:n.error,onRetry:()=>void n.refetch()});if(d.length===0)return e.jsx(rt,{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 c=d.reduce((p,f)=>{const m=f.createdAt.slice(0,10);return p[m]=[...p[m]??[],f],p},{});return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Fe,{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:`${d.length} recent events`}),e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]",children:[e.jsx(gm,{rows:d,onRemove:async p=>{await o.mutateAsync(p)}}),e.jsx("div",{className:"grid gap-4",children:Object.entries(c).slice(0,6).map(([p,f])=>e.jsxs(Z,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:p}),e.jsx("div",{className:"mt-4 grid gap-3",children:f.slice(0,3).map(m=>e.jsxs("div",{className:`rounded-[18px] p-4 ${i===m.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:m.title}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:m.description}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.16em] text-white/35",children:xi(m.createdAt)}),Rt(m)&&ha(m)?e.jsx(Ne,{to:Rt(m),className:"mt-3 inline-flex text-[11px] uppercase tracking-[0.16em] text-[var(--primary)]",children:ha(m)}):null]},m.id))})]},p))})]})]})}function Ba(t){return t.trim().toLowerCase()}function qn(t,s){return t.includes(s)?t:[...t,s]}function We({options:t,selectedValues:s,onChange:a,placeholder:r="Search or create…",emptyMessage:i="No matching entries yet.",createLabel:n="Create",onCreate:o,className:d}){const[c,b]=g.useState(""),[p,f]=g.useState(!1),[m,x]=g.useState(0),[v,w]=g.useState(!1),[h,P]=g.useState(null),[T,O]=g.useState([]),y=g.useMemo(()=>{const j=new Map;return[...T,...t].forEach(S=>{j.set(S.value,S)}),Array.from(j.values())},[T,t]),C=g.useMemo(()=>s.map(j=>y.find(S=>S.value===j)??{value:j,label:j}),[y,s]),l=Ba(c),N=g.useMemo(()=>{const j=y.filter(S=>!s.includes(S.value));return l?j.filter(S=>`${S.label} ${S.description??""} ${S.searchText??""}`.toLowerCase().includes(l)).slice(0,8):j.slice(0,8)},[y,l,s]),u=y.some(j=>Ba(j.label)===l),M=j=>{a(qn(s,j)),b(""),P(null),x(0),f(!1)},A=j=>{a(s.filter(S=>S!==j))},I=async()=>{const j=c.trim();if(!(!o||!j)){w(!0);try{const S=await o(j);O(E=>E.some(X=>X.value===S.value)?E:[S,...E]),a(qn(s,S.value)),b(""),P(null),x(0),f(!1)}catch(S){P(S instanceof Error?S.message:"Unable to create that link right now.")}finally{w(!1)}}};return e.jsxs("div",{className:te("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:[C.length>0?e.jsx("div",{className:"mb-2 flex flex-wrap gap-2",children:C.map(j=>e.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-2",children:[j.kind?e.jsx(xe,{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:()=>A(j.value),children:e.jsx(yt,{className:"size-3.5"})})]},j.value))}):null,e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tt,{className:"size-4 text-white/34"}),e.jsx("input",{value:c,onChange:j=>{b(j.target.value),P(null),f(!0),x(0)},onFocus:()=>f(!0),onBlur:()=>{window.setTimeout(()=>f(!1),120)},onKeyDown:j=>{if(j.key==="Backspace"&&!c&&s.length>0){A(s[s.length-1]);return}if(j.key==="ArrowDown"){j.preventDefault(),f(!0),x(X=>N.length===0?0:Math.min(N.length-1,X+1));return}if(j.key==="ArrowUp"){j.preventDefault(),x(X=>Math.max(0,X-1));return}if(j.key==="Escape"){f(!1);return}if(j.key!=="Enter")return;j.preventDefault();const S=N[m];if(S){M(S.value);return}const E=y.find(X=>Ba(X.label)===l);if(E&&!s.includes(E.value)){M(E.value);return}I()},placeholder:r,className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]})]}),p?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,S)=>e.jsx("button",{type:"button",className:te("flex w-full items-start justify-between gap-3 rounded-[18px] px-3 py-2.5 text-left transition",S===m?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>x(S),onMouseDown:E=>E.preventDefault(),onClick:()=>M(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(xe,{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)),!u&&l&&o?e.jsxs("button",{type:"button",disabled:v,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 I(),children:[e.jsx(Ht,{className:"size-4"}),e.jsx("span",{className:"truncate",children:v?"Creating…":`${n} "${c.trim()}"`})]}):null,N.length===0&&(!l||u||!o)?e.jsx("div",{className:"px-3 py-2.5 text-sm text-white/42",children:i}):null]}):null,h?e.jsx("div",{className:"text-sm text-rose-300",children:h}):null]})}const bm={goal:"goal",project:"project",task:"task",habit:"habit"};function Vt(t){const s=new Date(t);return new Date(s.getTime()-s.getTimezoneOffset()*6e4).toISOString().slice(0,16)}function Kn(t,s){var n;const a=new Date,r=new Date(a.getTime()+30*6e4),i=new Date(r.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)??"",startAtLocal:t?Vt(t.startAt):s!=null&&s.startAt?Vt(s.startAt):Vt(r.toISOString()),endAtLocal:t?Vt(t.endAt):s!=null&&s.endAt?Vt(s.endAt):Vt(i.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:((n=s==null?void 0:s.categories)==null?void 0:n.join(", "))??(t==null?void 0:t.categories.join(", "))??"",linkQuery:"",links:(s==null?void 0:s.links)??(t==null?void 0:t.links.map(o=>({entityType:o.entityType,entityId:o.entityId,relationshipType:o.relationshipType,label:`${o.entityType.replaceAll("_"," ")} · ${o.entityId}`})))??[]}}function vm({open:t,onOpenChange:s,writableCalendars:a,linkOptions:r,event:i,seed:n,onSubmit:o,pending:d=!1}){const[c,b]=g.useState(()=>Kn(i,n)),[p,f]=g.useState(null);g.useEffect(()=>{t&&(b(Kn(i,n)),f(null))},[i,t,n]);const m=g.useMemo(()=>r.map(v=>{const w=bm[v.entityType];return{value:`${v.entityType}:${v.entityId}`,label:v.label,description:v.subtitle,searchText:`${v.label} ${v.subtitle} ${v.entityType}`,kind:w,menuBadge:w?e.jsx(xe,{kind:w,label:v.label,compact:!0,gradient:!1}):void 0,badge:w?e.jsx(xe,{kind:w,label:v.label,compact:!0}):void 0}}),[r]),x=g.useMemo(()=>[{id:"identity",eyebrow:"Event",title:i?"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:(v,w)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(B,{label:"Title",children:e.jsx(se,{value:v.title,onChange:h=>w({title:h.target.value}),placeholder:"Weekly research supervision"})}),e.jsx(B,{label:"Description",children:e.jsx(ve,{value:v.description,onChange:h=>w({description:h.target.value}),placeholder:"Agenda, context, or outcomes you want this event to carry."})}),e.jsx(B,{label:"Location",children:e.jsx(se,{value:v.location,onChange:h=>w({location:h.target.value}),placeholder:"Clinic room 2 or Zoom"})})]})},{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:(v,w)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(B,{label:"Starts",children:e.jsx(se,{type:"datetime-local",value:v.startAtLocal,onChange:h=>w({startAtLocal:h.target.value})})}),e.jsx(B,{label:"Ends",children:e.jsx(se,{type:"datetime-local",value:v.endAtLocal,onChange:h=>w({endAtLocal:h.target.value})})})]}),e.jsx(B,{label:"Timezone",children:e.jsx(se,{value:v.timezone,onChange:h=>w({timezone:h.target.value}),placeholder:"Europe/Zurich"})}),e.jsx(B,{label:"Availability",children:e.jsx(Ke,{value:v.availability,onChange:h=>w({availability:h}),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 goals, projects, tasks, or habits so the calendar carries operating context instead of staying isolated.",render:(v,w)=>e.jsx("div",{className:"grid gap-4",children:e.jsx(B,{label:"Search Forge entities",description:"The linked entities use the same icon and color system as the rest of Forge.",children:e.jsx(We,{options:m,selectedValues:v.links.map(h=>`${h.entityType}:${h.entityId}`),onChange:h=>{w({links:h.map(P=>{const[T,...O]=P.split(":"),y=O.join(":"),C=r.find(l=>l.entityType===T&&l.entityId===y);return C?{entityType:C.entityType,entityId:C.entityId,relationshipType:"context",label:C.label}:null}).filter(P=>P!==null)})},placeholder:"Search goals, projects, tasks, habits",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:(v,w)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"grid gap-3",children:[a.length>0?e.jsxs("button",{type:"button",onClick:()=>w({preferredCalendarId:void 0}),className:`rounded-[22px] border px-4 py-4 text-left transition ${v.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(Ct,{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 ${v.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(Gt,{className:"size-4"}),"Forge only"]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/55",children:"Keep the event in Forge without creating a remote provider copy yet."})]}),a.map(h=>e.jsxs("button",{type:"button",onClick:()=>w({preferredCalendarId:h.id}),className:`rounded-[22px] border px-4 py-4 text-left transition ${v.preferredCalendarId===h.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(Ct,{className:"size-4"}),h.title]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/55",children:h.description||`${h.timezone} · writable`})]},h.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(Al,{className:"size-4 text-[var(--primary)]"}),"Categories and filtering"]}),e.jsx(se,{value:v.categoriesText,onChange:h=>w({categoriesText:h.target.value}),placeholder:"meeting, clinic, research"})]})]})}],[i,r,m,a]);return e.jsx(He,{open:t,onOpenChange:s,eyebrow:i?"Edit event":"New event",title:i?"Edit calendar event":"Create calendar event",description:"Forge-owned events can stay local or publish to a connected provider calendar.",value:c,onChange:b,steps:x,onSubmit:async()=>{if(!c.title.trim()){f("Add an event title before saving.");return}if(!c.startAtLocal||!c.endAtLocal){f("Set both the start and end time before saving.");return}if(new Date(c.endAtLocal).getTime()<=new Date(c.startAtLocal).getTime()){f("The event end time must be after the start time.");return}f(null),await o({title:c.title.trim(),description:c.description.trim(),location:c.location.trim(),startAt:new Date(c.startAtLocal).toISOString(),endAt:new Date(c.endAtLocal).toISOString(),timezone:c.timezone.trim()||"UTC",availability:c.availability,categories:c.categoriesText.split(",").map(v=>v.trim()).filter(Boolean),links:c.links.map(v=>({entityType:v.entityType,entityId:v.entityId,relationshipType:v.relationshipType})),...c.preferredCalendarId!==void 0?{preferredCalendarId:c.preferredCalendarId}:{}})},submitLabel:i?"Save event":"Create event",pending:d,pendingLabel:i?"Saving":"Creating",error:p})}function ym({open:t,onOpenChange:s,initialTitle:a,pending:r=!1,onSubmit:i}){const[n,o]=g.useState(a),[d,c]=g.useState(null);return g.useEffect(()=>{t&&(o(a),c(null))},[a,t]),e.jsx(He,{open:t,onOpenChange:s,eyebrow:"Calendar",title:"Quick rename",description:"Rename the event without reopening the full event guide.",value:{title:n},onChange:b=>o(b.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:(b,p)=>e.jsx(B,{label:"Event title",children:e.jsx(se,{value:b.title,onChange:f=>p({title:f.target.value}),placeholder:"Weekly research supervision"})})}],submitLabel:"Save title",pending:r,pendingLabel:"Saving",error:d,onSubmit:async()=>{const b=n.trim();if(!b){c("Add a title before saving.");return}c(null),await i(b),s(!1)}})}const Un=[{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"}],Qn=[{value:"busy",label:"Busy"},{value:"free",label:"Free"}],ct={allowWorkBlockKinds:[],blockWorkBlockKinds:[],allowCalendarIds:[],blockCalendarIds:[],allowEventTypes:[],blockEventTypes:[],allowEventKeywords:[],blockEventKeywords:[],allowAvailability:[],blockAvailability:[]};function Zt(t){return t.join(", ")}function es(t){return t.split(",").map(s=>s.trim()).filter(Boolean)}function Us({label:t,selected:s,onToggle:a,options:r}){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:r.map(i=>{const n=s.includes(i.value);return e.jsx("button",{type:"button",onClick:()=>a(i.value),className:`rounded-full px-3 py-2 text-sm transition ${n?"bg-[var(--primary)]/18 text-[var(--primary)] shadow-[inset_0_0_0_1px_rgba(192,193,255,0.24)]":"bg-white/[0.05] text-white/62 hover:bg-white/[0.08]"}`,children:i.label},i.value)})})]})}function Ti({title:t,subtitle:s,initialRules:a,initialPlannedDurationSeconds:r,onSave:i,saveLabel:n="Save scheduling rules",allowPlannedDuration:o=!1}){const[d,c]=g.useState((a==null?void 0:a.allowWorkBlockKinds)??ct.allowWorkBlockKinds),[b,p]=g.useState((a==null?void 0:a.blockWorkBlockKinds)??ct.blockWorkBlockKinds),[f,m]=g.useState((a==null?void 0:a.allowAvailability)??ct.allowAvailability),[x,v]=g.useState((a==null?void 0:a.blockAvailability)??ct.blockAvailability),[w,h]=g.useState(Zt((a==null?void 0:a.allowCalendarIds)??ct.allowCalendarIds)),[P,T]=g.useState(Zt((a==null?void 0:a.blockCalendarIds)??ct.blockCalendarIds)),[O,y]=g.useState(Zt((a==null?void 0:a.allowEventTypes)??ct.allowEventTypes)),[C,l]=g.useState(Zt((a==null?void 0:a.blockEventTypes)??ct.blockEventTypes)),[N,u]=g.useState(Zt((a==null?void 0:a.allowEventKeywords)??ct.allowEventKeywords)),[M,A]=g.useState(Zt((a==null?void 0:a.blockEventKeywords)??ct.blockEventKeywords)),[I,j]=g.useState(r?String(Math.round(r/60)):"30"),[S,E]=g.useState(!1),X=g.useMemo(()=>({allowWorkBlockKinds:d,blockWorkBlockKinds:b,allowCalendarIds:es(w),blockCalendarIds:es(P),allowEventTypes:es(O),blockEventTypes:es(C),allowEventKeywords:es(N),blockEventKeywords:es(M),allowAvailability:f,blockAvailability:x}),[f,w,N,O,d,x,P,M,C,b]),G=Object.values(X).every(D=>D.length===0),z=(D,F,q)=>{F(D.includes(q)?D.filter(Y=>Y!==q):[...D,q])};return e.jsxs(Z,{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})]}),o?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(se,{type:"number",min:15,step:15,value:I,onChange:D=>j(D.target.value),placeholder:"30"})]}):null,e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx(Us,{label:"Allow work blocks",selected:d,onToggle:D=>z(d,c,D),options:Un}),e.jsx(Us,{label:"Block work blocks",selected:b,onToggle:D=>z(b,p,D),options:Un}),e.jsx(Us,{label:"Allow availability",selected:f,onToggle:D=>z(f,m,D),options:Qn}),e.jsx(Us,{label:"Block availability",selected:x,onToggle:D=>z(x,v,D),options:Qn})]}),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(se,{value:w,onChange:D=>h(D.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(se,{value:P,onChange:D=>T(D.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(se,{value:O,onChange:D=>y(D.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(se,{value:C,onChange:D=>l(D.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(se,{value:N,onChange:D=>u(D.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(se,{value:M,onChange:D=>A(D.target.value),placeholder:"psychiatrist, clinic, rest"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(K,{pending:S,pendingLabel:"Saving",onClick:async()=>{E(!0);try{await i({schedulingRules:G?ct:X,plannedDurationSeconds:o?Math.max(15,Number(I||30))*60:void 0})}finally{E(!1)}},children:n}),e.jsx(K,{variant:"secondary",onClick:async()=>{E(!0);try{c([]),p([]),m([]),v([]),h(""),T(""),y(""),l(""),u(""),A(""),await i({schedulingRules:null,plannedDurationSeconds:o?Math.max(15,Number(I||30))*60:void 0})}finally{E(!1)}},children:"Clear custom rules"})]})]})}function wm({open:t,onOpenChange:s,tasks:a,onSave:r}){const i=g.useMemo(()=>a.filter(c=>c.status!=="done"),[a]),[n,o]=g.useState("");g.useEffect(()=>{if(t){if(i.length===0){o("");return}o(c=>c&&i.some(b=>b.id===c)?c:i[0].id)}},[i,t]);const d=i.find(c=>c.id===n)??null;return e.jsx(ya,{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(Z,{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(Gt,{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."})]})]})}),i.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Task"}),e.jsx("select",{value:n,onChange:c=>o(c.target.value),className:"rounded-[22px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none",children:i.map(c=>e.jsx("option",{value:c.id,children:c.title},c.id))})]}),d?e.jsx(Ti,{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:c,plannedDurationSeconds:b})=>{await r({taskId:d.id,schedulingRules:c,plannedDurationSeconds:b===void 0?d.plannedDurationSeconds:b??null}),s(!1)}}):null]}):e.jsxs(Z,{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(K,{variant:"secondary",onClick:()=>s(!1),children:"Close"})})]})]})})}const jm=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],ni=[{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 Xn(t=new Date){const s=new Date(t),a=s.getUTCDay(),r=a===0?-6:1-a;return s.setUTCDate(s.getUTCDate()+r),s.setUTCHours(0,0,0,0),s}function Qs(t,s){const a=new Date(t);return a.setUTCDate(a.getUTCDate()+s),a}function ys(t){return new Intl.DateTimeFormat("en",{weekday:"short",month:"short",day:"numeric"}).format(t)}function Gn(t){const s=Math.floor(t/60).toString().padStart(2,"0"),a=String(t%60).padStart(2,"0");return`${s}:${a}`}function km({open:t,onOpenChange:s,tasks:a,from:r,to:i,onCreateTimebox:n}){const o=g.useMemo(()=>a.filter(h=>h.status!=="done"),[a]),[d,c]=g.useState({taskId:"",selectedTimeboxId:""}),[b,p]=g.useState(null),[f,m]=g.useState(!1);g.useEffect(()=>{var P;if(!t)return;const h=((P=o[0])==null?void 0:P.id)??"";p(null),c({taskId:h,selectedTimeboxId:""})},[o,t]);const x=o.find(h=>h.id===d.taskId)??null,v=oe({queryKey:["forge-calendar-suggestions-dialog",d.taskId,r,i],queryFn:()=>Ec({taskId:d.taskId,from:r,to:i,limit:8}),enabled:t&&d.taskId.length>0});g.useEffect(()=>{var P;if(!t)return;const h=((P=v.data)==null?void 0:P.timeboxes)??[];if(!h.length){c(T=>T.selectedTimeboxId?{...T,selectedTimeboxId:""}:T);return}c(T=>T.selectedTimeboxId&&h.some(O=>O.id===T.selectedTimeboxId)?T:{...T,selectedTimeboxId:h[0].id})},[t,v.data]);const w=g.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:(h,P)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(B,{label:"Task",children:e.jsx("select",{value:h.taskId,onChange:T=>P({taskId:T.target.value,selectedTimeboxId:""}),className:"rounded-[22px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none",children:o.map(T=>e.jsx("option",{value:T.id,children:T.title},T.id))})}),x?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:x.title}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(_,{className:"bg-white/[0.08] text-white/74",children:x.plannedDurationSeconds?`${Math.round(x.plannedDurationSeconds/60)} min target`:"No duration yet"}),e.jsx(_,{className:"bg-white/[0.08] text-white/74",children:x.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:(h,P)=>{var O;const T=((O=v.data)==null?void 0:O.timeboxes)??[];return v.isLoading?e.jsx("div",{className:"text-sm text-white/62",children:"Looking for valid upcoming slots…"}):T.length?e.jsx("div",{className:"grid gap-3",children:T.map(y=>{const C=h.selectedTimeboxId===y.id;return e.jsxs("button",{type:"button",onClick:()=>P({selectedTimeboxId:y.id}),className:`rounded-[24px] border px-4 py-4 text-left transition ${C?"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:y.title}),e.jsx(_,{className:"bg-white/[0.08] text-white/76",children:y.source})]}),e.jsxs("div",{className:"mt-2 text-sm leading-6 text-white/58",children:[ys(new Date(y.startsAt))," ·"," ",new Date(y.startsAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," ","-"," ",new Date(y.endsAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]},y.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(K,{variant:"secondary",onClick:()=>void v.refetch(),children:"Refresh suggestions"})]})}}],[o,x,v]);return e.jsx(He,{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:c,steps:w,submitLabel:"Schedule timebox",pending:f,pendingLabel:"Scheduling",error:b,onSubmit:async()=>{var P;const h=(((P=v.data)==null?void 0:P.timeboxes)??[]).find(T=>T.id===d.selectedTimeboxId);if(!h){p("Pick one suggested slot before scheduling the timebox.");return}try{m(!0),p(null),await n({taskId:h.taskId,projectId:h.projectId,title:h.title,startsAt:h.startsAt,endsAt:h.endsAt,source:"suggested"}),s(!1)}catch(T){p(T instanceof Error?T.message:"Forge could not create the selected timebox.")}finally{m(!1)}}})}function Wn(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=ni[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 Hn(t){return t??""}function Nm({open:t,onOpenChange:s,onSubmit:a,pending:r=!1,template:i=null}){const[n,o]=g.useState(()=>Wn(i)),[d,c]=g.useState(null),b=i!==null;g.useEffect(()=>{t&&(c(null),o(Wn(i)))},[t,i]);const p=g.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:(f,m)=>e.jsx("div",{className:"grid gap-4",children:e.jsx(B,{label:"Block type",children:e.jsx(Ke,{value:f.kind,columns:3,onChange:x=>{const v=ni.find(w=>w.kind===x);if(v){const w=v.kind==="holiday"?[0,1,2,3,4,5,6]:[1,2,3,4,5];m({kind:v.kind,title:v.title,color:v.color,weekDays:w,startMinute:v.startMinute,endMinute:v.endMinute,blockingState:v.blockingState});return}m({kind:"custom",title:"Custom block",color:"#7dd3fc"})},options:[...ni.map(x=>({value:x.kind,label:x.title,description:`${Gn(x.startMinute)}-${Gn(x.endMinute)}`})),{value:"custom",label:"Custom",description:"Build a different recurring window."}]})})})},{id:"shape",eyebrow:"Schedule",title:"Define when this recurring block should exist",description:"Weekdays and times describe the recurring pattern. Optional start and end dates bound when the template is active.",render:(f,m)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(B,{label:"Block title",children:e.jsx(se,{value:f.title,onChange:x=>m({title:x.target.value}),placeholder:"Main Activity"})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(B,{label:"Start minute",children:e.jsx(se,{type:"number",min:0,max:1440,step:15,value:f.startMinute,onChange:x=>m({startMinute:Number(x.target.value)||0})})}),e.jsx(B,{label:"End minute",children:e.jsx(se,{type:"number",min:0,max:1440,step:15,value:f.endMinute,onChange:x=>m({endMinute:Number(x.target.value)||0})})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(B,{label:"Start date",children:e.jsx(se,{type:"date",value:Hn(f.startsOn),onChange:x=>m({startsOn:x.target.value.trim()||null})})}),e.jsx(B,{label:"End date",children:e.jsx(se,{type:"date",value:Hn(f.endsOn),onChange:x=>m({endsOn:x.target.value.trim()||null})})})]}),e.jsx("div",{className:"text-sm leading-6 text-white/54",children:"Leave the end date empty to keep repeating indefinitely. Holiday blocks work well with all seven weekdays and `0-1440`."}),e.jsx(B,{label:"Weekdays",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:jm.map((x,v)=>{const w=f.weekDays.includes(v);return e.jsx("button",{type:"button",onClick:()=>m({weekDays:w?f.weekDays.filter(h=>h!==v):[...f.weekDays,v].sort((h,P)=>h-P)}),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:x},x)})})})]})},{id:"policy",eyebrow:"Policy",title:"Tell Forge whether this block allows or blocks work",description:"Use blocked mode for time that should normally stop optional work. Use allowed mode for protected focus windows.",render:(f,m)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(B,{label:"Work effect",children:e.jsx(Ke,{value:f.blockingState,onChange:x=>m({blockingState:x}),options:[{value:"blocked",label:"Blocks work",description:"Starting blocked tasks should require an explicit override."},{value:"allowed",label:"Allows work",description:"Use this for protected windows where the right tasks should fit."}]})}),e.jsx(B,{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:f.color,onChange:x=>m({color:x.target.value})}),e.jsx(se,{className:"border-none bg-transparent px-0 py-0",value:f.color,onChange:x=>m({color:x.target.value})})]})})]})}],[]);return e.jsx(He,{open:t,onOpenChange:s,eyebrow:"Calendar",title:b?"Edit work block":"Create a work block",description:b?"Adjust the recurring pattern, date bounds, or work policy for this block.":"Build recurring half-day, holiday, or custom blocks so Forge can understand when work should be protected or blocked.",value:n,onChange:o,steps:p,submitLabel:b?"Save changes":"Save work block",pending:r,pendingLabel:b?"Saving changes":"Saving",error:d,onSubmit:async()=>{if(!n.title.trim()){c("Give the block a title so it stays readable in the calendar.");return}if(n.weekDays.length===0){c("Select at least one weekday for the recurring block.");return}if(n.endMinute<=n.startMinute){c("The end minute needs to be later than the start minute.");return}if(n.startsOn&&n.endsOn&&n.endsOn<n.startsOn){c("The end date needs to be on or after the start date.");return}try{c(null),await a({...n,title:n.title.trim()}),s(!1)}catch(f){c(f instanceof Error?f.message:"Forge could not save this work block.")}}})}function dt({className:t}){return e.jsx("div",{className:te("surface-pulse rounded-2xl bg-white/[0.05]",t)})}function xt({header:t=!0,sideRail:s=!0,className:a,eyebrow:r,title:i,description:n,columns:o=2,blocks:d=4}){const c=Array.from({length:Math.max(2,d)});return e.jsxs("div",{className:te("grid gap-5",a),"aria-hidden":"true",children:[t?e.jsxs(Z,{className:"grid gap-4",children:[e.jsx(dt,{className:te("h-3",r?"w-40":"w-32")}),e.jsx(dt,{className:te("h-12",i?"max-w-2xl":"max-w-3xl")}),e.jsx(dt,{className:te("h-5",n?"max-w-3xl":"max-w-2xl")})]}):null,e.jsxs("section",{className:te("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(Z,{className:"grid gap-4",children:[e.jsx(dt,{className:"h-3 w-28"}),e.jsx(dt,{className:"h-28 w-full"})]}),e.jsxs(Z,{className:"grid gap-4",children:[e.jsx(dt,{className:"h-3 w-40"}),e.jsx("div",{className:te("grid gap-3",o>1?"md:grid-cols-2":""),children:c.map((b,p)=>e.jsx(dt,{className:"h-28 w-full"},p))})]})]}),s?e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(Z,{className:"grid gap-4",children:[e.jsx(dt,{className:"h-3 w-24"}),e.jsx(dt,{className:"h-20 w-full"})]}),e.jsxs(Z,{className:"grid gap-4",children:[e.jsx(dt,{className:"h-3 w-36"}),e.jsx(dt,{className:"h-16 w-full"}),e.jsx(dt,{className:"h-16 w-full"})]})]}):null]})]})}function wo({open:t,title:s,subtitle:a,items:r,position:i,onClose:n}){return g.useEffect(()=>{if(!t)return;let o=!1;const d=window.setTimeout(()=>{o=!0},0),c=p=>{p.key==="Escape"&&n()},b=()=>{o&&n()};return window.addEventListener("keydown",c),window.addEventListener("pointerdown",b),()=>{window.clearTimeout(d),window.removeEventListener("keydown",c),window.removeEventListener("pointerdown",b)}},[n,t]),!t||!i||typeof document>"u"?null:_r.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(i.x,window.innerWidth-24-352),top:Math.min(i.y,window.innerHeight-24-320)},onPointerDown:o=>o.stopPropagation(),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-[20px] bg-white/[0.03] px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:s}),a?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/50",children:a}):null]}),e.jsx("button",{type:"button",className:"rounded-full bg-white/[0.04] p-2 text-white/55 transition hover:bg-white/[0.08] hover:text-white",onClick:n,children:e.jsx(yt,{className:"size-4"})})]}),e.jsx("div",{className:"mt-2 grid gap-1",children:r.map(o=>{const d=o.icon;return e.jsxs("button",{type:"button",disabled:o.disabled,onClick:()=>{o.disabled||(o.onSelect(),n())},className:te("flex w-full items-start gap-3 rounded-[20px] px-4 py-3 text-left transition",o.disabled?"cursor-not-allowed bg-white/[0.02] text-white/28":o.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:te("mt-0.5 rounded-[14px] p-2",o.disabled?"bg-white/[0.03] text-white/28":o.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:o.label}),o.description?e.jsx("span",{className:"mt-1 block text-xs leading-5 text-white/48",children:o.description}):null]})]},o.id)})})]})}),document.body)}const jo="forge.calendar-display-preferences",Yn=["#7dd3fc","#34d399","#f59e0b","#fb7185","#60a5fa","#a3e635","#f97316","#22c55e"],za={useCalendarColors:!0,calendarColors:{}};function ko(t){return typeof t=="string"&&/^#[0-9a-fA-F]{6}$/.test(t)}function No(){if(typeof window>"u")return za;const t=window.localStorage.getItem(jo);if(!t)return za;try{const s=JSON.parse(t);return{useCalendarColors:s.useCalendarColors??!0,calendarColors:s.calendarColors&&typeof s.calendarColors=="object"?Object.fromEntries(Object.entries(s.calendarColors).filter(a=>ko(a[1]))):{}}}catch{return za}}function Cm(t){typeof window>"u"||window.localStorage.setItem(jo,JSON.stringify(t))}function Co(t){return Yn[t%Yn.length]??"#7dd3fc"}function So(t,s){return Object.fromEntries(t.map((a,r)=>[a.id,ko(s[a.id])?s[a.id]:Co(r)]))}function Jn(t){let s=0;for(let a=0;a<t.length;a+=1)s=s*31+t.charCodeAt(a)>>>0;return Co(s)}const Xs=$r(t=>({entry:null,setEntry:s=>t({entry:s}),clear:()=>t({entry:null}),completePaste:()=>t(s=>{var a;return{entry:((a=s.entry)==null?void 0:a.mode)==="cut"?null:s.entry}})})),Sm={goal:"goal",project:"project",task:"task",habit:"habit"};function Tm(t){const s=new Date(t);s.setUTCHours(9,0,0,0);const a=new Date(s.getTime()+3600*1e3);return{startAt:s.toISOString(),endAt:a.toISOString(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",availability:"busy"}}function Vn(t,s){const a=new Date(t.startAt),i=new Date(t.endAt).getTime()-a.getTime(),n=new Date(s);n.setUTCHours(a.getUTCHours(),a.getUTCMinutes(),0,0);const o=new Date(n.getTime()+i);return{startAt:n.toISOString(),endAt:o.toISOString()}}function Zn(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 Im(t){switch(t){case"apple":return"Apple";case"google":return"Google";case"caldav":return"CalDAV";case"native":return"Forge";default:return"Derived"}}function Pm(t,s){var a;if(t.calendarId){const r=(a=s.get(t.calendarId))==null?void 0:a.trim();if(r)return r}return t.originType==="native"?"Forge only":Im(t.originType)}function er(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 tr(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 Mm(){var lt,It,Pt;const t=ht(),s=Xe(),a=Qe(),r=Xs(U=>U.entry),i=Xs(U=>U.setEntry),n=Xs(U=>U.clear),o=Xs(U=>U.completePaste),[d,c]=g.useState(()=>Xn()),[b,p]=g.useState(null),[f,m]=g.useState(null),[x,v]=g.useState(!1),[w,h]=g.useState(null),[P,T]=g.useState(!1),[O,y]=g.useState(!1),[C,l]=g.useState(!1),[N,u]=g.useState(null),[M,A]=g.useState(null),I=g.useMemo(()=>No(),[]),[j,S]=g.useState(null),[E,X]=g.useState(null),[G,z]=g.useState(null),D=g.useMemo(()=>{const U=d.toISOString(),de=Qs(d,7).toISOString();return{from:U,to:de}},[d]),F=oe({queryKey:["forge-calendar-overview",D.from,D.to],queryFn:()=>Sa(D)}),q=["forge-calendar-overview",D.from,D.to],Y=U=>{if(U.deletedAt)return!1;const de=new Date(U.startAt).getTime();return de>=new Date(D.from).getTime()&&de<new Date(D.to).getTime()},L=U=>{a.setQueryData(q,de=>de&&U(de))},V=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"]})])},le=ue({mutationFn:Cc,onSuccess:V}),ce=ue({mutationFn:({templateId:U,patch:de})=>Sc(U,de),onSuccess:V}),he=ue({mutationFn:Tc,onSuccess:V}),je=ue({mutationFn:U=>Ac(U),onSuccess:V}),W=ue({mutationFn:({timeboxId:U,startsAt:de,endsAt:ge})=>Dc(U,{startsAt:de,endsAt:ge}),onSuccess:V}),$=ue({mutationFn:Ic,onMutate:async U=>{z({tone:"saving",message:"Saving event changes in the background…"}),await a.cancelQueries({queryKey:q});const de=a.getQueryData(q),ge=(de==null?void 0:de.calendar.calendars.find(ne=>ne.canWrite&&ne.selectedForSync))??(de==null?void 0:de.calendar.calendars.find(ne=>ne.canWrite))??null,Be=new Date().toISOString(),ze={id:`calendar_event_optimistic_${Date.now()}`,connectionId:(ge==null?void 0:ge.connectionId)??null,calendarId:U.preferredCalendarId===void 0?(ge==null?void 0:ge.id)??null:U.preferredCalendarId,remoteId:null,ownership:"forge",originType:"native",status:"confirmed",title:U.title,description:U.description??"",location:U.location??"",startAt:U.startAt,endAt:U.endAt,timezone:U.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",isAllDay:U.isAllDay??!1,availability:U.availability??"busy",eventType:U.eventType??"general",categories:U.categories??[],sourceMappings:[],links:(U.links??[]).map((ne,Pe)=>({id:`calendar_event_link_optimistic_${Date.now()}_${Pe}`,entityType:ne.entityType,entityId:ne.entityId,relationshipType:ne.relationshipType??"context",createdAt:Be,updatedAt:Be})),remoteUpdatedAt:null,deletedAt:null,createdAt:Be,updatedAt:Be};return de&&Y(ze)&&L(ne=>({...ne,calendar:{...ne.calendar,events:[ze,...ne.calendar.events]}})),{previous:de,optimisticEventId:ze.id}},onError:(U,de,ge)=>{ge!=null&&ge.previous&&a.setQueryData(q,ge.previous),z({tone:"error",message:U instanceof Error?U.message:"Forge could not sync that event change."})},onSuccess:({event:U},de,ge)=>{z(null),L(Be=>({...Be,calendar:{...Be.calendar,events:(Y(U)?[U,...Be.calendar.events.filter(ze=>ze.id!==(ge==null?void 0:ge.optimisticEventId))]:Be.calendar.events.filter(ze=>ze.id!==(ge==null?void 0:ge.optimisticEventId))).filter((ze,ne,Pe)=>Pe.findIndex(me=>me.id===ze.id)===ne)}}))},onSettled:V}),k=ue({mutationFn:({eventId:U,patch:de})=>Pc(U,de),onMutate:async({eventId:U,patch:de})=>{z({tone:"saving",message:"Saving event changes in the background…"}),await a.cancelQueries({queryKey:q});const ge=a.getQueryData(q);return ge&&L(Be=>{var Pe;const ze=Be.calendar.events.find(me=>me.id===U);if(!ze)return Be;const ne={...ze,...de,calendarId:de.preferredCalendarId===void 0?ze.calendarId:de.preferredCalendarId,links:((Pe=de.links)==null?void 0:Pe.map((me,Ae)=>{var Me,we;return{id:((Me=ze.links[Ae])==null?void 0:Me.id)??`calendar_event_link_optimistic_${Date.now()}_${Ae}`,entityType:me.entityType,entityId:me.entityId,relationshipType:me.relationshipType??"context",createdAt:((we=ze.links[Ae])==null?void 0:we.createdAt)??ze.createdAt,updatedAt:new Date().toISOString()}}))??ze.links,updatedAt:new Date().toISOString()};return{...Be,calendar:{...Be.calendar,events:Be.calendar.events.map(me=>me.id===U?ne:me).filter(Y)}}}),{previous:ge}},onError:(U,de,ge)=>{ge!=null&&ge.previous&&a.setQueryData(q,ge.previous),z({tone:"error",message:U instanceof Error?U.message:"Forge could not sync that event change."})},onSuccess:({event:U})=>{z(null),L(de=>({...de,calendar:{...de.calendar,events:de.calendar.events.map(ge=>ge.id===U.id?U:ge).filter(Y)}}))},onSettled:V}),R=ue({mutationFn:Mc,onMutate:async U=>{z({tone:"saving",message:"Removing the event in the background…"}),await a.cancelQueries({queryKey:q});const de=a.getQueryData(q);return de&&L(ge=>({...ge,calendar:{...ge.calendar,events:ge.calendar.events.filter(Be=>Be.id!==U)}})),{previous:de}},onError:(U,de,ge)=>{ge!=null&&ge.previous&&a.setQueryData(q,ge.previous),z({tone:"error",message:U instanceof Error?U.message:"Forge could not delete that event."})},onSuccess:()=>{z(null)},onSettled:V}),Q=(lt=F.data)==null?void 0:lt.calendar,Ce=g.useMemo(()=>Array.from({length:7},(U,de)=>Qs(d,de)),[d]),ie=Q??{connections:[],calendars:[],events:[],workBlockTemplates:[],workBlockInstances:[],timeboxes:[]},_e=g.useMemo(()=>new Map(ie.calendars.map(U=>[U.id,U.title])),[ie.calendars]),J=g.useMemo(()=>So(ie.calendars,I.calendarColors),[I.calendarColors,ie.calendars]),H=$.isPending||k.isPending||R.isPending,pe=ie.timeboxes.filter(U=>U.status==="planned"),Ie=ie.calendars.filter(U=>U.canWrite),Ye=[...s.snapshot.goals.map(U=>({entityType:"goal",entityId:U.id,label:U.title,subtitle:"Goal"})),...s.snapshot.projects.map(U=>({entityType:"project",entityId:U.id,label:U.title,subtitle:"Project"})),...s.snapshot.tasks.map(U=>({entityType:"task",entityId:U.id,label:U.title,subtitle:"Task"})),...s.snapshot.habits.map(U=>({entityType:"habit",entityId:U.id,label:U.title,subtitle:"Habit"}))],fe=g.useMemo(()=>new Map(Ye.map(U=>[`${U.entityType}:${U.entityId}`,U.label])),[Ye]),ye=ie.connections.length===0?"No providers connected":`${ie.connections.filter(U=>U.status==="connected").length}/${ie.connections.length} healthy`,$e=(r==null?void 0:r.items.filter(U=>U.type==="calendar_event"))??[],ae=U=>{u(null),S(Tm(U)),l(!0)},ot=async(U,de)=>{const ge=Vn({startAt:U.startAt,endAt:U.endAt},de);await k.mutateAsync({eventId:U.id,patch:ge})},st=async U=>{if($e.length!==0){for(const de of $e){const ge=Vn(de,U);(r==null?void 0:r.mode)==="cut"?await k.mutateAsync({eventId:de.eventId,patch:ge}):await $.mutateAsync({title:de.title,description:de.description,location:de.location,startAt:ge.startAt,endAt:ge.endAt,timezone:de.timezone,availability:de.availability,preferredCalendarId:de.preferredCalendarId,categories:de.categories,links:de.links})}o()}},Je=g.useMemo(()=>{if(!E)return[];if(E.kind==="day"){const de=Ce.find(ge=>ge.toISOString().slice(0,10)===E.dayKey);return de?[{id:"create-event",label:"Create event",description:"Open the event guide with this day already selected.",icon:Qt,onSelect:()=>ae(de)},{id:"create-work-block",label:"Create work block",description:"Open the guided work-block flow while you are looking at this day.",icon:na,onSelect:()=>{h(null),v(!0)}},{id:"paste",label:(r==null?void 0:r.mode)==="cut"?"Paste moved event":"Paste copied event",description:$e.length>0?`${$e.length} calendar item${$e.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:Dl,disabled:$e.length===0,onSelect:()=>void st(de)}]:[]}if(E.kind==="work-block"){const de=ie.workBlockTemplates.find(ge=>ge.id===E.templateId);return de?[{id:"edit-work-block",label:"Edit",description:"Adjust the recurring pattern, date bounds, or work policy.",icon:Qt,onSelect:()=>{h(de),v(!0)}},{id:"delete-work-block",label:"Delete",description:"Remove this recurring work block from Forge.",icon:bt,tone:"danger",onSelect:()=>{(w==null?void 0:w.id)===de.id&&h(null),he.mutateAsync(de.id)}}]:[]}const U=ie.events.find(de=>de.id===E.eventId);return U?[{id:"rename",label:"Quick rename",description:"Change the event title without opening the full event flow.",icon:Qt,onSelect:()=>A(U)},{id:"copy",label:"Copy",description:"Put this event on the Forge clipboard so you can paste it into another day.",icon:Br,onSelect:()=>i({id:`clipboard_${U.id}_${Date.now()}`,mode:"copy",source:"calendar",label:U.title,createdAt:new Date().toISOString(),items:[Zn(U)]})},{id:"cut",label:"Cut",description:"Move this event by pasting it into another day.",icon:El,onSelect:()=>i({id:`clipboard_cut_${U.id}_${Date.now()}`,mode:"cut",source:"calendar",label:U.title,createdAt:new Date().toISOString(),items:[Zn(U)]})},{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"&&$e.some(de=>de.eventId===U.id)&&n(),R.mutateAsync(U.id)}}]:[]},[n,$e,r,Ce,R,he,E,ie.events,ie.workBlockTemplates,w,i]);return F.isLoading?e.jsx(xt,{}):F.isError||!F.data?e.jsx(Le,{eyebrow:"Calendar",error:F.error??new Error("Calendar data is unavailable"),onRetry:()=>void F.refetch()}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Fe,{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:`${ie.connections.length} connection${ie.connections.length===1?"":"s"}`}),e.jsxs(Z,{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."}),G?e.jsx("div",{className:`mt-3 inline-flex max-w-full items-center gap-2 rounded-full px-3 py-1.5 text-xs ${G.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:G.message}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(_,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[e.jsx(Ct,{className:"mr-1 size-3.5"}),"Week of ",ys(d)]}),H?e.jsxs(_,{className:"bg-white/[0.08] text-white/78",children:[e.jsx(ns,{className:"mr-1 size-3.5 animate-spin"}),"Syncing changes"]}):null,r?e.jsxs(_,{className:"bg-white/[0.08] text-white/74",children:[r.mode==="cut"?"Cut":"Copied"," · ",r.label]}):null,e.jsx(K,{variant:"secondary",onClick:()=>c(Qs(d,-7)),children:"Previous"}),e.jsx(K,{variant:"secondary",onClick:()=>c(Xn()),children:"This week"}),e.jsx(K,{variant:"secondary",onClick:()=>c(Qs(d,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:Ce.map(U=>{const de=U.toISOString().slice(0,10),ge=ie.events.filter(ne=>ne.startAt.slice(0,10)===de&&!ne.deletedAt),Be=ie.workBlockInstances.filter(ne=>ne.dateKey===de),ze=ie.timeboxes.filter(ne=>ne.startsAt.slice(0,10)===de);return e.jsxs("div",{"data-calendar-day":de,onClick:ne=>{ne.target.closest("[data-calendar-item='true']")||X({kind:"day",dayKey:de,position:{x:ne.clientX,y:ne.clientY}})},onDragOver:ne=>{ne.preventDefault()},onDrop:ne=>{ne.preventDefault();const Pe=ne.dataTransfer.getData("text/forge-event-id")||f;if(Pe){const ke=ie.events.find(qs=>qs.id===Pe);ke&&ot(ke,U),m(null);return}const me=ne.dataTransfer.getData("text/forge-timebox-id")||b;if(!me)return;const Ae=ie.timeboxes.find(ke=>ke.id===me);if(!Ae)return;const Me=new Date(Ae.startsAt),it=new Date(Ae.endsAt).getTime()-Me.getTime(),De=new Date(U);De.setUTCHours(Me.getUTCHours(),Me.getUTCMinutes(),0,0);const jt=new Date(De.getTime()+it);W.mutateAsync({timeboxId:me,startsAt:De.toISOString(),endsAt:jt.toISOString()}),p(null)},className:"min-w-0 overflow-hidden rounded-[24px] border border-white/6 bg-white/[0.03] p-3 transition hover:border-white/12 hover:bg-white/[0.045]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[18px] bg-[rgba(10,16,30,0.96)] px-3 py-2 text-sm font-medium text-white",children:[e.jsx("span",{className:"min-w-0 truncate",children:ys(U)}),e.jsx("button",{type:"button","aria-label":`Open actions for ${ys(U)}`,className:"rounded-full bg-white/[0.06] p-2 text-white/58 transition hover:bg-white/[0.1] hover:text-white",onClick:ne=>{ne.stopPropagation(),X({kind:"day",dayKey:de,position:{x:ne.clientX,y:ne.clientY}})},children:e.jsx(ra,{className:"size-4"})})]}),e.jsxs("div",{className:"mt-3 grid min-w-0 gap-2",children:[Be.map(ne=>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:`${ne.color}22`,border:`1px solid ${ne.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:ne.title}),e.jsxs("div",{className:"mt-1 flex min-w-0 flex-wrap items-center gap-1.5",children:[e.jsx(_,{size:"sm",className:"shrink-0 bg-white/[0.08] text-white/78",children:ne.blockingState}),e.jsx(_,{size:"sm",className:"shrink-0 bg-white/[0.08] text-white/78",children:er(ne.kind)})]})]}),e.jsx("button",{type:"button","aria-label":`Open actions for ${ne.title}`,className:"rounded-full bg-white/[0.05] p-1.5 text-white/56 transition hover:bg-white/[0.1] hover:text-white",onClick:Pe=>{Pe.stopPropagation(),X({kind:"work-block",templateId:ne.templateId,position:{x:Pe.clientX,y:Pe.clientY}})},children:e.jsx(ra,{className:"size-4"})})]}),e.jsxs("div",{className:"mt-1 text-white/60",children:[new Date(ne.startAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," ","-"," ",new Date(ne.endAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),e.jsx("div",{className:"mt-2 text-xs text-white/48",children:tr(ie.workBlockTemplates.find(Pe=>Pe.id===ne.templateId)??{id:ne.templateId,title:ne.title,kind:ne.kind,color:ne.color,startsOn:null,endsOn:null,blockingState:ne.blockingState,createdAt:ne.createdAt,updatedAt:ne.updatedAt})})]},ne.id)),ge.map(ne=>e.jsxs("div",{"data-calendar-item":"true",draggable:!0,onDragStart:Pe=>{m(ne.id),Pe.dataTransfer.setData("text/forge-event-id",ne.id)},onClick:Pe=>{Pe.stopPropagation(),u(ne),S(null),l(!0)},className:`min-w-0 cursor-move overflow-hidden rounded-[18px] px-3 py-2 text-left text-sm text-white/82 transition ${I.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:I.useCalendarColors?{backgroundColor:`${(ne.calendarId?J[ne.calendarId]:null)??Jn(`origin:${ne.originType}`)}1f`,border:`1px solid ${(ne.calendarId?J[ne.calendarId]:null)??Jn(`origin:${ne.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:ne.title}),e.jsxs("div",{className:"mt-1 text-white/55",children:[new Date(ne.startAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," ","-"," ",new Date(ne.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 ${ne.title}`,className:"rounded-full bg-white/[0.05] p-1.5 text-white/56 transition hover:bg-white/[0.1] hover:text-white",onClick:Pe=>{Pe.stopPropagation(),X({kind:"event",eventId:ne.id,position:{x:Pe.clientX,y:Pe.clientY}})},children:e.jsx(ra,{className:"size-4"})})})]}),e.jsxs("div",{className:"mt-2 flex min-w-0 flex-wrap items-center gap-1.5",children:[e.jsx(_,{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:Pm(ne,_e)}),ne.calendarId&&I.useCalendarColors?e.jsx("span",{"aria-hidden":"true",className:"size-2.5 shrink-0 rounded-full",style:{backgroundColor:J[ne.calendarId]}}):null]}),ne.links.length>0?e.jsx("div",{className:"mt-2 flex min-w-0 flex-wrap gap-1.5",children:ne.links.slice(0,3).map(Pe=>{const me=Sm[Pe.entityType];return me?e.jsx(xe,{kind:me,label:fe.get(`${Pe.entityType}:${Pe.entityId}`)??Pe.entityType,compact:!0,gradient:!1},Pe.id):e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:Pe.entityType},Pe.id)})}):null]},ne.id)),ze.map(ne=>e.jsxs("div",{"data-calendar-item":"true",draggable:!0,onDragStart:Pe=>{p(ne.id),Pe.dataTransfer.setData("text/forge-timebox-id",ne.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:ne.title}),e.jsx(_,{size:"sm",className:"shrink-0 bg-white/[0.08] text-white/78",children:ne.status})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-white/70",children:[e.jsx(ds,{className:"size-3.5"}),new Date(ne.startsAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," ","-"," ",new Date(ne.endsAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]},ne.id)),Be.length===0&&ge.length===0&&ze.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]})]},de)})})]}),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(Z,{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(Qt,{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(K,{onClick:()=>{h(null),u(null),S(null),l(!0)},children:[e.jsx(Qt,{className:"size-4"}),"Open event guide"]})})]}),e.jsxs(Z,{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(na,{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(K,{onClick:()=>{h(null),v(!0)},children:[e.jsx(na,{className:"size-4"}),"Open work-block guide"]})})]}),e.jsxs(Z,{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(Gt,{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(K,{onClick:()=>y(!0),children:[e.jsx(Gt,{className:"size-4"}),"Open planning guide"]})})]}),e.jsxs(Z,{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:ye})]})]}),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(K,{variant:"secondary",onClick:()=>t("/settings/calendar"),children:[e.jsx(Is,{className:"size-4"}),"Open calendar settings"]}),e.jsxs(K,{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(Z,{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(K,{variant:"secondary",onClick:()=>void F.refetch(),children:[e.jsx(ns,{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:ie.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:ie.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:pe.length})]})]})]}),e.jsxs(Z,{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:()=>T(!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(_,{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(_,{className:"bg-white/[0.08] text-white/74",children:ie.workBlockTemplates.length})]}),e.jsxs("div",{className:"mt-3 grid gap-2",children:[ie.workBlockTemplates.slice(0,4).map(U=>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:U.title}),e.jsxs("div",{className:"mt-1 text-white/56",children:[er(U.kind)," · ",U.weekDays.length," day",U.weekDays.length===1?"":"s"," · ",U.blockingState]}),e.jsx("div",{className:"mt-1 text-white/46",children:tr(U)}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(K,{variant:"secondary",size:"sm",onClick:()=>{h(U),v(!0)},children:[e.jsx(Qt,{className:"size-3.5"}),"Edit"]}),e.jsxs(K,{variant:"secondary",size:"sm",onClick:()=>void he.mutateAsync(U.id),children:[e.jsx(bt,{className:"size-3.5"}),"Delete"]})]})]},U.id)),ie.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(Nm,{open:x,onOpenChange:U=>{v(U),U||h(null)},pending:le.isPending||ce.isPending,template:w,onSubmit:async U=>{if(w){await ce.mutateAsync({templateId:w.id,patch:U});return}await le.mutateAsync(U)}}),e.jsx(wm,{open:P,onOpenChange:T,tasks:s.snapshot.tasks,onSave:async({taskId:U,schedulingRules:de,plannedDurationSeconds:ge})=>{await Os(U,{schedulingRules:de,plannedDurationSeconds:ge}),await s.refresh(),await V(),await a.invalidateQueries({queryKey:["task-context",U]})}}),e.jsx(km,{open:O,onOpenChange:y,tasks:s.snapshot.tasks,from:D.from,to:D.to,onCreateTimebox:async U=>{await je.mutateAsync(U)}}),e.jsx(vm,{open:C,onOpenChange:U=>{l(U),U||(u(null),S(null))},writableCalendars:Ie,linkOptions:Ye,event:N,seed:j??void 0,onSubmit:async U=>{if(N){const de=N.id;l(!1),u(null),S(null),k.mutateAsync({eventId:de,patch:U}).catch(()=>{});return}else{l(!1),u(null),S(null),$.mutateAsync(U).catch(()=>{});return}},pending:$.isPending||k.isPending}),e.jsx(ym,{open:M!==null,onOpenChange:U=>{U||A(null)},initialTitle:(M==null?void 0:M.title)??"",pending:k.isPending,onSubmit:async U=>{if(!M)return;const de=M.id;A(null),k.mutateAsync({eventId:de,patch:{title:U}}).catch(()=>{})}}),e.jsx(wo,{open:E!==null,title:(E==null?void 0:E.kind)==="event"?((It=ie.events.find(U=>U.id===E.eventId))==null?void 0:It.title)??"Event actions":(E==null?void 0:E.kind)==="work-block"?((Pt=ie.workBlockTemplates.find(U=>U.id===E.templateId))==null?void 0:Pt.title)??"Work block actions":(E==null?void 0:E.kind)==="day"?ys(Ce.find(U=>U.toISOString().slice(0,10)===E.dayKey)??d):"Calendar actions",subtitle:(E==null?void 0:E.kind)==="day"?"Choose what to create or paste into this day.":(E==null?void 0:E.kind)==="work-block"?"Edit or remove this recurring work block.":r?`Clipboard ready: ${r.label}`:"Quick calendar event actions.",items:Je,position:(E==null?void 0:E.position)??null,onClose:()=>X(null)})]})}function Gs(t,s){const a=[],r=/(\[([^\]]+)\]\(([^)]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|\*([^*]+)\*)/g;let i=0,n=null,o=0;for(;(n=r.exec(t))!==null;){if(n.index>i&&(a.push(e.jsx(g.Fragment,{children:t.slice(i,n.index)},`${s}-text-${o}`)),o+=1),n[2]&&n[3]){const d=n[3].trim(),c=/^https?:\/\//i.test(d);a.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:c?"_blank":void 0,rel:c?"noreferrer":void 0,children:n[2]},`${s}-link-${o}`))}else n[4]?a.push(e.jsx("code",{className:"rounded bg-white/[0.08] px-1.5 py-0.5 text-[0.92em] text-white/90",children:n[4]},`${s}-code-${o}`)):n[5]?a.push(e.jsx("strong",{className:"font-semibold text-white",children:n[5]},`${s}-strong-${o}`)):n[6]&&a.push(e.jsx("em",{className:"italic text-white/88",children:n[6]},`${s}-em-${o}`));i=r.lastIndex,o+=1}return i<t.length&&a.push(e.jsx(g.Fragment,{children:t.slice(i)},`${s}-tail-${o}`)),a}function Am(t){const s=t.replace(/\r/g,"").split(`
2
+ `),a=[];let r=0;for(;r<s.length;){const i=s[r]??"",n=i.trim();if(!n){r+=1;continue}if(n.startsWith("```")){const c=[];for(r+=1;r<s.length&&!(s[r]??"").trim().startsWith("```");)c.push(s[r]??""),r+=1;r+=1,a.push(e.jsx("pre",{className:"overflow-x-auto rounded-[18px] bg-[rgba(6,10,18,0.88)] px-4 py-3 text-xs leading-6 text-white/86",children:e.jsx("code",{children:c.join(`
3
+ `)})},`code-${r}`));continue}const o=i.match(/^(#{1,6})\s+(.*)$/);if(o){const c=o[1].length,b=c===1?"text-xl":c===2?"text-lg":c===3?"text-base":"text-sm";a.push(e.jsx("div",{className:te("font-semibold text-white",b),children:Gs(o[2],`heading-${r}`)},`heading-${r}`)),r+=1;continue}if(/^>\s?/.test(i)){const c=[];for(;r<s.length&&/^>\s?/.test(s[r]??"");)c.push((s[r]??"").replace(/^>\s?/,"")),r+=1;a.push(e.jsx("blockquote",{className:"border-l-2 border-[var(--secondary)]/50 pl-4 text-sm leading-7 text-white/72",children:Gs(c.join(" "),`quote-${r}`)},`quote-${r}`));continue}if(/^[-*+]\s+/.test(i)||/^\d+\.\s+/.test(i)){const c=/^\d+\.\s+/.test(i),b=[];for(;r<s.length&&(/^[-*+]\s+/.test(s[r]??"")||/^\d+\.\s+/.test(s[r]??""));)b.push((s[r]??"").replace(/^[-*+]\s+/,"").replace(/^\d+\.\s+/,"")),r+=1;const p=c?"ol":"ul";a.push(e.jsx(p,{className:te("space-y-1 pl-5 text-sm leading-7 text-white/74",c?"list-decimal":"list-disc"),children:b.map((f,m)=>e.jsx("li",{children:Gs(f,`list-${r}-${m}`)},`item-${r}-${m}`))},`list-${r}`));continue}const d=[];for(;r<s.length;){const c=s[r]??"";if(!c.trim()||c.trim().startsWith("```")||/^#{1,6}\s+/.test(c)||/^>\s?/.test(c)||/^[-*+]\s+/.test(c)||/^\d+\.\s+/.test(c))break;d.push(c.trim()),r+=1}a.push(e.jsx("p",{className:"text-sm leading-7 text-white/72",children:Gs(d.join(" "),`paragraph-${r}`)},`paragraph-${r}`))}return a}function mt({markdown:t,className:s}){return e.jsx("div",{className:te("grid gap-3",s),children:Am(t)})}const Dm={spark:"Spark stage",story:"Story stage",state:"State stage",lens:"Lens stage",pivot:"Pivot stage"};function Em(t,s){return`${t}:${s}`}function at(t,s,a){return(t==null?void 0:t[Em(s,a)])??{count:0,latestNoteId:null,latestCreatedAt:null}}function To(t){return`${t} Note${t===1?"":"s"}`}function Xt(t){return t.replaceAll("_"," ")}function js(t){if(!t)return null;const s=t.trim().toLowerCase(),a=Dm[s];return a||s.split(/[_\-\s]+/).filter(Boolean).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ")}function Lm(t,s){const a=js(s);return a?t==="trigger_report"?`This note is pinned to the ${a.toLowerCase()} of the report, so it stays attached to that part of the reflective chain.`:`This note is pinned to the "${a}" section of the ${Xt(t)} instead of only the whole entity.`:null}function ua(t,s){switch(t){case"goal":return`/goals/${s}`;case"project":return`/projects/${s}`;case"task":return`/tasks/${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 Io(t,s){switch(t){case"goal":case"project":case"task":case"trigger_report":{const a=ua(t,s);return a?`${a}#notes`:null}default:return`/notes?entityType=${encodeURIComponent(t)}&entityId=${encodeURIComponent(s)}`}}function sr(t){return t.links.find(s=>ua(s.entityType,s.entityId)!==null)??t.links[0]??null}const ar=[{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 vt(t){const s=new Set;return t.map(a=>a.trim()).filter(Boolean).filter(a=>{const r=a.toLowerCase();return s.has(r)?!1:(s.add(r),!0)})}function Po(t){const s=t.trim();if(!s)return null;const a=new Date(s);return Number.isNaN(a.getTime())?null:a.toISOString()}function Mo(t){if(!t)return"";const s=new Date(t);if(Number.isNaN(s.getTime()))return"";const a=s.getFullYear(),r=String(s.getMonth()+1).padStart(2,"0"),i=String(s.getDate()).padStart(2,"0"),n=String(s.getHours()).padStart(2,"0"),o=String(s.getMinutes()).padStart(2,"0");return`${a}-${r}-${i}T${n}:${o}`}function Ao(t,s){const a=Number(t);if(!Number.isFinite(a)||a<=0)return null;const r=s==="hours"?3600*1e3:1440*60*1e3;return new Date(Date.now()+a*r).toISOString()}function Fm(t){const s=new Set(ar.map(i=>i.value.toLowerCase())),a=ar.map(i=>({value:i.value,label:i.label,description:i.description,searchText:`${i.label} ${i.description}`,badge:e.jsx(_,{className:"bg-cyan-400/10 text-cyan-50",children:i.label}),menuBadge:e.jsx(_,{className:"bg-cyan-400/10 text-cyan-50",children:i.label})})),r=vt(t).filter(i=>!s.has(i.toLowerCase())).map(i=>({value:i,label:i,description:"Custom note tag",searchText:i,badge:e.jsx(_,{className:"bg-white/[0.08] text-white/78",children:i}),menuBadge:e.jsx(_,{className:"bg-white/[0.08] text-white/78",children:i})}));return[...a,...r]}function ks({value:t,onChange:s,placeholder:a="Add a memory tag or create a custom tag"}){const r=Fm(t);return e.jsx(We,{options:r,selectedValues:vt(t),onChange:i=>s(vt(i)),placeholder:a,emptyMessage:"No note tags yet.",createLabel:"Add custom tag",onCreate:async i=>{const n=i.trim();return{value:n,label:n,description:"Custom note tag",searchText:n,badge:e.jsx(_,{className:"bg-white/[0.08] text-white/78",children:n}),menuBadge:e.jsx(_,{className:"bg-white/[0.08] text-white/78",children:n})}}})}function Om(t,s,a){return t.links.filter(r=>!(r.entityType===s&&r.entityId===a))}function Rm(t,s){return t.entityType===s.entityType&&t.entityId===s.entityId&&(t.anchorKey??null)===(s.anchorKey??null)}function qa(t){const s=new Set;return t.filter(a=>{const r=`${a.entityType}:${a.entityId}:${a.anchorKey??""}`;return s.has(r)?!1:(s.add(r),!0)})}function ir(t,s,a){return Po(t)??Ao(s,a)}function Ia({entityType:t,entityId:s,anchorKey:a,includeAnchorlessWhenAnchored:r=!1,title:i="Notes",description:n="Markdown notes linked to this entity stay searchable, editable, and visible alongside the work.",invalidateQueryKeys:o=[],compact:d=!1}){var Pt,U,de,ge,Be,ze,ne,Pe;const c=Xe(),b=Qe(),[p,f]=g.useState(""),[m,x]=g.useState(!1),[v,w]=g.useState(""),[h,P]=g.useState(!1),[T,O]=g.useState({entityType:"goal",entityId:""}),[y,C]=g.useState([]),[l,N]=g.useState([]),[u,M]=g.useState(""),[A,I]=g.useState(""),[j,S]=g.useState("days"),[E,X]=g.useState(null),[G,z]=g.useState(""),[D,F]=g.useState(!1),[q,Y]=g.useState([]),[L,V]=g.useState({entityType:"goal",entityId:""}),[le,ce]=g.useState([]),[he,je]=g.useState(""),[W,$]=g.useState(""),[k,R]=g.useState("days"),Q=js(a),Ce=Lm(t,a),ie=oe({queryKey:["notes",t,s],queryFn:()=>no({linkedEntityType:t,linkedEntityId:s,limit:100})}),_e=oe({queryKey:["forge-psyche-values"],queryFn:$t}),J=oe({queryKey:["forge-psyche-patterns"],queryFn:Es}),H=oe({queryKey:["forge-psyche-behaviors"],queryFn:Bt}),pe=oe({queryKey:["forge-psyche-beliefs"],queryFn:hs}),Ie=oe({queryKey:["forge-psyche-modes"],queryFn:zt}),Ye=oe({queryKey:["forge-psyche-reports"],queryFn:Ca}),fe=g.useMemo(()=>{var me,Ae,Me,we,it,De,jt;return{goal:c.snapshot.goals.map(ke=>({id:ke.id,label:ke.title})),project:c.snapshot.dashboard.projects.map(ke=>({id:ke.id,label:ke.title})),task:c.snapshot.tasks.map(ke=>({id:ke.id,label:ke.title})),habit:c.snapshot.habits.map(ke=>({id:ke.id,label:ke.title})),tag:c.snapshot.tags.map(ke=>({id:ke.id,label:ke.name})),note:(((me=ie.data)==null?void 0:me.notes)??[]).map(ke=>({id:ke.id,label:ke.contentPlain||ke.contentMarkdown})),insight:[],psyche_value:(((Ae=_e.data)==null?void 0:Ae.values)??[]).map(ke=>({id:ke.id,label:ke.title})),behavior_pattern:(((Me=J.data)==null?void 0:Me.patterns)??[]).map(ke=>({id:ke.id,label:ke.title})),behavior:(((we=H.data)==null?void 0:we.behaviors)??[]).map(ke=>({id:ke.id,label:ke.title})),belief_entry:(((it=pe.data)==null?void 0:it.beliefs)??[]).map(ke=>({id:ke.id,label:ke.statement})),mode_profile:(((De=Ie.data)==null?void 0:De.modes)??[]).map(ke=>({id:ke.id,label:ke.title})),mode_guide_session:[],event_type:[],emotion_definition:[],trigger_report:(((jt=Ye.data)==null?void 0:jt.reports)??[]).map(ke=>({id:ke.id,label:ke.title})),calendar_event:[],work_block_template:[],task_timebox:[]}},[(Pt=H.data)==null?void 0:Pt.behaviors,(U=pe.data)==null?void 0:U.beliefs,(de=Ie.data)==null?void 0:de.modes,(ge=ie.data)==null?void 0:ge.notes,(Be=J.data)==null?void 0:Be.patterns,(ze=Ye.data)==null?void 0:ze.reports,c.snapshot.dashboard.projects,c.snapshot.goals,c.snapshot.habits,c.snapshot.tags,c.snapshot.tasks,(ne=_e.data)==null?void 0:ne.values]),ye=async()=>{await Promise.all([b.invalidateQueries({queryKey:["notes",t,s]}),b.invalidateQueries({queryKey:["forge-snapshot"]}),...o.map(me=>b.invalidateQueries({queryKey:me}))])},$e=ue({mutationFn:async me=>Ci({contentMarkdown:me,tags:vt(l),destroyAt:ir(u,A,j),links:qa([{entityType:t,entityId:s,anchorKey:a??null},...y])}),onSuccess:async()=>{w(""),P(!1),C([]),O({entityType:"goal",entityId:""}),N([]),M(""),I(""),S("days"),await ye()}}),ae=ue({mutationFn:async({noteId:me,contentMarkdown:Ae,links:Me,tags:we,destroyAt:it})=>ro(me,{contentMarkdown:Ae,links:Me,tags:we,destroyAt:it}),onSuccess:async()=>{X(null),z(""),F(!1),Y([]),V({entityType:"goal",entityId:""}),ce([]),je(""),$(""),R("days"),await ye()}}),ot=ue({mutationFn:async me=>oo(me),onSuccess:ye}),st=g.useMemo(()=>{var Ae;return(((Ae=ie.data)==null?void 0:Ae.notes)??[]).filter(Me=>a===void 0?!0:Me.links.some(we=>we.entityType===t&&we.entityId===s&&((we.anchorKey??null)===a||r&&(we.anchorKey??null)===null))).filter(Me=>{const we=p.trim().toLowerCase();return we?`${Me.contentPlain} ${Me.author??""} ${(Me.tags??[]).join(" ")}`.toLowerCase().includes(we):!0})},[a,s,t,r,(Pe=ie.data)==null?void 0:Pe.notes,p]),Je=(me,Ae,Me)=>{const we=me.entityId.trim();return we?(Ae(qa([...Me,{entityType:me.entityType,entityId:we,anchorKey:null}])),!0):!1},lt=me=>{var Me,we;const Ae=(Me=fe[me.entityType])==null?void 0:Me.find(it=>it.id===me.entityId);return(we=Ae==null?void 0:Ae.label)!=null&&we.trim()?Ae.label.trim():`Deleted ${Xt(me.entityType)}`},It=(me,Ae,Me,we,it)=>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(_,{className:"bg-white/[0.08] text-white/68",children:[me.length," linked"]})]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:me.map(De=>{const jt=me.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:[Xt(De.entityType)," · ",lt(De)]}),De.anchorKey?e.jsx("span",{className:"rounded-full bg-white/[0.08] px-2 py-0.5 text-[11px] text-white/54",children:js(De.anchorKey)}):null,e.jsx("button",{type:"button",disabled:!jt,className:"text-white/44 transition hover:text-white disabled:cursor-not-allowed disabled:opacity-30",onClick:()=>Ae(me.filter(ke=>!Rm(ke,De))),"aria-label":`Remove ${Xt(De.entityType)} link to ${lt(De)}`,children:e.jsx(bt,{className:"size-3.5"})})]},`${it}-${De.entityType}-${De.entityId}-${De.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:Me.entityType,onChange:De=>we({...Me,entityType:De.target.value,entityId:""}),children:["goal","project","task","habit","tag","note","psyche_value","behavior_pattern","behavior","belief_entry","mode_profile","mode_guide_session","event_type","emotion_definition","trigger_report"].map(De=>e.jsx("option",{value:De,children:Xt(De)},De))}),e.jsxs("select",{className:"min-w-0 rounded-[14px] bg-white/[0.06] px-3 py-3 text-white",value:Me.entityId,onChange:De=>we({...Me,entityId:De.target.value}),children:[e.jsx("option",{value:"",children:(fe[Me.entityType]??[]).length>0?"Choose linked item":"No linked items available"}),(fe[Me.entityType]??[]).map(De=>e.jsx("option",{value:De.id,children:De.label},De.id))]}),e.jsx(K,{variant:"secondary",disabled:!Me.entityId,onClick:()=>{Je(Me,Ae,me)&&we({...Me,entityId:""})},children:"Add link"})]})]});return e.jsx(Z,{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:i}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:n}),Q?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 ",Q]}),Ce?e.jsx(Oe,{content:Ce,label:`Explain ${Q}`}):null]}):null]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:To(st.length)}),m?null:e.jsxs(K,{type:"button",size:"sm",onClick:()=>x(!0),children:[e.jsx(Ht,{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(Tt,{className:"size-4 text-white/34"}),e.jsx(se,{value:p,onChange:me=>f(me.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(Ht,{className:"size-4 text-[var(--secondary)]"}),"Add note"]}),e.jsxs(K,{type:"button",variant:"secondary",size:"sm",className:"gap-2",onClick:()=>P(me=>!me),children:[e.jsx(bn,{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:v.trim()?e.jsx(mt,{markdown:v}):e.jsx("div",{className:"text-sm leading-6 text-white/42",children:"Markdown preview appears here once you have note content."})})]}):e.jsx(ve,{value:v,onChange:me=>w(me.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:It(qa([{entityType:t,entityId:s,anchorKey:a??null},...y]),me=>C(me.filter(Ae=>!(Ae.entityType===t&&Ae.entityId===s&&(Ae.anchorKey??null)===(a??null)))),T,O,"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(ks,{value:l,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(se,{type:"datetime-local",value:u,onChange:me=>M(me.target.value)}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_10rem]",children:[e.jsx(se,{type:"number",min:"1",value:A,onChange:me=>I(me.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:me=>S(me.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(K,{type:"button",variant:"secondary",onClick:()=>{x(!1),P(!1),w(""),C([]),O({entityType:"goal",entityId:""}),N([]),M(""),I(""),S("days")},children:"Cancel"}),e.jsx(K,{pending:$e.isPending,pendingLabel:"Saving",disabled:v.trim().length===0,onClick:async()=>{await $e.mutateAsync(v.trim()),x(!1)},children:"Save note"})]})]}):null,e.jsxs("div",{className:"mt-4 grid gap-3",children:[ie.isLoading?e.jsx("div",{className:"rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/56",children:"Loading notes…"}):null,!ie.isLoading&&st.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,st.map(me=>{const Ae=E===me.id,Me=Om(me,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:[(me.author??"Unknown author").toString()," •"," ",new Date(me.updatedAt).toLocaleString()]}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[Me.map(we=>e.jsxs(_,{className:"bg-white/[0.08] text-white/68",wrap:!0,children:[Xt(we.entityType)," ·"," ",lt(we),we.anchorKey?` · ${js(we.anchorKey)}`:""]},`${me.id}-${we.entityType}-${we.entityId}-${we.anchorKey??""}`)),(me.tags??[]).map(we=>e.jsx(_,{className:"bg-cyan-400/10 text-cyan-50",wrap:!0,children:we},`${me.id}-tag-${we}`)),me.destroyAt?e.jsxs(_,{className:"bg-amber-400/10 text-amber-100",wrap:!0,children:["Ephemeral · deletes"," ",new Date(me.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:()=>{X(me.id),z(me.contentMarkdown),F(!1),Y(me.links),V({entityType:"goal",entityId:""}),ce(vt(me.tags??[])),je(Mo(me.destroyAt??null)),$(""),R("days")},children:e.jsx(Ss,{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:()=>{ot.mutateAsync(me.id)},children:e.jsx(bt,{className:"size-4"})})]})]}),Ae?e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"flex flex-wrap items-center justify-end gap-2",children:e.jsxs(K,{type:"button",variant:"secondary",size:"sm",className:"gap-2",onClick:()=>F(we=>!we),children:[e.jsx(bn,{className:"size-4"}),D?"Back to editor":"Preview"]})}),e.jsx("div",{className:"mt-3",children:D?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:G.trim()?e.jsx(mt,{markdown:G}):e.jsx("div",{className:"text-sm text-white/42",children:"No content yet."})})]}):e.jsx(ve,{value:G,onChange:we=>z(we.target.value),className:"min-h-[12rem]"})}),e.jsxs("div",{className:"mt-3 grid gap-3 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]",children:[e.jsx(ks,{value:le,onChange:ce}),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(se,{type:"datetime-local",value:he,onChange:we=>je(we.target.value)}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_10rem]",children:[e.jsx(se,{type:"number",min:"1",value:W,onChange:we=>$(we.target.value),placeholder:"Destroy after"}),e.jsxs("select",{className:"rounded-[14px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:k,onChange:we=>R(we.target.value),children:[e.jsx("option",{value:"hours",children:"Hours"}),e.jsx("option",{value:"days",children:"Days"})]})]})]})]}),e.jsx("div",{className:"mt-3",children:It(q,Y,L,V,`edit-note-links-${me.id}`)}),e.jsxs("div",{className:"mt-3 flex flex-wrap justify-end gap-2",children:[e.jsx(K,{variant:"secondary",onClick:()=>{X(null),F(!1),ce([]),je(""),$(""),R("days")},children:"Cancel"}),e.jsx(K,{pending:ae.isPending,pendingLabel:"Saving",disabled:G.trim().length===0||q.length===0,onClick:async()=>{await ae.mutateAsync({noteId:me.id,contentMarkdown:G.trim(),links:q,tags:vt(le),destroyAt:ir(he,W,k)})},children:"Save changes"})]})]}):e.jsx("div",{className:"mt-4",children:e.jsx(mt,{markdown:me.contentMarkdown})})]},me.id)})]})]})})}const nr={active:"Active",paused:"Suspended",completed:"Finished",all:"All"};function Ii({value:t,counts:s,onChange:a,className:r}){return e.jsx("div",{className:te("flex flex-wrap gap-2",r),children:Object.keys(nr).map(i=>{const n=i===t;return e.jsxs("button",{type:"button",onClick:()=>a(i),className:te("inline-flex min-h-10 items-center gap-2 rounded-full border px-4 py-2 text-sm transition",n?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.16)] text-white shadow-[0_16px_36px_rgba(8,12,24,0.18)]":"border-white/8 bg-white/[0.04] text-white/62 hover:bg-white/[0.08] hover:text-white"),children:[e.jsx("span",{children:nr[i]}),e.jsx("span",{className:te("rounded-full px-2 py-0.5 text-[11px]",n?"bg-white/12 text-white/88":"bg-white/8 text-white/54"),children:s[i]})]},i)})})}function _t({value:t,className:s,tone:a="primary"}){const r=`${Math.max(4,Math.min(100,t))}%`,i=a==="secondary"?"from-[var(--secondary)] to-[rgba(78,222,163,0.45)]":a==="tertiary"?"from-[var(--tertiary)] to-[rgba(255,185,95,0.45)]":"from-[var(--primary)] to-[rgba(192,193,255,0.45)]";return e.jsx("div",{className:te("h-1.5 rounded-full bg-white/[0.08]",s),children:e.jsx("div",{className:te("h-full rounded-full bg-gradient-to-r",i),style:{width:r}})})}function Do(t){const s=`${t.title} ${t.description} ${t.source??""}`.toLowerCase();return s.includes("playwright")||s.includes("operator console")||s.includes("retroactive work logging")}function Pa(t){return Do(t)?"Work log added":t.title}function Ma(t){return Do(t)?"This entry was added later so the work history stays complete and accurate.":t.description}function Pi(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 Mi(t,s){return s==="all"?t:t.filter(a=>a.status===s)}function _m(){const{t}=qe(),s=Xe(),a=fa(),[r,i]=g.useState(!1),[n,o]=g.useState(!1),[d,c]=g.useState("active"),[b,p]=g.useState(null),f=s.snapshot.dashboard.goals.find(l=>l.id===a.goalId)??null,m=g.useMemo(()=>s.snapshot.dashboard.projects.filter(l=>l.goalId===a.goalId),[a.goalId,s.snapshot.dashboard.projects]),x=g.useMemo(()=>Pi(m),[m]),v=g.useMemo(()=>Mi(m,d),[m,d]),w=new Set(m.map(l=>l.id)),h=new Set(s.snapshot.tasks.filter(l=>w.has(l.projectId??"")).map(l=>l.id)),P=s.snapshot.activity.filter(l=>l.entityId===a.goalId||w.has(l.entityId)||h.has(l.entityId)||l.entityType==="task_run"&&typeof l.metadata.taskId=="string"&&h.has(l.metadata.taskId));if(!f)return e.jsx(rt,{eyebrow:t("common.goalDetail.eyebrow"),title:t("common.goalDetail.missingTitle"),description:t("common.goalDetail.missingDescription"),action:e.jsx(Ne,{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 T=v.find(l=>l.nextTaskTitle)??v[0]??null,O=s.snapshot.overview.neglectedGoals.find(l=>l.goalId===f.id)??null,y=P[0]??null,C=async l=>{p(l);try{await s.patchProject(l,{status:"active"})}finally{p(null)}};return e.jsxs("div",{className:"grid min-w-0 gap-5",children:[e.jsx(Fe,{entityKind:"goal",title:e.jsx(Te,{kind:"goal",label:f.title,variant:"heading",size:"lg"}),titleText:f.title,description:f.description?e.jsx(mt,{markdown:f.description,className:"[&>p]:text-[13px] [&>p]:leading-6 [&>blockquote]:text-[13px] [&>ul]:text-[13px] [&>ol]:text-[13px]"}):"No strategic description yet.",badge:t(v.length===1?"common.goalDetail.heroBadgeOne":"common.goalDetail.heroBadgeOther",{count:v.length})}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(K,{onClick:()=>i(!0),children:t("common.goalDetail.edit")}),e.jsx(K,{variant:"secondary",onClick:()=>o(!0),children:t("common.goalDetail.addProject")})]}),e.jsxs("section",{className:"grid min-w-0 gap-5 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]",children:[e.jsxs(Z,{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(Ii,{value:d,counts:x,onChange:c,className:"justify-end"})]}),v.length===0?e.jsx("div",{className:"mt-4 rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/58",children:d==="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:v.map(l=>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.jsx(xe,{kind:"project",compact:!0,gradient:!1}),e.jsx(_,{children:l.status})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Ne,{to:`/projects/${l.id}`,className:"transition hover:opacity-90",children:e.jsx(Te,{kind:"project",label:l.title,variant:"heading",size:"lg"})})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:l.description}),e.jsx("div",{className:"mt-4",children:e.jsx(_t,{value:l.progress})}),e.jsx("div",{className:"mt-4 text-[11px] uppercase tracking-[0.16em] text-white/40",children:l.nextTaskTitle?t("common.goalDetail.nextMove",{value:l.nextTaskTitle}):t("common.goalDetail.addNextTask")}),e.jsxs("div",{className:"mt-4 flex flex-wrap justify-between gap-3",children:[e.jsx(Ne,{to:`/projects/${l.id}`,children:e.jsx(K,{variant:"ghost",children:"Open project"})}),d!=="active"&&l.status!=="active"?e.jsx(K,{variant:"secondary",size:"sm",pending:b===l.id,pendingLabel:"Restarting…",onClick:()=>void C(l.id),children:"Restart"}):null]})]},l.id))})]}),e.jsx("div",{className:"grid min-w-0 gap-5",children:e.jsxs(Z,{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(xe,{kind:"goal",compact:!0,gradient:!1}),e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:t("common.goalDetail.progressTitle",{progress:f.progress,count:f.completedTasks})}),e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:t("common.goalDetail.progressDetail",{xp:f.earnedPoints})}),e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:t(v.length===1?"common.goalDetail.heroBadgeOne":"common.goalDetail.heroBadgeOther",{count:v.length})})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:t("common.goalDetail.fieldProgress")}),e.jsxs("div",{className:"mt-2 font-display text-xl text-white",children:[f.progress,"%"]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:t("common.goalDetail.fieldCompletedTasks")}),e.jsx("div",{className:"mt-2 font-display text-xl text-white",children:f.completedTasks})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:t("common.goalDetail.fieldXpBanked")}),e.jsx("div",{className:"mt-2 font-display text-xl text-white",children:f.earnedPoints})]})]}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:t("common.goalDetail.signalNext")}),T?e.jsx(xe,{kind:"project",compact:!0,gradient:!1}):null]}),e.jsx("div",{className:"mt-2 font-medium text-white",children:(T==null?void 0:T.title)??t("common.goalDetail.noProject")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:T!=null&&T.nextTaskTitle?t("common.goalDetail.nextMove",{value:T.nextTaskTitle}):(T==null?void 0:T.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:(O==null?void 0:O.title)??t("common.goalDetail.noRisk")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(O==null?void 0:O.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:(y==null?void 0:y.title)??t("common.goalDetail.noEvidence")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(y==null?void 0:y.description)||t("common.goalDetail.noEvidenceDetail")})]})]})]})]})})]}),e.jsx(Ia,{entityType:"goal",entityId:f.id,title:"Goal notes",description:"Use notes to capture strategy changes, meaning shifts, and progress context that belongs at the goal level."}),e.jsxs(Z,{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(l=>e.jsxs(Ne,{to:Rt(l)??`/activity?eventId=${l.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:Pa(l)}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:Ma(l)})]},l.id))})]}),e.jsx(vi,{open:r,editingGoal:f,tags:s.snapshot.tags,onOpenChange:i,onSubmit:async(l,N)=>{N&&await s.patchGoal(N,l)}}),e.jsx(yi,{open:n,goals:s.snapshot.goals,editingProject:null,initialGoalId:f.id,onOpenChange:o,onSubmit:async l=>{await s.createProject(l)}})]})}function Ze({entityType:t,entityId:s,count:a,className:r=""}){const i=ht(),n=Io(t,s);return n?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 ${r}`,onClick:o=>{o.stopPropagation(),i(n)},onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),o.stopPropagation(),i(n))},children:[e.jsx(li,{className:"size-3.5"}),To(a)]}):null}function $m({goals:t,tags:s,pending:a=!1,onCreate:r,onUpdate:i}){const[n,o]=g.useState(!1),[d,c]=g.useState(null),b=t.find(p=>p.id===d)??null;return e.jsxs(e.Fragment,{children:[e.jsxs(Z,{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(K,{onClick:()=>{c(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(p=>{const f=`${Math.max(6,Math.min(100,p.progress))}%`;return e.jsxs(Ne,{to:`/goals/${p.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(xe,{kind:"goal",compact:!0,gradient:!1}),e.jsx("div",{className:"mt-2",children:e.jsx(Te,{kind:"goal",label:p.title,variant:"heading",size:"lg",showKind:!1})}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/58",children:p.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:m=>{m.preventDefault(),m.stopPropagation(),c(p.id),o(!0)},children:e.jsx(Qt,{className:"size-4"})})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(_,{className:"bg-white/[0.08] text-white/70",children:p.horizon}),e.jsx(_,{className:p.status==="active"?"text-emerald-300":p.status==="paused"?"text-amber-300":"text-[var(--tertiary)]",children:p.status}),e.jsxs(_,{className:"bg-white/[0.08] text-white/70",children:[p.earnedPoints," / ",p.targetPoints," xp"]}),e.jsxs(_,{className:"bg-white/[0.08] text-white/70",children:[p.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:f}})}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:p.tags.map(m=>e.jsx(_,{className:"bg-white/[0.06] text-white/58",children:m.name},m.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:p.momentumLabel}),e.jsxs("span",{className:"inline-flex items-center gap-2",style:{color:p.themeColor},children:["Open arc",e.jsx(Jt,{className:"size-3.5"})]})]})]},p.id)})]})]}),e.jsx(vi,{open:n,pending:a,editingGoal:b,tags:s,onOpenChange:p=>{o(p),p||c(null)},onSubmit:async(p,f)=>{if(f){await i(f,p);return}await r(p)}})]})}function Bm(){const t=Xe(),[s,a]=g.useState("active"),[r,i]=g.useState(null),n=t.snapshot.dashboard.goals.length>0,o=Pi(t.snapshot.dashboard.projects),d=Mi(t.snapshot.dashboard.projects,s),c=new Map(t.snapshot.dashboard.goals.map(p=>[p.id,d.filter(f=>f.goalId===p.id)])),b=async p=>{i(p);try{await t.patchProject(p,{status:"active"})}finally{i(null)}};return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Fe,{entityKind:"goal",title:e.jsx(Te,{kind:"goal",label:"Life Goals",variant:"heading",size:"lg"}),titleText:"Life Goals",description:"Life goals are the destinations you care about over the long run. Each one can hold several projects, and those projects turn direction into real work.",badge:`${t.snapshot.dashboard.goals.length} active goals`,actions:n?e.jsxs("div",{className:"inline-flex min-h-10 items-center rounded-full border border-white/8 bg-white/[0.04] px-4 py-2 text-sm whitespace-nowrap text-white/68",children:[t.snapshot.dashboard.projects.length," live project",t.snapshot.dashboard.projects.length===1?"":"s"," attached"]}):null}),e.jsx($m,{goals:t.snapshot.dashboard.goals,tags:t.snapshot.tags,onCreate:t.createGoal,onUpdate:t.patchGoal}),n?e.jsx(Ii,{value:s,counts:o,onChange:a}):null,n?null:e.jsx(rt,{eyebrow:"Life goals",title:"No life goals yet",description:"Define the first long-horizon direction above so Forge can attach projects, tasks, momentum, and evidence to something meaningful."}),n?e.jsx("div",{className:"grid gap-4",children:t.snapshot.dashboard.goals.map(p=>{const f=c.get(p.id)??[],m=at(t.snapshot.dashboard.notesSummaryByEntity,"goal",p.id);return e.jsx(Ne,{to:`/goals/${p.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:[p.tags.slice(0,3).map(x=>e.jsx(_,{className:"bg-white/[0.08]",style:{color:x.color},children:x.name},x.id)),e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:p.horizon})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Te,{kind:"goal",label:p.title,variant:"heading",size:"xl"})}),e.jsx("p",{className:"mt-3 max-w-2xl text-sm leading-7 text-white/58",children:p.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:[p.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:[p.completedTasks,"/",Math.max(p.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:p.earnedPoints})]})]}),e.jsx("div",{className:"mt-4",children:e.jsx(_t,{value:p.progress})}),e.jsx("div",{className:"mt-4",children:e.jsx(Ze,{entityType:"goal",entityId:p.id,count:m.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:f.length})]}),f.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:f.slice(0,3).map(x=>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(xe,{kind:"project",compact:!0,gradient:!1}),e.jsx(Te,{kind:"project",label:x.title,className:"min-w-0",showIcon:!1})]}),e.jsx(_,{children:x.status})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:x.description}),e.jsxs("div",{className:"mt-3 text-sm text-white/42",children:["Next move: ",x.nextTaskTitle??"Define the first attached task"]}),s!=="active"&&x.status!=="active"?e.jsx("div",{className:"mt-4 flex justify-end",children:e.jsx(K,{variant:"secondary",size:"sm",pending:r===x.id,pendingLabel:"Restarting…",onClick:v=>{v.preventDefault(),v.stopPropagation(),b(x.id)},children:"Restart"})}):null]},x.id))})]})]})},p.id)})}):e.jsx(Z,{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 Ka={title:"",description:"",status:"active",polarity:"positive",frequency:"daily",targetCount:1,weekDays:[],linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],linkedValueIds:[],linkedPatternIds:[],linkedBehaviorIds:[],linkedBeliefIds:[],linkedModeIds:[],linkedReportIds:[],linkedBehaviorId:"",rewardXp:12,penaltyXp:8},zm=[{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 qm(t){return{title:t.title,description:t.description,status:t.status,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}}function Km({open:t,pending:s=!1,editingHabit:a,values:r,patterns:i,behaviors:n,beliefs:o,modes:d,reports:c,goals:b,projects:p,tasks:f,onOpenChange:m,onSubmit:x}){const[v,w]=g.useState(Ka),[h,P]=g.useState(null),[T,O]=g.useState({});g.useEffect(()=>{t&&(w(a?qm(a):Ka),P(null),O({}))},[a,t]);const y=g.useMemo(()=>n.slice().sort((u,M)=>u.title.localeCompare(M.title)),[n]),C=u=>({linkedBehaviorIds:u,linkedBehaviorId:u[0]??""}),l=(u,M)=>u.includes(M)?u.filter(A=>A!==M):[...u,M],N=[{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,M)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Title",error:T.title??null,children:e.jsx(se,{value:u.title,onChange:A=>M({title:A.target.value}),placeholder:"Train lower body"})}),e.jsx(B,{label:"Description",children:e.jsx(ve,{value:u.description,onChange:A=>M({description:A.target.value}),placeholder:"Write the habit description in Markdown. Define what counts, edge cases, and examples."})})]})},{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,M)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Polarity",children:e.jsx(Ke,{value:u.polarity,onChange:A=>M({polarity:A}),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(B,{label:"Frequency",children:e.jsx(Ke,{value:u.frequency,onChange:A=>M({frequency:A}),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(B,{label:"Weekdays",error:T.weekDays??null,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:zm.map(A=>{const I=u.weekDays.includes(A.value);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${I?"bg-white/16 text-white":"bg-white/6 text-white/58 hover:bg-white/10 hover:text-white"}`,onClick:()=>M({weekDays:I?u.weekDays.filter(j=>j!==A.value):[...u.weekDays,A.value].sort()}),children:A.label},A.value)})})}):null,e.jsx(B,{label:"Status",children:e.jsx(Ke,{value:u.status,onChange:A=>M({status:A}),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:"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,M)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Goals",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:b.map(A=>{const I=u.linkedGoalIds.includes(A.id);return e.jsx("button",{type:"button",onClick:()=>M({linkedGoalIds:l(u.linkedGoalIds,A.id)}),children:e.jsx(xe,{kind:"goal",label:A.title,gradient:I,className:I?"":"opacity-75"})},A.id)})})}),e.jsx(B,{label:"Projects",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:p.map(A=>{const I=u.linkedProjectIds.includes(A.id);return e.jsx("button",{type:"button",onClick:()=>M({linkedProjectIds:l(u.linkedProjectIds,A.id)}),children:e.jsx(xe,{kind:"project",label:A.title,gradient:I,className:I?"":"opacity-75"})},A.id)})})}),e.jsx(B,{label:"Tasks",children:e.jsx("div",{className:"flex max-h-48 flex-wrap gap-2 overflow-y-auto",children:f.map(A=>{const I=u.linkedTaskIds.includes(A.id);return e.jsx("button",{type:"button",onClick:()=>M({linkedTaskIds:l(u.linkedTaskIds,A.id)}),children:e.jsx(xe,{kind:"task",label:A.title,gradient:I,className:I?"":"opacity-75",wrap:!0})},A.id)})})}),e.jsx(B,{label:"Values",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:r.map(A=>{const I=u.linkedValueIds.includes(A.id);return e.jsx("button",{type:"button",onClick:()=>M({linkedValueIds:l(u.linkedValueIds,A.id)}),children:e.jsx(xe,{kind:"value",label:A.title,gradient:I,className:I?"":"opacity-75"})},A.id)})})}),e.jsx(B,{label:"Patterns",children:e.jsx("div",{className:"flex max-h-44 flex-wrap gap-2 overflow-y-auto",children:i.map(A=>{const I=u.linkedPatternIds.includes(A.id);return e.jsx("button",{type:"button",onClick:()=>M({linkedPatternIds:l(u.linkedPatternIds,A.id)}),children:e.jsx(xe,{kind:"pattern",label:A.title,gradient:I,className:I?"":"opacity-75",wrap:!0})},A.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,M)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Linked behavior",children:e.jsx("div",{className:"flex max-h-44 flex-wrap gap-2 overflow-y-auto",children:y.map(A=>{const I=u.linkedBehaviorIds.includes(A.id);return e.jsx("button",{type:"button",onClick:()=>M(C(l(u.linkedBehaviorIds,A.id))),children:e.jsx(xe,{kind:"behavior",label:A.title,gradient:I,className:I?"":"opacity-75",wrap:!0})},A.id)})})}),e.jsx(B,{label:"Beliefs",children:e.jsx("div",{className:"flex max-h-44 flex-wrap gap-2 overflow-y-auto",children:o.map(A=>{const I=u.linkedBeliefIds.includes(A.id);return e.jsx("button",{type:"button",onClick:()=>M({linkedBeliefIds:l(u.linkedBeliefIds,A.id)}),children:e.jsx(xe,{kind:"belief",label:A.statement,gradient:I,className:I?"":"opacity-75",wrap:!0})},A.id)})})}),e.jsx(B,{label:"Modes",children:e.jsx("div",{className:"flex max-h-44 flex-wrap gap-2 overflow-y-auto",children:d.map(A=>{const I=u.linkedModeIds.includes(A.id);return e.jsx("button",{type:"button",onClick:()=>M({linkedModeIds:l(u.linkedModeIds,A.id)}),children:e.jsx(xe,{kind:"mode",label:A.title,gradient:I,className:I?"":"opacity-75",wrap:!0})},A.id)})})}),e.jsx(B,{label:"Reports",children:e.jsx("div",{className:"flex max-h-44 flex-wrap gap-2 overflow-y-auto",children:c.map(A=>{const I=u.linkedReportIds.includes(A.id);return e.jsx("button",{type:"button",onClick:()=>M({linkedReportIds:l(u.linkedReportIds,A.id)}),children:e.jsx(xe,{kind:"report",label:A.title,gradient:I,className:I?"":"opacity-75",wrap:!0})},A.id)})})}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[e.jsx(B,{label:"Target count",error:T.targetCount??null,children:e.jsx(se,{type:"number",value:u.targetCount,onChange:A=>M({targetCount:Number(A.target.value)||1})})}),e.jsx(B,{label:"Reward XP",error:T.rewardXp??null,children:e.jsx(se,{type:"number",value:u.rewardXp,onChange:A=>M({rewardXp:Number(A.target.value)||1})})}),e.jsx(B,{label:"Penalty XP",error:T.penaltyXp??null,children:e.jsx(se,{type:"number",value:u.penaltyXp,onChange:A=>M({penaltyXp:Number(A.target.value)||1})})})]})]})}];return e.jsx(He,{open:t,onOpenChange:m,eyebrow:"Habit",title:a?"Edit habit":"Create habit",description:"Habits are recurring commitments or recurring slips with explicit XP consequences.",value:v,onChange:w,steps:N,pending:s,pendingLabel:a?"Save habit":"Create habit",submitLabel:a?"Save habit":"Create habit",error:h,onSubmit:async()=>{P(null);const u=Rd.safeParse(v);if(!u.success){O(Object.fromEntries(Object.entries(u.error.flatten().fieldErrors).map(([M,A])=>[M,A==null?void 0:A[0]]))),P("Some habit fields still need attention.");return}O({});try{await x(u.data,a==null?void 0:a.id),w(Ka),m(!1)}catch(M){P(M instanceof Error?M.message:"Habit update failed.")}}})}const Um=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function Qm(t){return t.frequency==="daily"?`${t.targetCount}x daily`:`${t.targetCount}x weekly · ${t.weekDays.map(s=>Um[s]).join(", ")}`}function Xm(){var T,O,y,C,l,N;const t=Xe(),s=Qe(),[a,r]=ut(),[i,n]=g.useState(null),[o,d]=g.useState(!1),[c,b]=g.useState(null),p=oe({queryKey:["forge-habits"],queryFn:async()=>(await Lc()).habits}),f=oe({queryKey:["forge-psyche-overview"],queryFn:async()=>(await ka()).overview});g.useEffect(()=>{a.get("create")==="1"&&(n(null),d(!0),r(u=>{const M=new URLSearchParams(u);return M.delete("create"),M},{replace:!0}))},[a,r]);const m=async()=>{await s.invalidateQueries({queryKey:["forge-habits"]}),await t.refresh()},x=ue({mutationFn:async({input:u,habitId:M})=>M?(await Oc(M,u)).habit:(await Fc(u)).habit,onSuccess:async()=>{b(null),await m()},onError:u=>{b(u instanceof Error?u.message:"Habit save failed.")}}),v=ue({mutationFn:async({habitId:u,status:M})=>_c(u,{status:M}),onSuccess:async()=>{b(null),await m()},onError:u=>{b(u instanceof Error?u.message:"Habit check-in failed.")}}),w=ue({mutationFn:async u=>Rc(u),onSuccess:async()=>{b(null),await m()},onError:u=>{b(u instanceof Error?u.message:"Habit delete failed.")}}),h=g.useMemo(()=>(p.data??[]).filter(u=>u.status!=="archived"),[p.data]),P=g.useMemo(()=>h.filter(u=>u.dueToday),[h]);if(p.error)throw p.error;return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Fe,{entityKind:"habit",title:e.jsx(Te,{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:`${h.length} habits`,actions:e.jsxs(K,{onClick:()=>{n(null),d(!0)},children:[e.jsx(Gt,{className:"size-4"}),"New habit"]})}),c?e.jsx(Z,{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(zr,{className:"mt-0.5 size-4 shrink-0"}),e.jsx("div",{children:c})]})}):null,e.jsxs("section",{className:"grid gap-4 lg:grid-cols-3",children:[e.jsxs(Z,{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:P.length}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Habits that still need a check-in today."})]}),e.jsxs(Z,{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-white",children:Math.max(0,...h.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(Z,{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:[h.length>0?Math.round(h.reduce((u,M)=>u+M.completionRate,0)/h.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."})]})]}),p.isLoading?e.jsx(Z,{children:"Loading habits..."}):h.length===0?e.jsx(rt,{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(K,{onClick:()=>{n(null),d(!0)},children:"Create habit"})}):e.jsx("div",{className:"grid gap-4 xl:grid-cols-2",children:h.map(u=>e.jsxs(Z,{className:te("overflow-hidden",u.dueToday&&"border-teal-300/20 shadow-[0_0_0_1px_rgba(45,212,191,0.12)]"),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(Te,{kind:"habit",label:u.title,variant:"heading",size:"sm"}),e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:u.status}),e.jsx(_,{className:u.polarity==="positive"?"bg-emerald-400/12 text-emerald-200":"bg-rose-400/12 text-rose-200",children:u.polarity==="positive"?"Positive":"Negative"})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:u.description?e.jsx(mt,{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:"text-right",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/35",children:"Alignment"}),e.jsxs("div",{className:"mt-1 text-lg font-semibold text-white",children:[u.completionRate,"%"]})]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsxs(_,{className:"bg-white/[0.08] text-white/72",children:[e.jsx(Ct,{className:"mr-1 size-3.5"}),Qm(u)]}),e.jsxs(_,{className:"bg-white/[0.08] text-white/72",children:["Streak ",u.streakCount]}),e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:u.polarity==="positive"?`+${u.rewardXp} XP done`:`+${u.rewardXp} XP resisted`}),e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:u.polarity==="positive"?`-${u.penaltyXp} XP missed`:`-${u.penaltyXp} XP performed`}),u.linkedBehaviorTitles.slice(0,2).map(M=>e.jsxs(_,{className:"bg-orange-400/12 text-orange-100",children:[e.jsx(na,{className:"mr-1 size-3.5"}),M]},M)),u.linkedGoalIds.slice(0,2).map(M=>{const A=t.snapshot.goals.find(I=>I.id===M);return A?e.jsxs(_,{className:"bg-amber-400/12 text-amber-100",children:["Goal · ",A.title]},A.id):null}),u.linkedProjectIds.slice(0,2).map(M=>{const A=t.snapshot.dashboard.projects.find(I=>I.id===M);return A?e.jsxs(_,{className:"bg-sky-400/12 text-sky-100",children:["Project · ",A.title]},A.id):null}),u.linkedTaskIds.slice(0,2).map(M=>{const A=t.snapshot.tasks.find(I=>I.id===M);return A?e.jsxs(_,{className:"bg-indigo-400/12 text-indigo-100",children:["Task · ",A.title]},A.id):null}),u.linkedValueIds.slice(0,2).map(M=>{var I;const A=(I=f.data)==null?void 0:I.values.find(j=>j.id===M);return A?e.jsxs(_,{className:"bg-emerald-400/12 text-emerald-100",children:["Value · ",A.title]},A.id):null}),u.linkedPatternIds.slice(0,2).map(M=>{var I;const A=(I=f.data)==null?void 0:I.patterns.find(j=>j.id===M);return A?e.jsxs(_,{className:"bg-cyan-400/12 text-cyan-100",children:["Pattern · ",A.title]},A.id):null}),u.linkedBeliefIds.slice(0,2).map(M=>{var I;const A=(I=f.data)==null?void 0:I.beliefs.find(j=>j.id===M);return A?e.jsxs(_,{className:"bg-rose-400/12 text-rose-100",children:["Belief · ",A.statement]},A.id):null}),u.linkedModeIds.slice(0,2).map(M=>{var I;const A=(I=f.data)==null?void 0:I.modes.find(j=>j.id===M);return A?e.jsxs(_,{className:"bg-violet-400/12 text-violet-100",children:["Mode · ",A.title]},A.id):null}),u.linkedReportIds.slice(0,2).map(M=>{var I;const A=(I=f.data)==null?void 0:I.reports.find(j=>j.id===M);return A?e.jsxs(_,{className:"bg-fuchsia-400/12 text-fuchsia-100",children:["Report · ",A.title]},A.id):null})]}),e.jsxs("div",{className:"mt-5 grid gap-3 sm:grid-cols-[1fr_auto_auto_auto] sm:items-center",children:[e.jsxs("div",{className:"text-sm text-white/58",children:[u.lastCheckInAt?`Last check-in ${u.lastCheckInStatus==="done"?"marked done":"marked missed"} on ${u.lastCheckInAt.slice(0,10)}.`:"No check-ins recorded yet.",e.jsx("div",{className:"mt-3",children:e.jsx(Ze,{entityType:"habit",entityId:u.id,count:at(t.snapshot.dashboard.notesSummaryByEntity,"habit",u.id).count})})]}),e.jsx(K,{variant:u.polarity==="positive"?"primary":"secondary",disabled:v.isPending,onClick:()=>void v.mutateAsync({habitId:u.id,status:"done"}),children:u.polarity==="positive"?"Done":"Performed"}),e.jsx(K,{variant:u.polarity==="negative"?"primary":"secondary",disabled:v.isPending,onClick:()=>void v.mutateAsync({habitId:u.id,status:"missed"}),children:u.polarity==="positive"?"Missed":"Resisted"}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(K,{variant:"secondary",disabled:x.isPending,onClick:()=>{n(u),d(!0)},children:"Edit"}),e.jsx(K,{variant:"ghost",disabled:w.isPending,onClick:()=>{window.confirm(`Delete habit "${u.title}"?`)&&w.mutateAsync(u.id)},children:e.jsx(bt,{className:"size-4"})})]})]})]},u.id))}),e.jsx(Km,{open:o,pending:x.isPending,editingHabit:i,values:((T=f.data)==null?void 0:T.values)??[],patterns:((O=f.data)==null?void 0:O.patterns)??[],behaviors:((y=f.data)==null?void 0:y.behaviors)??[],beliefs:((C=f.data)==null?void 0:C.beliefs)??[],modes:((l=f.data)==null?void 0:l.modes)??[],reports:((N=f.data)==null?void 0:N.reports)??[],goals:t.snapshot.dashboard.goals,projects:t.snapshot.dashboard.projects,tasks:t.snapshot.tasks,onOpenChange:d,onSubmit:async(u,M)=>{try{await x.mutateAsync({input:u,habitId:M})}catch(A){throw A instanceof ja,A}}})]})}const Gm={title:"",description:"",owner:"Albert",goalId:"",projectId:"",priority:"medium",status:"focus",effort:"deep",energy:"steady",dueDate:"",points:60,tagIds:[],notes:[]},Wm={goalId:"",title:"",description:"",status:"active",targetPoints:240,themeColor:"#c0c1ff",notes:[]},Hm={title:"",description:"",horizon:"year",status:"active",targetPoints:400,themeColor:"#c8a46b",tagIds:[],notes:[]},Ym=["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 Jm(t){return t!==null&&Ym.includes(t)}function Ai(t,s,a=96){const r=t.trim()||s.trim();return r.length<=a?r:`${r.slice(0,a-1).trimEnd()}…`}function Vm(t){return[t.summary.trim(),t.rationale.trim()?`Why it matters: ${t.rationale.trim()}`:""].filter(Boolean).join(`
4
+
5
+ `)}function Di(t){return!Jm(t.entityType)||!t.entityId?null:{entityType:t.entityType,entityId:t.entityId,anchorKey:null}}function Eo(t,s,a){var r,i;return t.entityType==="goal"&&t.entityId?t.entityId:t.entityType==="project"&&t.entityId?((r=s.find(n=>n.id===t.entityId))==null?void 0:r.goalId)??"":t.entityType==="task"&&t.entityId?((i=a.find(n=>n.id===t.entityId))==null?void 0:i.goalId)??"":""}function Zm(t,s){var a;return t.entityType==="project"&&t.entityId?t.entityId:t.entityType==="task"&&t.entityId?((a=s.find(r=>r.id===t.entityId))==null?void 0:a.projectId)??"":""}function Lo(t,s,a){const r=[];return a.length>0&&r.push("task"),s.length>0&&r.push("project"),r.push("goal"),Di(t)&&r.push("note"),r}function eh(t,s,a){const r=Lo(t,s,a);return r.includes("task")&&(t.entityType==="task"||t.entityType==="project")?"task":r.includes("project")&&t.entityType==="goal"?"project":r[0]??"goal"}function th(t,s,a){var d,c,b;const r=Eo(t,s,a),n=Zm(t,a)||(r?((d=s.find(p=>p.goalId===r))==null?void 0:d.id)??"":"")||((c=s[0])==null?void 0:c.id)||"",o=n?((b=s.find(p=>p.id===n))==null?void 0:b.goalId)??r:r;return{...Gm,title:Ai(t.recommendation,t.title),description:Vm(t),goalId:o,projectId:n}}function sh(t,s,a,r){var o;const n=Eo(t,a,r)||((o=s[0])==null?void 0:o.id)||"";return{...Wm,goalId:n,title:Ai(t.title,t.recommendation),description:`${t.summary.trim()}
6
+
7
+ Recommendation: ${t.recommendation.trim()}`.trim()}}function ah(t){return{...Hm,title:Ai(t.title,t.recommendation),description:`${t.summary.trim()}
8
+
9
+ Recommendation: ${t.recommendation.trim()}`.trim()}}function ih(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 rr(t,s,a,r){return{kind:eh(t,s,a),task:th(t,a,r),project:sh(t,s,a,r),goal:ah(t),noteMarkdown:ih(t)}}function nh(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 rh({open:t,onOpenChange:s,insight:a,goals:r,projects:i,tasks:n,tags:o,pending:d=!1,onSubmit:c}){const b=g.useMemo(()=>Lo(a,r,i),[r,a,i]),p=g.useMemo(()=>Di(a),[a]),[f,m]=g.useState(()=>rr(a,r,i,n)),[x,v]=g.useState(null),[w,h]=g.useState({});g.useEffect(()=>{t&&(m(rr(a,r,i,n)),v(null),h({}))},[r,a,t,i,n]);const P=f.task.projectId?i.find(C=>C.id===f.task.projectId)??null:null;g.useEffect(()=>{P&&f.task.goalId!==P.goalId&&m(C=>({...C,task:{...C.task,goalId:P.goalId}}))},[f.task.goalId,P]);const T=f.project.goalId?r.find(C=>C.id===f.project.goalId)??null:null,O=g.useMemo(()=>{var C,l,N;if(!p)return null;switch(p.entityType){case"goal":return((C=r.find(u=>u.id===p.entityId))==null?void 0:C.title)??"Linked goal";case"project":return((l=i.find(u=>u.id===p.entityId))==null?void 0:l.title)??"Linked project";case"task":return((N=n.find(u=>u.id===p.entityId))==null?void 0:N.title)??"Linked task";default:return`${p.entityType.replaceAll("_"," ")}`}},[r,i,p,n]),y=[{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:(C,l)=>e.jsx(B,{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(Ke,{value:C.kind,onChange:N=>l({kind:N}),options:b.map(N=>({value:N,...nh(N)})),columns:b.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:(C,l)=>C.kind==="task"?e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Task title",error:w.title??null,children:e.jsx(se,{value:C.task.title,onChange:N=>l({task:{...C.task,title:N.target.value}}),placeholder:"Turn the recommendation into a task"})}),e.jsx(B,{label:"Description",children:e.jsx(ve,{value:C.task.description,onChange:N=>l({task:{...C.task,description:N.target.value}}),placeholder:"Add the operational context for this task."})}),e.jsx(B,{label:"Project",error:w.projectId??null,children:e.jsx("div",{className:"grid gap-3",children:i.map(N=>{const u=N.id===C.task.projectId;return e.jsxs("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${u?"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:()=>l({task:{...C.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(xe,{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(B,{label:"Owner",error:w.owner??null,children:e.jsx(se,{value:C.task.owner,onChange:N=>l({task:{...C.task,owner:N.target.value}}),placeholder:"Albert"})}),e.jsx(B,{label:"Tags",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:o.map(N=>{const u=C.task.tagIds.includes(N.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${u?"bg-white/16 text-white":"bg-white/6 text-white/58 hover:bg-white/10 hover:text-white"}`,onClick:()=>l({task:{...C.task,tagIds:u?C.task.tagIds.filter(M=>M!==N.id):[...C.task.tagIds,N.id]}}),children:N.name},N.id)})})})]}):C.kind==="project"?e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Project title",error:w.title??null,children:e.jsx(se,{value:C.project.title,onChange:N=>l({project:{...C.project,title:N.target.value}}),placeholder:"Turn the insight into a project"})}),e.jsx(B,{label:"Description",children:e.jsx(ve,{value:C.project.description,onChange:N=>l({project:{...C.project,description:N.target.value}}),placeholder:"Describe the initiative this insight points to."})}),e.jsx(B,{label:"Goal",error:w.goalId??null,children:e.jsx("div",{className:"grid gap-3",children:r.map(N=>{const u=N.id===C.project.goalId;return e.jsxs("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${u?"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:()=>l({project:{...C.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)})})}),T?e.jsxs(Ot,{children:["This project will sit under the “",T.title,"” goal."]}):null]}):C.kind==="goal"?e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Goal title",error:w.title??null,children:e.jsx(se,{value:C.goal.title,onChange:N=>l({goal:{...C.goal,title:N.target.value}}),placeholder:"Turn the insight into a life goal"})}),e.jsx(B,{label:"Description",children:e.jsx(ve,{value:C.goal.description,onChange:N=>l({goal:{...C.goal,description:N.target.value}}),placeholder:"Describe the strategic direction this insight suggests."})}),e.jsx(B,{label:"Tags",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:o.map(N=>{const u=C.goal.tagIds.includes(N.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${u?"bg-white/16 text-white":"bg-white/6 text-white/58 hover:bg-white/10 hover:text-white"}`,onClick:()=>l({goal:{...C.goal,tagIds:u?C.goal.tagIds.filter(M=>M!==N.id):[...C.goal.tagIds,N.id]}}),children:N.name},N.id)})})})]}):e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Linked note",description:"This stores the insight as durable Markdown evidence on the linked entity instead of creating a new work item.",hint:O?`This note will attach to ${O}.`:void 0,children:e.jsx(ve,{value:C.noteMarkdown,onChange:N=>l({noteMarkdown:N.target.value}),placeholder:"Write the applied note content in Markdown",className:"min-h-64"})}),O?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:O})]}):null]})}];return e.jsx(He,{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:f,onChange:m,steps:y,submitLabel:"Apply insight",pending:d,error:x,onSubmit:async()=>{v(null),h({});try{if(f.kind==="task"){const C=Vr.safeParse(f.task);if(!C.success){h(Object.fromEntries(Object.entries(C.error.flatten().fieldErrors).map(([l,N])=>[l,N==null?void 0:N[0]]))),v("This applied task still needs a valid title, project, and owner.");return}await c({kind:"task",input:C.data}),s(!1);return}if(f.kind==="project"){const C=Jr.safeParse(f.project);if(!C.success){h(Object.fromEntries(Object.entries(C.error.flatten().fieldErrors).map(([l,N])=>[l,N==null?void 0:N[0]]))),v("This applied project still needs a valid title and goal.");return}await c({kind:"project",input:C.data}),s(!1);return}if(f.kind==="goal"){const C=Yr.safeParse(f.goal);if(!C.success){h(Object.fromEntries(Object.entries(C.error.flatten().fieldErrors).map(([l,N])=>[l,N==null?void 0:N[0]]))),v("This applied goal still needs a valid title and target.");return}await c({kind:"goal",input:C.data}),s(!1);return}if(!f.noteMarkdown.trim()){v("The linked note needs Markdown content before it can be saved.");return}if(!p){v("This insight is not attached to a specific entity yet, so Forge cannot place a linked note for it.");return}await c({kind:"note",input:{contentMarkdown:f.noteMarkdown.trim()}}),s(!1)}catch(C){v(C instanceof Error?C.message:"Unable to apply this insight right now.")}}})}function or(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 Fo({open:t,onOpenChange:s,title:a="Store insight",description:r="Capture a clear observation, its recommendation, and where it belongs without dropping into a raw admin form.",eyebrow:i="Insight",pending:n=!1,submitLabel:o="Store insight",initialValue:d,lockedEntity:c,entityCandidates:b=[],onSubmit:p}){const[f,m]=g.useState(()=>or(d,c)),[x,v]=g.useState(null);g.useEffect(()=>{t&&(m(or(d,c)),v(null))},[d,c,t]);const w=g.useMemo(()=>{const T=new Set(["general"]);return b.forEach(O=>T.add(O.entityType)),c&&T.add(c.entityType),Array.from(T)},[b,c]),h=b.filter(T=>T.entityType===f.targetKind),P=[{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:(T,O)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{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(se,{value:T.title,onChange:y=>O({title:y.target.value}),placeholder:"Weekly review needs a tighter end ritual"})}),e.jsx(B,{label:"Timeframe",description:"Keep the horizon short and readable.",children:e.jsx(se,{value:T.timeframeLabel,onChange:y=>O({timeframeLabel:y.target.value}),placeholder:"This week"})}),e.jsx(B,{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:c?e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx(xe,{kind:c.kind,label:c.label}),c.description?e.jsx(Ot,{className:"mt-2",children:c.description}):null]}):e.jsxs(e.Fragment,{children:[e.jsx(Ke,{value:T.targetKind,onChange:y=>O({targetKind:y,entityType:y==="general"?"":y,entityId:""}),options:w.map(y=>({value:y,label:y==="general"?"General insight":y==="trigger_report"?"Report":y.charAt(0).toUpperCase()+y.slice(1),description:y==="general"?"Store it in the broader insight feed.":`Attach it to a specific ${y==="trigger_report"?"report":y}.`})),columns:w.length>=3?3:2}),T.targetKind!=="general"?h.length>0?e.jsx("div",{className:"mt-4 grid gap-3 md:grid-cols-2",children:h.map(y=>{const C=T.entityType===y.entityType&&T.entityId===y.entityId;return e.jsxs("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${C?"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:()=>O({entityType:y.entityType,entityId:y.entityId}),children:[e.jsx(xe,{kind:y.kind,label:y.label,compact:!0}),y.description?e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:y.description}):null]},`${y.entityType}:${y.entityId}`)})}):e.jsxs(Ot,{className:"mt-4",children:["No ",T.targetKind==="trigger_report"?"reports":`${T.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:(T,O)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{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(ve,{value:T.summary,onChange:y=>O({summary:y.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(B,{label:"Why this matters",description:"Optional context that helps explain the recommendation.",children:e.jsx(ve,{value:T.rationale,onChange:y=>O({rationale:y.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:(T,O)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{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(ve,{value:T.recommendation,onChange:y=>O({recommendation:y.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(B,{label:"Confidence",description:"Choose how strongly this recommendation holds up right now.",children:e.jsx(Ke,{value:String(T.confidence),onChange:y=>O({confidence:Number(y)}),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(He,{open:t,onOpenChange:s,eyebrow:i,title:a,description:r,value:f,onChange:m,steps:P,submitLabel:o,pending:n,error:x,onSubmit:async()=>{v(null);const T=Od.safeParse({originType:f.originType,originAgentId:f.originAgentId,originLabel:f.originLabel,entityType:f.targetKind==="general"?"":f.entityType,entityId:f.targetKind==="general"?"":f.entityId,timeframeLabel:f.timeframeLabel,title:f.title,summary:f.summary,recommendation:f.recommendation,rationale:f.rationale,confidence:f.confidence,ctaLabel:f.ctaLabel});if(!T.success){v("This insight still needs a title, a summary, and a recommendation before it can be stored.");return}try{await p(T.data),s(!1)}catch(O){v(O instanceof Error?O.message:"Unable to store this insight right now.")}}})}function oh(){var T,O,y,C;const t=Qe(),s=ht(),{snapshot:a}=Xe(),[r,i]=g.useState(!1),[n,o]=g.useState(null),d=oe({queryKey:["forge-insights"],queryFn:sc}),c=ue({mutationFn:lo,onSuccess:async()=>{await t.invalidateQueries({queryKey:["forge-insights"]})}}),b=ue({mutationFn:({insightId:l,feedbackType:N})=>_n(l,N),onSuccess:async()=>{await t.invalidateQueries({queryKey:["forge-insights"]})}}),p=ue({mutationFn:({insightId:l})=>hc(l),onMutate:async({insightId:l})=>{await t.cancelQueries({queryKey:["forge-insights"]});const N=t.getQueryData(["forge-insights"]);if(N){const u=N.insights.feed.find(M=>M.id===l);t.setQueryData(["forge-insights"],{insights:{...N.insights,feed:N.insights.feed.filter(M=>M.id!==l),openCount:(u==null?void 0:u.status)==="open"?Math.max(0,N.insights.openCount-1):N.insights.openCount}})}return{previous:N}},onError:(l,N,u)=>{u!=null&&u.previous&&t.setQueryData(["forge-insights"],u.previous)},onSettled:async()=>{await t.invalidateQueries({queryKey:["forge-insights"]})}}),f=ue({mutationFn:async({insight:l,submission:N})=>{let u=null,M="Applied the insight.";if(N.kind==="task"){const A=await ii(N.input);u=`/tasks/${A.task.id}`,M=`Created task: ${A.task.title}`}else if(N.kind==="project"){const A=await uo(N.input);u=`/projects/${A.project.id}`,M=`Created project: ${A.project.title}`}else if(N.kind==="goal"){const A=await ho(N.input);u=`/goals/${A.goal.id}`,M=`Created goal: ${A.goal.title}`}else{const A=Di(l);if(!A)throw new Error("This insight is not linked to a concrete entity yet, so Forge cannot attach a linked note to it.");await Ci({contentMarkdown:N.input.contentMarkdown,links:[A]}),u=Io(A.entityType,A.entityId),M="Created a linked note from the insight."}return await _n(l.id,"applied",M),{href:u}},onSuccess:async({href:l})=>{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),l&&s(l)}}),m=(T=d.data)==null?void 0:T.insights,x=g.useMemo(()=>[...a.goals.slice(0,8).map(l=>({entityType:"goal",entityId:l.id,kind:"goal",label:l.title,description:l.description})),...a.projects.slice(0,8).map(l=>({entityType:"project",entityId:l.id,kind:"project",label:l.title,description:l.goalTitle})),...a.tasks.slice(0,10).map(l=>({entityType:"task",entityId:l.id,kind:"task",label:l.title,description:l.status.replaceAll("_"," ")}))],[a.goals,a.projects,a.tasks]),v=b.isPending?((O=b.variables)==null?void 0:O.insightId)??null:null,w=p.isPending?((y=p.variables)==null?void 0:y.insightId)??null:null,h=f.isPending?((C=f.variables)==null?void 0:C.insight.id)??null:null,P=a.metrics.topGoalId?a.goals.find(l=>l.id===a.metrics.topGoalId)??null:null;return d.isLoading?e.jsx(pt,{eyebrow:"Insights",title:"Loading the insight feed",description:"Pulling coaching, momentum analysis, and stored recommendations."}):d.isError||!m?e.jsx(Le,{eyebrow:"Insights",error:d.error,onRetry:()=>void t.invalidateQueries({queryKey:["forge-insights"]})}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Fe,{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:`${m.openCount} open`,actions:e.jsx(K,{onClick:()=>i(!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(Z,{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:m.momentumHeatmap.map(l=>e.jsxs("div",{className:"rounded-[16px] bg-white/[0.04] p-3",children:[e.jsx("div",{className:"h-12 rounded-[12px]",style:{background:l.intensity>=4?"rgba(192,193,255,0.95)":l.intensity===3?"rgba(192,193,255,0.7)":l.intensity===2?"rgba(192,193,255,0.45)":l.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:l.label})]},l.id))})]}),e.jsxs(Z,{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(Oe,{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(Xr,{width:"100%",height:"100%",minWidth:280,minHeight:288,children:e.jsxs(od,{data:m.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(Gr,{dataKey:"label",tick:{fill:"rgba(255,255,255,0.42)",fontSize:11}}),e.jsx(Wr,{hide:!0}),e.jsx(jn,{dataKey:"xp",stroke:"#c0c1ff",fill:"url(#insight-xp)",strokeWidth:2}),e.jsx(jn,{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(Oe,{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(Oe,{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(Z,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_,{className:"bg-white/[0.08] text-white/60",children:"Deterministic coaching"}),e.jsx(Oe,{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:m.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:m.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:m.coaching.recommendation}),P?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:P.title})]}),e.jsx(K,{variant:"secondary",size:"sm",onClick:()=>s(`/goals/${P.id}`),children:"Open goal"})]}):null]})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(Z,{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(K,{onClick:()=>i(!0),children:"Store insight"})})]})]}),e.jsxs(Z,{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:m.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."}):m.feed.map(l=>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:l.title}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:l.summary})]}),e.jsx(_,{className:"text-white/70",children:l.status})]}),e.jsx("div",{className:"mt-3 text-sm text-white/58",children:l.recommendation}),e.jsxs("div",{className:"mt-3 text-xs uppercase tracking-[0.16em] text-white/38",children:[l.originLabel??l.originType," · confidence ",Math.round(l.confidence*100),"%"]}),l.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:l.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:[l.status!=="accepted"?e.jsx(K,{variant:"secondary",pending:v===l.id,onClick:()=>void b.mutateAsync({insightId:l.id,feedbackType:"accepted"}),children:"Accept"}):null,e.jsx(K,{pending:h===l.id,onClick:()=>o(l),children:"Apply"}),e.jsx(K,{variant:"ghost",pending:w===l.id,onClick:()=>void p.mutateAsync({insightId:l.id}),children:"Dismiss"})]})]})]},l.id))})]})]})]}),e.jsx(Fo,{open:r,onOpenChange:i,entityCandidates:x,pending:c.isPending,onSubmit:async l=>{await c.mutateAsync(l)}}),n?e.jsx(rh,{open:!!n,onOpenChange:l=>{l||o(null)},insight:n,goals:a.goals,projects:a.projects,tasks:a.tasks,tags:a.tags,pending:f.isPending,onSubmit:async l=>{await f.mutateAsync({insight:n,submission:l})}}):null]})}const kt=["backlog","focus","in_progress","blocked","done"];function Oo(t){return t.startsWith("lane:")||t.includes(":lane:")}function lh(t){var s,a;return((a=(s=t.data)==null?void 0:s.current)==null?void 0:a.type)==="lane"||Oo(String(t.id))}function dh(t,s){const a=Math.max(0,Math.min(t.right,s.right)-Math.max(t.left,s.left)),r=Math.max(0,Math.min(t.bottom,s.bottom)-Math.max(t.top,s.top));return a*r}const ch=t=>{const s=pd(t),a=s.find(n=>Oo(String(n.id)));if(a)return[a];const i=t.droppableContainers.filter(n=>lh(n)).map(n=>{const o=t.droppableRects.get(n.id);if(!o)return null;const d=dh(t.collisionRect,o);return d<=0?null:{id:n.id,data:{droppableContainer:n,value:d}}}).filter(Boolean).sort((n,o)=>{var d,c;return(((d=o==null?void 0:o.data)==null?void 0:d.value)??0)-(((c=n==null?void 0:n.data)==null?void 0:c.value)??0)});return i.length>0?i:s.length>0?s:xd(t)};function Ro({task:t,goal:s,tags:a,isSelected:r,isDragging:i=!1,isOverlay:n=!1,style:o,setNodeRef:d,dragAttributes:c,dragListeners:b,isMobile:p=!1,onSelect:f,onStartTask:m,onQuickReopen:x,onStepTask:v,onOpenTask:w,onEditTask:h,notesSummaryByEntity:P}){const{t:T,formatDate:O}=qe(),y=kt[kt.indexOf(t.status)-1]??null,C=kt[kt.indexOf(t.status)+1]??null,l=at(P,"task",t.id).count;return e.jsxs("article",{ref:d,style:o,className:te("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",p&&"touch-none select-none",n&&"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)]",i&&!n&&"opacity-35 shadow-[inset_0_0_0_1px_rgba(255,255,255,0.02)]",r?"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":i?"true":"false","data-testid":`task-card-${t.id}`,onClick:()=>f(t.id),...c,...b,children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx(_,{className:"shrink-0 text-[11px] text-[var(--tertiary)]",children:t.priority}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[h?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(),h(t.id)},children:e.jsx(Ss,{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(Is,{className:"size-3.5"})}):null,p?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:!y,onClick:()=>{y&&(v==null||v(t.id,"previous"))},children:e.jsx(qr,{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:!C,onClick:()=>{C&&(v==null||v(t.id,"next"))},children:e.jsx(Kr,{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(Et,{className:"size-4 fill-current"})}):null,e.jsxs("span",{className:"text-[11px] text-white/44",children:[t.points," xp"]})]})]}),e.jsx(Te,{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||T("common.executionBoard.noExecutionNote")}),e.jsxs("div",{className:"mt-2.5 flex min-w-0 flex-wrap gap-1.5",children:[s?e.jsx(xe,{kind:"goal",label:s.title,compact:!0,wrap:!0,className:"min-w-0 max-w-full"}):null,e.jsx(Ze,{entityType:"task",entityId:t.id,count:l}),t.time.totalCreditedSeconds>0?e.jsxs(_,{className:"bg-white/8 text-white/72",children:[Math.floor(t.time.totalCreditedSeconds/60)," min"]}):null,t.time.activeRunCount>0?e.jsxs(_,{className:"bg-emerald-500/12 text-emerald-200",children:[t.time.activeRunCount," live"]}):null,a.slice(0,2).map(N=>e.jsx(_,{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"&&x?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(),x(t.id)},children:T("common.executionBoard.reopen")}):null,e.jsx("span",{children:O(t.dueDate)})]})]})]})}function lr(t){const{task:s,sortableId:a}=t,{attributes:r,listeners:i,setNodeRef:n,transform:o,transition:d,isDragging:c}=bd({id:a,data:{type:"task",taskId:s.id,status:s.status}});return e.jsx(Ro,{...t,setNodeRef:n,dragAttributes:r,dragListeners:i,isDragging:c,isMobile:t.isMobile,onStartTask:t.onStartTask,onStepTask:t.onStepTask,notesSummaryByEntity:t.notesSummaryByEntity,style:{transform:vd.Transform.toString(o),transition:d}})}function dr({droppableId:t,status:s,title:a,detail:r,count:i,dragging:n,children:o}){const{setNodeRef:d,isOver:c}=fd({id:t,data:{type:"lane",status:s}});return e.jsx("div",{ref:d,className:te("w-full max-w-full min-w-0 overflow-hidden rounded-[24px] transition",c&&"scale-[1.005]"),"data-lane-id":s,"data-testid":`kanban-lane-${s}`,"data-lane-hover":c?"true":"false",children:e.jsxs(Z,{className:te("h-full w-full max-w-full min-w-0 overflow-hidden p-3 transition-[background-color,box-shadow,border-color,transform]",n&&"border border-white/8",c?"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:r}),e.jsx("h3",{className:"mt-1 break-words text-[1.45rem] leading-[1] text-white",children:a})]}),e.jsx("div",{className:"shrink-0 font-display text-[1.45rem] text-[var(--primary)]",children:i})]}),e.jsx("div",{className:te("grid w-full max-w-full min-w-0 min-h-48 content-start gap-2 rounded-[18px] p-2 transition",c?"bg-[rgba(125,211,252,0.08)]":"bg-white/[0.02]"),children:o})]})})}function _o({tasks:t,goals:s,tags:a,selectedTaskId:r,onMove:i,onSelectTask:n,onStartTask:o,onQuickReopenTask:d,onOpenTask:c,onEditTask:b,notesSummaryByEntity:p}){const{t:f}=qe(),m=g.useId(),[x,v]=g.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(max-width: 1023px)").matches),w=cd(md(gd,{activationConstraint:{distance:6}})),[h,P]=g.useState(null),[T,O]=g.useState({}),y={backlog:{title:f("common.executionBoard.laneBacklogTitle"),detail:f("common.executionBoard.laneBacklogDetail")},focus:{title:f("common.executionBoard.laneFocusTitle"),detail:f("common.executionBoard.laneFocusDetail")},in_progress:{title:f("common.executionBoard.laneProgressTitle"),detail:f("common.executionBoard.laneProgressDetail")},blocked:{title:f("common.executionBoard.laneBlockedTitle"),detail:f("common.executionBoard.laneBlockedDetail")},done:{title:f("common.executionBoard.laneDoneTitle"),detail:f("common.executionBoard.laneDoneDetail")}},C=g.useMemo(()=>t.map(j=>{const S=T[j.id];return S?{...j,status:S}:j}),[T,t]),l=h?C.find(j=>j.id===h)??null:null,N=l?s.find(j=>j.id===l.goalId):void 0,u=l?l.tagIds.map(j=>a.find(S=>S.id===j)).filter(Boolean):[];g.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const j=window.matchMedia("(max-width: 1023px)"),S=E=>{v(E?E.matches:j.matches)};return S(),typeof j.addEventListener=="function"?(j.addEventListener("change",S),()=>j.removeEventListener("change",S)):(j.addListener(S),()=>j.removeListener(S))},[]),g.useEffect(()=>{if(!h){document.body.style.cursor="";return}return document.body.style.cursor="grabbing",()=>{document.body.style.cursor=""}},[h]),g.useEffect(()=>{O(j=>{const S=new Set(t.map(G=>G.id));let E=!1;const X={};for(const[G,z]of Object.entries(j)){const D=t.find(F=>F.id===G);if(!S.has(G)||!D||D.status===z){E=!0;continue}X[G]=z}return E?X:j})},[t]);function M(j){var E;const S=(E=j.active.data.current)==null?void 0:E.taskId;typeof S=="string"&&P(S)}async function A(j){var q,Y,L,V;const{active:S,over:E}=j;if(P(null),!E||S.id===E.id)return;const X=typeof((q=S.data.current)==null?void 0:q.taskId)=="string"?S.data.current.taskId:String(S.id),G=C.find(le=>le.id===X);if(!G)return;const z=typeof((Y=E.data.current)==null?void 0:Y.status)=="string"?E.data.current.status:null,D=typeof((L=E.data.current)==null?void 0:L.taskId)=="string"?E.data.current.taskId:String(E.id),F=z??((V=C.find(le=>le.id===D))==null?void 0:V.status)??G.status;if(F!==G.status&&kt.includes(F)){O(le=>({...le,[G.id]:F}));try{await i(G.id,F)}catch(le){throw O(ce=>{const he={...ce};return delete he[G.id],he}),le}}}async function I(j,S){const E=C.find(D=>D.id===j);if(!E)return;const X=kt.indexOf(E.status),G=S==="previous"?X-1:X+1,z=kt[G]??null;if(!(!z||z===E.status)){O(D=>({...D,[E.id]:z}));try{await i(E.id,z)}catch(D){throw O(F=>{const q={...F};return delete q[E.id],q}),D}}}return e.jsxs(hd,{sensors:w,collisionDetection:ch,onDragStart:M,onDragCancel:()=>P(null),onDragEnd:j=>void A(j),children:[e.jsx("div",{className:"w-full max-w-full min-w-0 pb-2",children:x?e.jsx("div",{className:"grid w-full max-w-full min-w-0 gap-2",children:kt.map(j=>{const S=C.filter(E=>E.status===j);return e.jsx(kn,{items:S.map(E=>`${m}:task:${E.id}`),strategy:Nn,children:e.jsxs(dr,{droppableId:`${m}:lane:${j}`,status:j,title:y[j].title,detail:y[j].detail,count:S.length,dragging:h!==null,children:[S.map(E=>e.jsx(lr,{sortableId:`${m}:task:${E.id}`,task:E,goal:s.find(X=>X.id===E.goalId),tags:E.tagIds.map(X=>a.find(G=>G.id===X)).filter(Boolean),isSelected:r===E.id,isMobile:!0,onSelect:n,onStartTask:o,onQuickReopen:d,onStepTask:I,onOpenTask:c,onEditTask:b,notesSummaryByEntity:p},E.id)),S.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:f("common.executionBoard.emptyLane")}):null]})},j)})}):e.jsx("div",{className:"grid w-full min-w-0 gap-0.5 xl:grid-cols-[repeat(5,minmax(0,1fr))]",children:kt.map(j=>{const S=C.filter(E=>E.status===j);return e.jsx(kn,{items:S.map(E=>`${m}:task:${E.id}`),strategy:Nn,children:e.jsxs(dr,{droppableId:`${m}:lane:${j}`,status:j,title:y[j].title,detail:y[j].detail,count:S.length,dragging:h!==null,children:[S.map(E=>e.jsx(lr,{sortableId:`${m}:task:${E.id}`,task:E,goal:s.find(X=>X.id===E.goalId),tags:E.tagIds.map(X=>a.find(G=>G.id===X)).filter(Boolean),isSelected:r===E.id,onSelect:n,onStartTask:o,onQuickReopen:d,onStepTask:I,onOpenTask:c,onEditTask:b,notesSummaryByEntity:p},E.id)),S.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:f("common.executionBoard.emptyLane")}):null]})},j)})})}),e.jsx(ud,{adjustScale:!1,dropAnimation:null,children:l?e.jsx("div",{className:"w-[20rem] max-w-[calc(100vw-2rem)]",children:e.jsx(Ro,{task:l,goal:N,tags:u,isSelected:r===l.id,isDragging:!0,isOverlay:!0,isMobile:x,onSelect:()=>{},onStartTask:o,notesSummaryByEntity:p})}):null})]})}const mh=$r(t=>({selectedOwner:null,selectedGoalId:null,selectedTagIds:[],setOwner:s=>t({selectedOwner:s}),setGoal:s=>t({selectedGoalId:s}),toggleTag:s=>t(a=>({selectedTagIds:a.selectedTagIds.includes(s)?a.selectedTagIds.filter(r=>r!==s):[...a.selectedTagIds,s]})),reset:()=>t({selectedOwner:null,selectedGoalId:null,selectedTagIds:[]})}));function hh(){var u;const{t}=qe(),s=Xe(),a=ht(),r=Qe(),[i,n]=g.useState(((u=s.snapshot.tasks[0])==null?void 0:u.id)??null),[o,d]=g.useState(null),{selectedGoalId:c,selectedOwner:b,selectedTagIds:p,setGoal:f,setOwner:m,toggleTag:x,reset:v}=mh(),w=s.snapshot.tasks.filter(M=>!(c&&M.goalId!==c||b&&M.owner!==b||p.length>0&&!p.every(A=>M.tagIds.includes(A)))),h=w.find(M=>M.id===i)??s.snapshot.tasks.find(M=>M.id===i)??null,P=o?s.snapshot.tasks.find(M=>M.id===o)??null:null,T=w.filter(M=>M.status==="blocked").length,O=w.filter(M=>M.status==="done").length,y=w.filter(M=>M.status==="focus"||M.status==="in_progress").length,C=s.snapshot.activeTaskRuns.length,l=async()=>{await Promise.all([r.invalidateQueries({queryKey:["forge-snapshot"]}),r.invalidateQueries({queryKey:["project-board"]}),r.invalidateQueries({queryKey:["task-context"]})])},N=ue({mutationFn:({taskId:M,patch:A})=>Os(M,A),onSuccess:l});return s.snapshot.tasks.length===0?e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-5",children:[e.jsx(Fe,{title:"Kanban",description:"Move tasks across the board, start work quickly, and keep your next step visible.",badge:"0 visible tasks",actions:e.jsx(K,{size:"lg",onClick:()=>s.openStartWork(),children:"Start work"})}),e.jsx(rt,{eyebrow:t("common.kanban.heroEyebrow"),title:t("common.kanban.emptyTitle"),description:t("common.kanban.emptyDescription"),action:e.jsx(Ne,{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(Fe,{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(K,{size:"lg",onClick:()=>s.openStartWork(h?{taskId:h.id}:void 0),children:"Start work"})}),e.jsx(Z,{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(_,{className:"bg-white/[0.08] text-white/72",children:[y," ready or active"]}),e.jsxs(_,{className:"bg-white/[0.08] text-white/72",children:[T," blocked"]}),e.jsxs(_,{className:"bg-white/[0.08] text-white/72",children:[O," done"]}),e.jsxs(_,{className:"bg-white/[0.08] text-white/72",children:[C," live timer",C===1?"":"s"]})]})]})}),e.jsxs(Z,{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(_,{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 ${c===null?"bg-white/[0.12] text-white":"bg-white/[0.04] text-white/58"}`,onClick:()=>f(null),children:"All goals"}),s.snapshot.goals.map(M=>e.jsx("button",{className:`interactive-tap min-w-0 max-w-full rounded-full px-4 py-2 text-sm ${c===M.id?"bg-white/[0.12] text-white":"bg-white/[0.04] text-white/58"}`,onClick:()=>f(c===M.id?null:M.id),children:e.jsx(Te,{kind:"goal",label:M.title,className:"max-w-full min-w-0",lines:2,labelClassName:"whitespace-normal text-left"})},M.id))]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(_,{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 ${b===null?"bg-white/[0.12] text-white":"bg-white/[0.04] text-white/58"}`,onClick:()=>m(null),children:"Everyone"}),s.snapshot.dashboard.owners.map(M=>e.jsx("button",{className:`interactive-tap max-w-full rounded-full px-4 py-2 text-sm ${b===M?"bg-white/[0.12] text-white":"bg-white/[0.04] text-white/58"}`,onClick:()=>m(b===M?null:M),children:M},M))]}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[s.snapshot.tags.map(M=>e.jsx("button",{className:`interactive-tap max-w-full rounded-full px-4 py-2 text-sm ${p.includes(M.id)?"bg-white/[0.12] text-white":"bg-white/[0.04] text-white/58"}`,onClick:()=>x(M.id),children:M.name},M.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:v,children:"Reset"})]})]}),w.length===0?e.jsx(rt,{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(K,{variant:"secondary",onClick:v,children:"Reset"})}):e.jsx(_o,{tasks:w,goals:s.snapshot.goals,tags:s.snapshot.tags,notesSummaryByEntity:s.snapshot.dashboard.notesSummaryByEntity,selectedTaskId:i,onMove:async(M,A)=>{await s.patchTaskStatus(M,A)},onQuickReopenTask:async M=>{await Si(M),await l()},onStartTask:async M=>{await s.startTaskNow(M),n(M),await r.invalidateQueries({queryKey:["task-context",M]})},onSelectTask:M=>{n(M)},onOpenTask:M=>{a(`/tasks/${M}`)},onEditTask:M=>{d(M)}}),e.jsx(wa,{open:P!==null,goals:s.snapshot.goals,projects:s.snapshot.dashboard.projects,tags:s.snapshot.tags,editingTask:P,onOpenChange:M=>{M||d(null)},onSubmit:async(M,A)=>{A&&(await N.mutateAsync({taskId:A,patch:M}),d(null))}})]})}function uh(t){return t.trim().toLowerCase()}function ph(t,s){return t.includes(s)?t:[...t,s]}function xh({entityOptions:t,selectedEntityValues:s,onSelectedEntityValuesChange:a,selectedTextTerms:r,onSelectedTextTermsChange:i,placeholder:n="Filter by linked entity or add free text"}){const[o,d]=g.useState(""),[c,b]=g.useState(!1),[p,f]=g.useState(0),m=uh(o),x=g.useMemo(()=>s.map(y=>t.find(C=>C.value===y)).filter(Boolean),[t,s]),v=g.useMemo(()=>{const y=t.filter(C=>!s.includes(C.value));return m?y.filter(C=>`${C.label} ${C.description??""} ${C.searchText??""}`.toLowerCase().includes(m)).slice(0,8):y.slice(0,8)},[t,m,s]),w=o.trim().length>0&&!r.includes(o.trim()),h=y=>{a(ph(s,y)),d(""),f(0),b(!1)},P=(y=o)=>{const C=y.trim();!C||r.includes(C)||(i([...r,C]),d(""),f(0),b(!1))},T=y=>{a(s.filter(C=>C!==y))},O=y=>{i(r.filter(C=>C!==y))};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:()=>P(),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:[x.length>0||r.length>0?e.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[x.map(y=>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:[y.kind?e.jsx(xe,{kind:y.kind,label:y.label,compact:!0,gradient:!1,className:"max-w-[16rem]"}):e.jsx(_,{className:"bg-white/[0.08] text-white/78",children:y.label}),e.jsx("button",{type:"button",className:"rounded-full text-white/50 transition hover:text-white",onClick:()=>T(y.value),"aria-label":`Remove ${y.label}`,children:e.jsx(yt,{className:"size-3.5"})})]},y.value)),r.map(y=>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(vn,{className:"size-3.5"}),e.jsx("span",{className:"max-w-[16rem] truncate",children:y})]}),e.jsx("button",{type:"button",className:"rounded-full text-cyan-100/70 transition hover:text-white",onClick:()=>O(y),"aria-label":`Remove free-text filter ${y}`,children:e.jsx(yt,{className:"size-3.5"})})]},y))]}):null,r.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(Tt,{className:"size-4 text-white/34"}),e.jsx("input",{value:o,onChange:y=>{d(y.target.value),b(!0),f(0)},onFocus:()=>b(!0),onBlur:()=>{window.setTimeout(()=>b(!1),120)},onKeyDown:y=>{if(y.key==="Backspace"&&!o){if(r.length>0){O(r[r.length-1]);return}s.length>0&&T(s[s.length-1]);return}if(y.key==="ArrowDown"){y.preventDefault(),b(!0),f(l=>v.length===0?0:Math.min(v.length-1,l+1));return}if(y.key==="ArrowUp"){y.preventDefault(),f(l=>Math.max(0,l-1));return}if(y.key==="Escape"){b(!1);return}if(y.key!=="Enter")return;y.preventDefault();const C=v[p];if(C){h(C.value);return}P()},placeholder:n,className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]}),c?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:[v.map((y,C)=>e.jsx("button",{type:"button",className:te("flex w-full items-start justify-between gap-3 rounded-[18px] px-3 py-2.5 text-left transition",C===p?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>f(C),onMouseDown:l=>l.preventDefault(),onClick:()=>h(y.value),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:y.kind?e.jsx(xe,{kind:y.kind,label:y.label,compact:!0,gradient:!1}):y.label}),y.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/46",children:y.description}):null]})},y.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:y=>y.preventDefault(),onClick:()=>P(),children:[e.jsx(vn,{className:"size-4"}),e.jsxs("span",{className:"truncate",children:['Add free text "',o.trim(),'"']})]}):null,v.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 gh=new Set(["goal","project","task","habit","tag","psyche_value","behavior_pattern","behavior","belief_entry","mode_profile","trigger_report"]),gt={goal:"goal",project:"project",task:"task",habit:"habit",psyche_value:"value",behavior_pattern:"pattern",behavior:"behavior",belief_entry:"belief",mode_profile:"mode",trigger_report:"report"};function $o(t){return gh.has(t)}function nt(t,s){return`${t}:${s}`}function Ws(t){const s=t.indexOf(":");if(s<=0||s>=t.length-1)return null;const a=t.slice(0,s);return $o(a)?{entityType:a,entityId:t.slice(s+1)}:null}function cr(t){return t!==null}function mr(t){const s=t.getAll("linkedTo"),a=t.get("entityType"),r=t.get("entityId");return a&&r&&$o(a)&&s.unshift(nt(a,r)),Array.from(new Set(s.map(i=>i.trim()).filter(Boolean)))}function fh(t){return Array.from(new Set(t.getAll("textTerms").map(s=>s.trim()).filter(Boolean)))}function bh(t){return vt(t.getAll("tags"))}function xs(t,s=[]){return{contentMarkdown:(t==null?void 0:t.contentMarkdown)??"",author:(t==null?void 0:t.author)??"",linkedValues:(t==null?void 0:t.links.map(a=>nt(a.entityType,a.entityId)))??s,tags:vt((t==null?void 0:t.tags)??[]),destroyAtInput:Mo((t==null?void 0:t.destroyAt)??null),destroyDelayValue:"",destroyDelayUnit:"days"}}function vh(t){return[...t].sort((s,a)=>s.label.localeCompare(a.label))}function hr(t){return Po(t.destroyAtInput)??Ao(t.destroyDelayValue,t.destroyDelayUnit)}function yh(){var k,R,Q,Ce,ie,_e,J;const t=ht(),s=Qe(),a=Xe(),[r,i]=ut(),[n,o]=g.useState(()=>mr(r)),[d,c]=g.useState(()=>bh(r)),[b,p]=g.useState(()=>fh(r)),[f,m]=g.useState(r.get("author")??""),[x,v]=g.useState(r.get("updatedFrom")??""),[w,h]=g.useState(r.get("updatedTo")??""),[P,T]=g.useState(!1),[O,y]=g.useState(()=>xs(null,mr(r))),[C,l]=g.useState(null),[N,u]=g.useState(null),[M,A]=g.useState(null),I=oe({queryKey:["forge-psyche-values"],queryFn:$t}),j=oe({queryKey:["forge-psyche-patterns"],queryFn:Es}),S=oe({queryKey:["forge-psyche-behaviors"],queryFn:Bt}),E=oe({queryKey:["forge-psyche-beliefs"],queryFn:hs}),X=oe({queryKey:["forge-psyche-modes"],queryFn:zt}),G=oe({queryKey:["forge-psyche-reports"],queryFn:Ca});g.useEffect(()=>{const H=new URLSearchParams;for(const pe of n)H.append("linkedTo",pe);for(const pe of d)H.append("tags",pe);for(const pe of b)H.append("textTerms",pe);f.trim()&&H.set("author",f.trim()),x&&H.set("updatedFrom",x),w&&H.set("updatedTo",w),i(H,{replace:!0})},[f,n,d,b,i,x,w]);const z=g.useMemo(()=>{var pe,Ie,Ye,fe,ye,$e;const H=[...a.snapshot.goals.map(ae=>({value:nt("goal",ae.id),label:ae.title,description:ae.description,searchText:`${ae.title} ${ae.description}`,kind:gt.goal})),...a.snapshot.dashboard.projects.map(ae=>({value:nt("project",ae.id),label:ae.title,description:ae.description,searchText:`${ae.title} ${ae.description} ${ae.goalTitle}`,kind:gt.project})),...a.snapshot.tasks.map(ae=>({value:nt("task",ae.id),label:ae.title,description:ae.description,searchText:`${ae.title} ${ae.description} ${ae.owner}`,kind:gt.task})),...a.snapshot.habits.map(ae=>({value:nt("habit",ae.id),label:ae.title,description:ae.description,searchText:`${ae.title} ${ae.description}`,kind:gt.habit})),...a.snapshot.tags.map(ae=>({value:nt("tag",ae.id),label:ae.name,description:ae.description,searchText:`${ae.name} ${ae.kind} ${ae.description}`})),...(((pe=I.data)==null?void 0:pe.values)??[]).map(ae=>({value:nt("psyche_value",ae.id),label:ae.title,description:ae.description,searchText:`${ae.title} ${ae.description} ${ae.valuedDirection}`,kind:gt.psyche_value})),...(((Ie=j.data)==null?void 0:Ie.patterns)??[]).map(ae=>({value:nt("behavior_pattern",ae.id),label:ae.title,description:ae.description,searchText:`${ae.title} ${ae.description} ${ae.targetBehavior}`,kind:gt.behavior_pattern})),...(((Ye=S.data)==null?void 0:Ye.behaviors)??[]).map(ae=>({value:nt("behavior",ae.id),label:ae.title,description:ae.description,searchText:`${ae.title} ${ae.description} ${ae.kind}`,kind:gt.behavior})),...(((fe=E.data)==null?void 0:fe.beliefs)??[]).map(ae=>({value:nt("belief_entry",ae.id),label:ae.statement,description:ae.flexibleAlternative||ae.originNote,searchText:`${ae.statement} ${ae.flexibleAlternative} ${ae.originNote}`,kind:gt.belief_entry})),...(((ye=X.data)==null?void 0:ye.modes)??[]).map(ae=>({value:nt("mode_profile",ae.id),label:ae.title,description:ae.archetype||ae.family,searchText:`${ae.title} ${ae.archetype} ${ae.family} ${ae.persona}`,kind:gt.mode_profile})),...((($e=G.data)==null?void 0:$e.reports)??[]).map(ae=>({value:nt("trigger_report",ae.id),label:ae.title,description:ae.eventSituation,searchText:`${ae.title} ${ae.eventSituation} ${ae.customEventType??""}`,kind:gt.trigger_report}))];return vh(H)},[(k=S.data)==null?void 0:k.behaviors,(R=E.data)==null?void 0:R.beliefs,(Q=X.data)==null?void 0:Q.modes,(Ce=j.data)==null?void 0:Ce.patterns,(ie=G.data)==null?void 0:ie.reports,a.snapshot.dashboard.projects,a.snapshot.goals,a.snapshot.habits,a.snapshot.tags,a.snapshot.tasks,(_e=I.data)==null?void 0:_e.values]),D=g.useMemo(()=>z.map(H=>{const pe=Ws(H.value);return{value:H.value,label:H.label,description:H.description,searchText:H.searchText,kind:H.kind,entityType:(pe==null?void 0:pe.entityType)??"goal",entityId:(pe==null?void 0:pe.entityId)??""}}),[z]),F=g.useMemo(()=>n.map(H=>Ws(H)).filter(Boolean),[n]),q=oe({queryKey:["notes-index",n.join("|"),d.join("|"),b.join("|"),f.trim(),x,w],queryFn:()=>no({linkedTo:F,tags:d,textTerms:b,author:f.trim()||void 0,updatedFrom:x||void 0,updatedTo:w||void 0,limit:200})}),Y=async()=>{await Promise.all([s.invalidateQueries({queryKey:["notes-index"]}),s.invalidateQueries({queryKey:["forge-snapshot"]})])},L=ue({mutationFn:async H=>Ci({contentMarkdown:H.contentMarkdown.trim(),author:H.author.trim()||null,tags:vt(H.tags),destroyAt:hr(H),links:H.linkedValues.map(pe=>Ws(pe)).filter(cr).map(pe=>({entityType:pe.entityType,entityId:pe.entityId}))}),onSuccess:async()=>{y(xs(null,n)),T(!1),await Y()}}),V=ue({mutationFn:async({noteId:H,draft:pe})=>ro(H,{contentMarkdown:pe.contentMarkdown.trim(),author:pe.author.trim()||null,tags:vt(pe.tags),destroyAt:hr(pe),links:pe.linkedValues.map(Ie=>Ws(Ie)).filter(cr).map(Ie=>({entityType:Ie.entityType,entityId:Ie.entityId}))}),onSuccess:async()=>{l(null),u(null),await Y()}}),le=ue({mutationFn:H=>oo(H),onSuccess:Y}),ce=((J=q.data)==null?void 0:J.notes)??[],he=M?ce.find(H=>H.id===M.noteId)??null:null,je=he?sr(he):null,W=je?ua(je.entityType,je.entityId):null,$=g.useMemo(()=>he?[{id:"open-linked",label:"Open linked record",description:W?"Jump back into the main entity this note is attached to.":"This note has no navigable linked record yet.",icon:Is,disabled:!W,onSelect:()=>{W&&t(W.includes("#")?W:`${W}#notes`)}},{id:"edit-note",label:"Edit note",description:"Update the Markdown body, note tags, expiry, or connected entity links.",icon:Ss,onSelect:()=>{l(he.id),u(xs(he))}},{id:"delete-note",label:"Delete note",description:"Soft-delete this note from the main workspace.",icon:bt,tone:"danger",disabled:le.isPending,onSelect:()=>{le.mutateAsync(he.id)}}]:[],[W,he,le,t]);return q.isError?e.jsx(Le,{eyebrow:"Notes",error:q.error,onRetry:()=>void q.refetch()}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Fe,{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:`${ce.length} visible`,actions:e.jsxs(K,{onClick:()=>{y(xs(null,n)),T(!0)},children:[e.jsx(Ht,{className:"size-4"}),"New note"]})}),e.jsxs(Z,{className:"grid gap-4",children:[e.jsx(xh,{entityOptions:D,selectedEntityValues:n,onSelectedEntityValuesChange:o,selectedTextTerms:b,onSelectedTextTermsChange:p}),e.jsx(ks,{value:d,onChange:c,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(se,{value:f,onChange:H=>m(H.target.value),placeholder:"Filter by author"}),e.jsx(se,{type:"date",value:x,onChange:H=>v(H.target.value)}),e.jsx(se,{type:"date",value:w,onChange:H=>h(H.target.value)})]})]}),P?e.jsxs(Z,{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(K,{variant:"ghost",onClick:()=>{T(!1),y(xs(null,n))},children:"Cancel"})]}),e.jsx(ve,{value:O.contentMarkdown,onChange:H=>y(pe=>({...pe,contentMarkdown:H.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(se,{value:O.author,onChange:H=>y(pe=>({...pe,author:H.target.value})),placeholder:"Optional author"}),e.jsx(We,{options:z,selectedValues:O.linkedValues,onChange:H=>y(pe=>({...pe,linkedValues:H})),placeholder:"Link this note to goals, tasks, habits, tags, or Psyche 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(ks,{value:O.tags,onChange:H=>y(pe=>({...pe,tags:H}))}),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(se,{type:"datetime-local",value:O.destroyAtInput,onChange:H=>y(pe=>({...pe,destroyAtInput:H.target.value}))}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_10rem]",children:[e.jsx(se,{type:"number",min:"1",value:O.destroyDelayValue,onChange:H=>y(pe=>({...pe,destroyDelayValue:H.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:O.destroyDelayUnit,onChange:H=>y(pe=>({...pe,destroyDelayUnit:H.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:O.contentMarkdown.trim()?e.jsx(mt,{markdown:O.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(K,{pending:L.isPending,pendingLabel:"Saving",disabled:O.contentMarkdown.trim().length===0||O.linkedValues.length===0,onClick:()=>void L.mutateAsync(O),children:"Save note"})})]}):null,q.isLoading?e.jsx(Z,{className:"text-sm text-white/58",children:"Loading notes…"}):ce.length===0?e.jsx(rt,{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:ce.map(H=>{const pe=sr(H),Ie=pe?ua(pe.entityType,pe.entityId):null,Ye=C===H.id&&N!==null;return e.jsxs(Z,{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:[(H.author??"Unknown author").toString()," •"," ",new Date(H.updatedAt).toLocaleString()]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[H.links.map(fe=>e.jsxs(_,{className:"bg-white/[0.08] text-white/68",wrap:!0,children:[Xt(fe.entityType),fe.anchorKey?` · ${js(fe.anchorKey)}`:""]},`${H.id}-${fe.entityType}-${fe.entityId}-${fe.anchorKey??""}`)),(H.tags??[]).map(fe=>e.jsx(_,{className:"bg-cyan-400/10 text-cyan-50",wrap:!0,children:fe},`${H.id}-tag-${fe}`)),H.destroyAt?e.jsxs(_,{className:"bg-amber-400/10 text-amber-100",wrap:!0,children:["Ephemeral · deletes"," ",new Date(H.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 ye=fe.currentTarget.getBoundingClientRect();A({noteId:H.id,position:{x:ye.right-8,y:ye.bottom+8}})},"aria-label":`Open actions for note ${H.id}`,children:e.jsx(ra,{className:"size-4"})})]}),Ye?e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsx(ve,{value:N.contentMarkdown,onChange:fe=>u(ye=>ye&&{...ye,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(se,{value:N.author,onChange:fe=>u(ye=>ye&&{...ye,author:fe.target.value}),placeholder:"Optional author"}),e.jsx(We,{options:z,selectedValues:N.linkedValues,onChange:fe=>u(ye=>ye&&{...ye,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(ks,{value:N.tags,onChange:fe=>u(ye=>ye&&{...ye,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(se,{type:"datetime-local",value:N.destroyAtInput,onChange:fe=>u(ye=>ye&&{...ye,destroyAtInput:fe.target.value})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_10rem]",children:[e.jsx(se,{type:"number",min:"1",value:N.destroyDelayValue,onChange:fe=>u(ye=>ye&&{...ye,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=>u(ye=>ye&&{...ye,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(mt,{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(K,{variant:"ghost",onClick:()=>{l(null),u(null)},children:"Cancel"}),e.jsx(K,{pending:V.isPending,pendingLabel:"Saving",disabled:N.contentMarkdown.trim().length===0||N.linkedValues.length===0,onClick:()=>void V.mutateAsync({noteId:H.id,draft:N}),children:"Save changes"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"mt-4 w-full text-left",onClick:()=>{Ie&&t(Ie.includes("#")?Ie:`${Ie}#notes`)},disabled:!Ie,children:e.jsx(mt,{markdown:H.contentMarkdown,className:"line-clamp-none"})}),Ie?e.jsx("div",{className:"mt-4 inline-flex text-xs uppercase tracking-[0.16em] text-[var(--secondary)]",children:"Open linked record"}):null]})]},H.id)})}),e.jsx(wo,{open:!!M,title:"Note actions",subtitle:he?he.contentPlain.slice(0,80)||"Markdown note":void 0,items:$,position:(M==null?void 0:M.position)??null,onClose:()=>A(null)})]})}function Bo({eyebrow:t,title:s,description:a,items:r,tone:i="core",className:n}){return e.jsxs("section",{className:te("min-w-0 overflow-hidden rounded-[28px] border border-white/6 shadow-[0_20px_54px_rgba(4,8,18,0.24)]",i==="core"?"bg-[linear-gradient(180deg,rgba(22,28,46,0.98),rgba(12,17,30,0.95))]":"bg-[linear-gradient(180deg,rgba(16,29,33,0.98),rgba(12,22,27,0.95))]",n),children:[e.jsxs("div",{className:te("grid min-w-0 gap-3 px-4 py-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,26rem)] lg:px-5",i==="core"?"bg-[radial-gradient(circle_at_top_right,rgba(192,193,255,0.12),transparent_36%),linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0))]":"bg-[radial-gradient(circle_at_top_right,rgba(110,231,183,0.1),transparent_36%),linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0))]"),children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:te("font-label text-[11px] uppercase tracking-[0.2em]",i==="core"?"text-[var(--secondary)]":"text-[rgba(110,231,183,0.82)]"),children:t}),e.jsx("h2",{className:"mt-2 max-w-3xl font-display text-[clamp(1.35rem,2vw,1.9rem)] leading-none text-white",children:s}),e.jsx("p",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/60",children:a})]}),e.jsx("div",{className:"grid min-w-0 gap-2 sm:grid-cols-3",children:r.slice(0,3).map(o=>o.href?e.jsxs(Ne,{to:o.href,className:te("min-w-0 rounded-[20px] border border-white/6 px-3 py-3 backdrop-blur-sm transition hover:bg-white/[0.08]",i==="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:o.label}),e.jsx("div",{className:"mt-1.5 min-w-0 font-medium text-white",children:o.title})]},o.id):e.jsxs("div",{className:te("min-w-0 rounded-[20px] border border-white/6 px-3 py-3 backdrop-blur-sm",i==="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:o.label}),e.jsx("div",{className:"mt-1.5 min-w-0 font-medium text-white",children:o.title})]},o.id))})]}),e.jsx("div",{className:"grid min-w-0 gap-3 px-4 py-4 lg:grid-cols-2 lg:px-5",children:r.map((o,d)=>{const c=te("group flex min-h-[13.5rem] min-w-0 flex-col overflow-hidden rounded-[24px] border border-white/7 p-0 transition hover:-translate-y-0.5 hover:shadow-[0_22px_46px_rgba(3,8,18,0.28)] sm:min-h-[15.5rem]",i==="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))]"),b=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:te("flex min-w-0 flex-1 flex-col p-4",i==="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:o.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:o.title})]}),o.badge?e.jsx(_,{wrap:!0,className:"max-w-[10rem] shrink-0 self-start bg-white/[0.08] text-white/72",children:o.badge}):null]}),e.jsx("div",{className:"mt-2.5 text-sm leading-6 text-white/60",children:o.detail}),e.jsx("div",{className:"flex-1"})]}),o.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:[o.actionLabel??"Open",e.jsx(Jt,{className:"size-3.5"})]})}):null]});return e.jsx(Ve.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.22,delay:.04*d,ease:"easeOut"},children:o.href?e.jsx(Ne,{to:o.href,className:c,children:b}):e.jsx("div",{className:c,children:b})},o.id)})})]})}function wh(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 jh(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 zo({profile:t,achievements:s,milestoneRewards:a,momentumPulse:r,recentLedger:i=[],className:n,tone:o="core"}){const d=s.filter(m=>m.unlocked),c=(d.length>0?d:s).slice(0,3),b=a.slice(0,3),p=i.slice(0,3),f=Math.min(100,Math.round(t.currentLevelXp/t.nextLevelXp*100));return e.jsxs("section",{className:te("min-w-0 overflow-hidden rounded-[30px] border border-white/6 bg-[linear-gradient(180deg,rgba(18,24,40,0.96),rgba(11,16,28,0.94))] shadow-[0_24px_70px_rgba(4,8,18,0.3)]",o==="psyche"&&"bg-[linear-gradient(180deg,rgba(18,27,35,0.96),rgba(12,20,26,0.94))]",n),children:[e.jsx("div",{className:te("bg-gradient-to-r px-5 py-5",jh(r.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:r.headline}),e.jsx("p",{className:"mt-3 max-w-3xl text-sm leading-7 text-white/68",children:r.detail})]}),e.jsxs("div",{className:"flex min-w-0 flex-wrap gap-2",children:[e.jsxs(_,{wrap:!0,className:"bg-black/20 text-white/84",children:["Level ",t.level]}),e.jsxs(_,{wrap:!0,className:"bg-black/20 text-white/84",children:[t.streakDays," day streak"]}),e.jsxs(_,{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(Ve.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:r.nextMilestoneLabel})]}),e.jsx(_,{wrap:!0,className:"max-w-[12rem] shrink-0 self-start text-[var(--tertiary)]",children:r.celebrationLabel})]}),e.jsx("div",{className:"mt-5",children:e.jsx(_t,{value:f})}),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:c.map((m,x)=>e.jsxs(Ve.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.24,delay:.04*x,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(_,{wrap:!0,className:te("max-w-[8rem] shrink-0 self-start",wh(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:b.map(m=>{const x=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(_,{wrap:!0,className:te("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(_t,{value:x})}),e.jsx("div",{className:"mt-3 text-xs uppercase tracking-[0.16em] text-white/38",children:m.progressLabel})]},m.id)})})]}),p.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:p.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(_,{wrap:!0,className:te("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:xi(m.createdAt)})]},m.id))})]}):null]})]})]})}function At({to:t,children:s,className:a}){return e.jsx(Ne,{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(Z,{className:te("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)]",a),children:s})})}function Dt({label:t,value:s,tone:a="default",detail:r,className:i}){return e.jsxs(Z,{className:te("rounded-[22px] p-4",a==="core"&&"bg-[linear-gradient(180deg,rgba(29,24,48,0.95),rgba(17,17,31,0.92))]",a==="psyche"&&"bg-[linear-gradient(180deg,rgba(18,31,34,0.96),rgba(13,24,27,0.94))]",i),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}),r?e.jsx("div",{className:"mt-2 text-sm text-white/56",children:r}):null]})}function kh(){const{t,formatDateTime:s}=qe(),{snapshot:a}=Xe(),r=a.metrics.momentumScore>=80?"Strong":a.metrics.momentumScore>=60?"Steady":"Needs attention",i=new Map(a.projects.map(h=>[h.id,h])),n=a.dashboard.milestoneRewards.find(h=>!h.completed)??a.dashboard.milestoneRewards[0]??null,o=a.dashboard.achievements.filter(h=>h.unlocked).length,d=a.overview.topTasks[0]??null,c=a.overview.dueHabits[0]??null,b=a.overview.activeGoals[0]??null,p=a.overview.neglectedGoals[0]??null,f=a.overview.recentEvidence[0]??null,m={status:a.metrics.momentumScore>=80?"surging":a.metrics.momentumScore>=60?"steady":"recovering",headline:a.metrics.momentumScore>=80?`${a.metrics.streakDays}-day streak active. Your recent work is building on itself.`:a.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:n!==null?`${n.title} is the clean next unlock. ${n.progressLabel}.`:`Level ${a.metrics.level} is active with ${a.metrics.weeklyXp} weekly XP recorded.`,celebrationLabel:o>0?`${o} achievement${o===1?"":"s"} unlocked`:a.metrics.weeklyXp>=120?"A strong week is taking shape":"The next reward comes from a real completion or repair",nextMilestoneId:(n==null?void 0:n.id)??null,nextMilestoneLabel:(n==null?void 0:n.rewardLabel)??"Keep building visible momentum"},x=a.overview.activeGoals.length>0||a.overview.projects.length>0||a.overview.topTasks.length>0||a.overview.recentEvidence.length>0||a.overview.dueHabits.length>0||a.overview.neglectedGoals.length>0,v=[{id:"top-task",label:d?"Top task":c?"Due habit":"Top goal",title:d?e.jsx(Te,{kind:"task",label:d.title,lines:3,labelClassName:"[overflow-wrap:anywhere]"}):c?e.jsx(Te,{kind:"habit",label:c.title,lines:3,labelClassName:"[overflow-wrap:anywhere]"}):b?e.jsx(Te,{kind:"goal",label:b.title,lines:3,labelClassName:"[overflow-wrap:anywhere]"}):"Choose the next task",detail:(d==null?void 0:d.description)||(c==null?void 0:c.description)||(b==null?void 0:b.description)||t("common.todayPage.noDirectiveDetail"),badge:d?`${d.points} xp`:c?`${c.rewardXp} xp`:`${a.overview.strategicHeader.focusTasks} focus tasks`,href:d?`/tasks/${d.id}`:c?"/habits":b?`/goals/${b.id}`:"/goals",actionLabel:d?"Open task":c?"Open habits":"Open goal"},{id:"reward",label:"Next reward",title:(n==null?void 0:n.title)??"Keep the streak going",detail:(n==null?void 0:n.progressLabel)??`Level ${a.metrics.level} is live. ${a.metrics.currentLevelXp} XP is already banked toward the next unlock.`,badge:(n==null?void 0:n.rewardLabel)??`${a.metrics.comboMultiplier.toFixed(2)}x combo`,href:"/today",actionLabel:"Open today"},{id:"goal-needing-attention",label:"Goal needing attention",title:p?e.jsx(Te,{kind:"goal",label:p.title,lines:3,labelClassName:"[overflow-wrap:anywhere]"}):"No goal needs urgent attention",detail:(p==null?void 0:p.summary)??`Only ${a.overview.strategicHeader.overdueTasks} overdue task${a.overview.strategicHeader.overdueTasks===1?"":"s"} are currently slowing the engine.`,badge:(p==null?void 0:p.risk)??"stable",href:p?`/goals/${p.goalId}`:"/today",actionLabel:p?"Open goal":"Open today"},{id:"recent-activity",label:"Recent activity",title:f?Pa(f):`${o} achievement${o===1?"":"s"} unlocked`,detail:(f?Ma(f):null)??t("common.overview.noEvidence"),badge:(f==null?void 0:f.source)??`${a.metrics.weeklyXp} weekly XP`,href:f?w(f):"/activity",actionLabel:f?"Open item":"Open activity"}];function w(h){return h.entityType==="goal"?`/goals/${h.entityId}`:h.entityType==="project"?`/projects/${h.entityId}`:h.entityType==="task"?`/tasks/${h.entityId}`:h.entityType==="habit"?"/habits":h.entityType==="task_run"&&typeof h.metadata.taskId=="string"?`/tasks/${h.metadata.taskId}`:`/activity?eventId=${h.id}`}return x?e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-5",children:[e.jsx(Fe,{title:"Overview",titleText:"Overview",description:`${r}. See your main goals, active projects, top tasks, and recent activity in one place.`,badge:`${a.metrics.streakDays} day streak`}),e.jsx(zo,{profile:a.metrics,achievements:a.dashboard.achievements,milestoneRewards:a.dashboard.milestoneRewards,momentumPulse:m}),e.jsx(Bo,{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:v}),e.jsxs("section",{className:"grid min-w-0 grid-cols-1 gap-5",children:[e.jsxs(Z,{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(Oe,{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(Dt,{label:t("common.overview.metricsLevel"),value:a.metrics.level,tone:"core"}),e.jsx(Dt,{label:t("common.overview.metricsWeeklyXp"),value:a.metrics.weeklyXp,tone:"core",detail:"XP earned so far this week."}),e.jsxs(At,{to:p?`/goals/${p.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:(p==null?void 0:p.title)??"No goal needs urgent attention"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(p==null?void 0:p.summary)??`Only ${a.overview.strategicHeader.overdueTasks} overdue task${a.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(Z,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Goals"}),a.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:a.overview.activeGoals.slice(0,3).map(h=>{var P;return e.jsxs(At,{to:`/goals/${h.id}`,className:"rounded-[22px] p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[e.jsx(xe,{kind:"goal",label:((P=h.tags[0])==null?void 0:P.name)??h.horizon,compact:!0,gradient:!1}),e.jsxs("div",{className:"shrink-0 text-[11px] uppercase tracking-[0.16em] text-white/42",children:[h.progress,"%"]})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Te,{kind:"goal",label:h.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:h.description}),e.jsx("div",{className:"mt-4",children:e.jsx(_t,{value:h.progress})}),e.jsx("div",{className:"mt-4",children:e.jsx(Ze,{entityType:"goal",entityId:h.id,count:at(a.dashboard.notesSummaryByEntity,"goal",h.id).count})})]},h.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(Z,{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(Oe,{content:"These are the projects currently carrying active work."})]}),a.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:a.overview.projects.slice(0,4).map(h=>e.jsxs(At,{to:`/projects/${h.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(xe,{kind:"project",compact:!0,gradient:!1}),e.jsx(Te,{kind:"project",label:h.title,className:"min-w-0",showIcon:!1,lines:2,labelClassName:"[overflow-wrap:anywhere]"})]}),e.jsxs(_,{wrap:!0,className:"max-w-[8rem] shrink-0",children:[h.earnedPoints," xp"]})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:h.description}),e.jsx("div",{className:"mt-3",children:e.jsx(xe,{kind:"goal",label:h.goalTitle,compact:!0})}),e.jsx("div",{className:"mt-4",children:e.jsx(Ze,{entityType:"project",entityId:h.id,count:at(a.dashboard.notesSummaryByEntity,"project",h.id).count})})]},h.id))})]}),e.jsxs(Z,{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(Oe,{content:"Recurring commitments or slips that still need a truthful check-in today."})]}),a.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:a.overview.dueHabits.slice(0,4).map(h=>e.jsxs(At,{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(xe,{kind:"habit",compact:!0,gradient:!1}),e.jsx(Te,{kind:"habit",label:h.title,className:"min-w-0",showIcon:!1,lines:2,labelClassName:"[overflow-wrap:anywhere]"})]}),e.jsxs(_,{wrap:!0,children:[h.rewardXp," xp"]})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:h.description||"Recurring operating commitment."}),e.jsx("div",{className:"mt-4",children:e.jsx(Ze,{entityType:"habit",entityId:h.id,count:at(a.dashboard.notesSummaryByEntity,"habit",h.id).count})})]},h.id))})]}),e.jsxs(Z,{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(Oe,{content:"These are the strongest task candidates to pick up next."})]}),a.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:a.overview.topTasks.slice(0,4).map(h=>{var P,T;return e.jsxs(At,{to:`/tasks/${h.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(xe,{kind:"task",compact:!0,gradient:!1}),e.jsx(Te,{kind:"task",label:h.title,className:"min-w-0",showIcon:!1,lines:2,labelClassName:"[overflow-wrap:anywhere]"})]}),e.jsxs(_,{wrap:!0,children:[h.points," xp"]})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:h.description}),e.jsx("div",{className:"mt-3",children:(P=i.get(h.projectId??""))!=null&&P.title?e.jsx(xe,{kind:"project",label:((T=i.get(h.projectId??""))==null?void 0:T.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(Ze,{entityType:"task",entityId:h.id,count:at(a.dashboard.notesSummaryByEntity,"task",h.id).count})})]},h.id)})})]})]}),e.jsxs(Z,{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(Oe,{content:"This shows the latest visible work, completions, and corrections linked to your goals, projects, and tasks."})]}),a.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:a.overview.recentEvidence.slice(0,6).map(h=>e.jsxs(At,{to:w(h),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:h.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:h.description})]}),e.jsx(_,{wrap:!0,children:h.source})]}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.16em] text-white/35",children:s(h.createdAt)})]},h.id))})]})]})]})]}):e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-5",children:[e.jsx(Fe,{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(rt,{eyebrow:t("common.overview.heroEyebrow"),title:t("common.overview.emptyTitle"),description:t("common.overview.emptyDescription"),action:e.jsx(Ne,{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 Nh=[10,15,30,45,60];function ur(){return{mode:"add",minutes:15,note:""}}function qo({open:t,onOpenChange:s,entityType:a,entityId:r,targetLabel:i,currentCreditedSeconds:n,pending:o=!1,onSubmit:d}){const[c,b]=g.useState(ur),[p,f]=g.useState(null);g.useEffect(()=>{t&&(b(ur()),f(null))},[t]);const m=oe({queryKey:["forge-xp-metrics"],queryFn:co,enabled:t}),x=g.useMemo(()=>{var O;const h=(O=m.data)==null?void 0:O.metrics.rules.find(y=>y.code==="task_run_progress"),P=Math.max(1,Number((h==null?void 0:h.config.intervalMinutes)??10)),T=Number((h==null?void 0:h.config.fixedXp)??4);return{intervalMinutes:P,fixedXp:T,intervalSeconds:P*60}},[m.data]),v=g.useMemo(()=>{const h=Math.max(0,Math.trunc(c.minutes||0)),P=c.mode==="add"?h:-h,T=Math.max(0,Math.floor(n/60)),O=P>=0?P:-Math.min(Math.abs(P),T),y=Math.max(0,n+O*60),C=Math.floor(Math.max(0,n)/x.intervalSeconds),N=Math.floor(y/x.intervalSeconds)-C;return{requestedDeltaMinutes:P,appliedDeltaMinutes:O,nextCreditedSeconds:y,bucketDelta:N,xpDelta:N*x.fixedXp,maxRemovableMinutes:T}},[x.fixedXp,x.intervalSeconds,n,c.minutes,c.mode]),w=[{id:"adjustment",eyebrow:a==="task"?"Task work":"Project work",title:`Adjust tracked work for ${i}`,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:(h,P)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Mode",labelHelp:"Add minutes when work happened off-timer. Remove minutes when the tracked total needs a correction.",children:e.jsx(Ke,{value:h.mode,onChange:T=>P({mode:T}),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(B,{label:"Minutes",description:`Currently tracked: ${Math.floor(n/60)} minutes.`,hint:h.mode==="remove"?`You can remove up to ${v.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(se,{type:"number",min:1,className:"w-36",value:h.minutes,onChange:T=>P({minutes:Number(T.target.value)||0})}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Nh.map(T=>e.jsxs(K,{type:"button",variant:h.minutes===T?"primary":"secondary",onClick:()=>P({minutes:T}),children:[T," min"]},T))})]})}),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:[v.appliedDeltaMinutes>0?"+":"",v.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:[v.xpDelta>0?"+":"",v.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(v.nextCreditedSeconds/60)," min"]})]})]}),e.jsxs("div",{className:"mt-3 text-sm leading-6 text-white/58",children:["Reward cadence: ",x.fixedXp," XP every ",x.intervalMinutes," credited minutes. ",v.bucketDelta===0?"This change does not cross a reward bucket.":`This change crosses ${Math.abs(v.bucketDelta)} reward bucket${Math.abs(v.bucketDelta)===1?"":"s"}.`]})]}),e.jsx(B,{label:"Note",description:"Optional context for why this correction is being added. The note stays attached to the adjustment metadata.",children:e.jsx(ve,{className:"min-h-28",value:h.note,onChange:T=>P({note:T.target.value}),placeholder:"Captured the review session that happened away from the live timer."})})]})}];return e.jsx(He,{open:t,onOpenChange:s,eyebrow:a==="task"?"Adjust task work":"Adjust project work",title:`Adjust work for ${i}`,description:"Add or remove tracked minutes without creating a live task run.",value:c,onChange:b,steps:w,submitLabel:"Save adjustment",pending:o,pendingLabel:"Saving adjustment...",error:p,onSubmit:async()=>{var O;f(null);const h=Math.max(0,Math.trunc(c.minutes||0)),P=c.mode==="add"?h:-h,T=_d.safeParse({entityType:a,entityId:r,deltaMinutes:P,note:c.note});if(!T.success){f(((O=T.error.issues[0])==null?void 0:O.message)??"Enter a valid minute adjustment.");return}try{await d({entityType:a,entityId:r,deltaMinutes:T.data.deltaMinutes,note:T.data.note||void 0}),s(!1)}catch(y){f(y instanceof Error?y.message:"Could not save the work adjustment right now.")}}})}const Ko={allowWorkBlockKinds:[],blockWorkBlockKinds:[],allowCalendarIds:[],blockCalendarIds:[],allowEventTypes:[],blockEventTypes:[],allowEventKeywords:[],blockEventKeywords:[],allowAvailability:[],blockAvailability:[]};function Ch(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean)}function Ua(t,s){const a=Ch(t);if(a.length===0)return!1;const r=s.join(" ").toLowerCase();return a.some(i=>r.includes(i))}function Sh(t){return t.allowWorkBlockKinds.length>0||t.allowCalendarIds.length>0||t.allowEventTypes.length>0||t.allowEventKeywords.length>0||t.allowAvailability.length>0}function Th(t,s){return t??s??Ko}function Uo(t){const s=t.rules??Ko,r=(t.at??new Date).getTime(),i=t.overview,n=(i==null?void 0:i.workBlockInstances.filter(m=>{const x=new Date(m.startAt).getTime(),v=new Date(m.endAt).getTime();return x<=r&&r<v}))??[],o=(i==null?void 0:i.events.filter(m=>{if(m.deletedAt)return!1;const x=new Date(m.startAt).getTime(),v=new Date(m.endAt).getTime();return x<=r&&r<v}))??[],d=[],c=n.some(m=>s.blockWorkBlockKinds.includes(m.kind))||o.some(m=>(m.calendarId?s.blockCalendarIds.includes(m.calendarId):!1)||s.blockEventTypes.includes(m.eventType)||s.blockAvailability.includes(m.availability)||Ua(s.blockEventKeywords,[m.title,m.description,m.location,...m.categories]));c&&(n.some(m=>s.blockWorkBlockKinds.includes(m.kind))&&d.push("The current work block is marked as blocked."),o.some(m=>m.calendarId?s.blockCalendarIds.includes(m.calendarId):!1)&&d.push("The active calendar belongs to a blocked calendar source."),o.some(m=>s.blockEventTypes.includes(m.eventType))&&d.push("The active calendar event type is blocked."),o.some(m=>s.blockAvailability.includes(m.availability))&&d.push("The active calendar availability is blocked."),o.some(m=>Ua(s.blockEventKeywords,[m.title,m.description,m.location,...m.categories]))&&d.push("The active calendar event matches a blocked keyword."));const b=Sh(s),p=n.some(m=>s.allowWorkBlockKinds.includes(m.kind))||o.some(m=>(m.calendarId?s.allowCalendarIds.includes(m.calendarId):!1)||s.allowEventTypes.includes(m.eventType)||s.allowAvailability.includes(m.availability)||Ua(s.allowEventKeywords,[m.title,m.description,m.location,...m.categories]));!c&&b&&!p&&d.push("The current calendar context does not match the allowed rules yet.");const f=[...n.map(m=>`${m.title} (${m.kind.replaceAll("_"," ")})`),...o.map(m=>m.title)];return d.length>0?{blocked:!0,label:"Blocked right now",tone:"blocked",conflicts:d,context:f}:f.length>0?{blocked:!1,label:"Allowed right now",tone:"allowed",conflicts:[],context:f}:{blocked:!1,label:b?"Waiting for an allowed calendar context":"No live calendar conflict right now",tone:b?"waiting":"allowed",conflicts:[],context:[]}}function Ih(t,s){return Th(t.schedulingRules,s)}function Ph(t){return!!(t&&t.startsWith("campaign:"))}function Mh(){var z;const{t}=qe(),s=Xe(),a=fa(),r=ht(),i=Qe(),[n,o]=g.useState(!1),[d,c]=g.useState(!1),[b,p]=g.useState(!1),[f]=g.useState(()=>{const D=new Date,F=new Date(D);F.setHours(0,0,0,0);const q=new Date(D);return q.setHours(23,59,59,999),{from:F.toISOString(),to:q.toISOString()}}),m=s.snapshot.dashboard.projects.find(D=>D.id===a.projectId)??null,x=m?s.snapshot.goals.find(D=>D.id===m.goalId)??null:null,v=m?s.snapshot.tasks.filter(D=>D.projectId===m.id||!D.projectId&&D.goalId===m.goalId):[],w=new Set(v.map(D=>D.id)),h=m?s.snapshot.activity.filter(D=>D.entityId===m.goalId||D.entityId===m.id||w.has(D.entityId)||D.entityType==="task_run"&&typeof D.metadata.taskId=="string"&&w.has(D.metadata.taskId)):[],P=Ph(a.projectId),T=oe({queryKey:["project-board",a.projectId],queryFn:()=>$c(a.projectId),enabled:!!a.projectId&&!P}),O=oe({queryKey:["project-calendar-overview",a.projectId,f.from,f.to],queryFn:()=>Sa(f),enabled:!!a.projectId&&!P}),y=ue({mutationFn:D=>Si(D),onSuccess:async()=>{await Promise.all([i.invalidateQueries({queryKey:["forge-snapshot"]}),i.invalidateQueries({queryKey:["project-board",a.projectId]})])}}),C=ue({mutationFn:xo,onSuccess:async()=>{await Promise.all([i.invalidateQueries({queryKey:["forge-snapshot"]}),i.invalidateQueries({queryKey:["project-board",a.projectId]}),i.invalidateQueries({queryKey:["forge-xp-metrics"]}),i.invalidateQueries({queryKey:["forge-reward-ledger"]}),i.invalidateQueries({queryKey:["forge-operator-context"]})])}}),l=ue({mutationFn:D=>po(a.projectId,{status:D}),onSuccess:async()=>{await Promise.all([i.invalidateQueries({queryKey:["forge-snapshot"]}),i.invalidateQueries({queryKey:["project-board",a.projectId]}),i.invalidateQueries({queryKey:["forge-xp-metrics"]}),i.invalidateQueries({queryKey:["forge-reward-ledger"]}),i.invalidateQueries({queryKey:["forge-operator-context"]})])}}),N=ue({mutationFn:()=>em(a.projectId),onSuccess:async()=>{await Promise.all([i.invalidateQueries({queryKey:["forge-snapshot"]}),i.invalidateQueries({queryKey:["project-board",a.projectId]})]),r("/projects")}}),u=T.data??(m&&x?{project:m,goal:x,tasks:v,activity:h}:void 0),M=s.snapshot.dashboard.projects.find(D=>D.id===a.projectId)??null;if(T.isError&&!P)return e.jsx(Le,{eyebrow:t("common.projectDetail.errorEyebrow"),error:T.error,onRetry:()=>void T.refetch()});if(!u)return e.jsx(xt,{});const A=u.tasks.find(D=>D.status==="focus"||D.status==="in_progress")??u.tasks[0]??null,I=u.tasks.find(D=>D.status==="blocked")??u.tasks.find(D=>D.status==="backlog")??null;u.activity[0];const j="notesSummaryByEntity"in u?u.notesSummaryByEntity:s.snapshot.dashboard.notesSummaryByEntity,S=l.isPending||N.isPending,E=Uo({rules:u.project.schedulingRules,overview:(z=O.data)==null?void 0:z.calendar}),X=async D=>{await l.mutateAsync(D)},G=async()=>{window.confirm(t("common.projectDetail.deleteProjectConfirm",{title:u.project.title}))&&await N.mutateAsync()};return e.jsxs("div",{className:"grid min-w-0 gap-5",children:[e.jsx(Fe,{entityKind:"project",title:e.jsx(Te,{kind:"project",label:u.project.title,variant:"heading",size:"lg"}),titleText:u.project.title,description:u.project.description?e.jsx(mt,{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(xe,{kind:"goal",label:u.goal.title,compact:!0,gradient:!1})}),P?e.jsxs(Z,{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(K,{onClick:()=>c(!0),children:t("common.projectDetail.addTask")}),P?null:e.jsx(K,{variant:"secondary",onClick:()=>p(!0),children:"Adjust work"}),P?null:e.jsx(K,{variant:"secondary",onClick:()=>o(!0),children:t("common.projectDetail.editProject")}),!P&&u.project.status==="active"?e.jsx(K,{variant:"secondary",pending:S&&l.variables==="paused",pendingLabel:t("common.projectDetail.suspending"),onClick:()=>void X("paused"),children:t("common.projectDetail.suspendProject")}):null,!P&&u.project.status!=="completed"?e.jsx(K,{pending:S&&l.variables==="completed",pendingLabel:t("common.projectDetail.finishing"),onClick:()=>void X("completed"),children:t("common.projectDetail.finishProject")}):null,!P&&u.project.status!=="active"?e.jsx(K,{variant:"secondary",pending:S&&l.variables==="active",pendingLabel:t("common.projectDetail.restarting"),onClick:()=>void X("active"),children:t("common.projectDetail.restartProject")}):null,P?null:e.jsx(K,{variant:"ghost",pending:N.isPending,pendingLabel:t("common.projectDetail.deleting"),onClick:()=>void G(),children:t("common.projectDetail.deleteProject")}),e.jsx(Ne,{to:`/goals/${u.goal.id}`,children:e.jsx(K,{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(Z,{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(xe,{kind:"project",compact:!0,gradient:!1}),e.jsx(xe,{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(Ne,{to:A?`/tasks/${A.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")}),A?e.jsx(xe,{kind:"task",compact:!0,gradient:!1}):null]}),e.jsx("div",{className:"mt-2 font-medium text-white",children:(A==null?void 0:A.title)??t("common.projectDetail.noNextTask")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(A==null?void 0:A.description)||t("common.projectDetail.noNextTaskDetail")})]}),e.jsxs(Ne,{to:I?`/tasks/${I.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")}),I?e.jsx(xe,{kind:"task",compact:!0,gradient:!1}):null]}),e.jsx("div",{className:"mt-2 font-medium text-white",children:(I==null?void 0:I.title)??t("common.projectDetail.noRisk")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(I==null?void 0:I.description)||t("common.projectDetail.noRiskDetail")})]})]})]}),e.jsxs(Z,{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(_,{className:"bg-white/[0.08] text-white/72",children:t(`common.enums.projectStatus.${u.project.status}`)}),e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:u.project.momentumLabel}),e.jsxs(_,{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(D=>D.status==="focus"||D.status==="in_progress").length})]})]})]})]}),P?null:e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,1fr)_22rem]",children:[e.jsx(Ti,{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:D})=>{await s.patchProject(u.project.id,{schedulingRules:D}),await i.invalidateQueries({queryKey:["project-board",a.projectId]}),await i.invalidateQueries({queryKey:["project-calendar-overview",a.projectId]})}}),e.jsxs(Z,{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(_,{className:E.tone==="blocked"?"bg-rose-500/14 text-rose-100":E.tone==="waiting"?"bg-amber-500/14 text-amber-100":"bg-emerald-500/14 text-emerald-100",children:E.label}),e.jsx(_,{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."}),E.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:E.context.map(D=>e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:D},D))})]}):null,E.conflicts.length>0?e.jsx("div",{className:"mt-4 grid gap-2",children:E.conflicts.map(D=>e.jsx("div",{className:"rounded-[16px] bg-rose-500/10 px-3 py-2 text-sm text-rose-100",children:D},D))}):null,e.jsx("div",{className:"mt-4",children:e.jsx(Ne,{to:"/calendar",children:e.jsx(K,{variant:"secondary",children:"Open calendar workspace"})})})]})]}),e.jsx(_o,{tasks:u.tasks,goals:s.snapshot.goals,tags:s.snapshot.tags,notesSummaryByEntity:j,selectedTaskId:null,onMove:async(D,F)=>{await s.patchTaskStatus(D,F),await i.invalidateQueries({queryKey:["project-board",a.projectId]})},onSelectTask:D=>r(`/tasks/${D}`),onQuickReopenTask:async D=>{await y.mutateAsync(D)}}),P?null:e.jsx(Ia,{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",a.projectId]]}),e.jsxs(Z,{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(D=>e.jsxs(Ne,{to:Rt(D)??`/activity?eventId=${D.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:Pa(D)}),e.jsx(_,{children:D.source})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:Ma(D)})]},D.id))})]}),e.jsx(yi,{open:n,goals:s.snapshot.goals,editingProject:M,onOpenChange:o,onSubmit:async(D,F)=>{F&&(await s.patchProject(F,D),await i.invalidateQueries({queryKey:["project-board",a.projectId]}))}}),e.jsx(wa,{open:d,goals:s.snapshot.goals,projects:s.snapshot.dashboard.projects,tags:s.snapshot.tags,editingTask:null,initialProjectId:P?null:u.project.id,onOpenChange:c,onSubmit:async(D,F)=>{F?await Os(F,D):await s.createTask(D),await i.invalidateQueries({queryKey:["project-board",a.projectId]})}}),P?null:e.jsx(qo,{open:b,onOpenChange:p,entityType:"project",entityId:u.project.id,targetLabel:u.project.title,currentCreditedSeconds:u.project.time.totalCreditedSeconds,pending:C.isPending,onSubmit:async D=>{await C.mutateAsync(D)}})]})}function Ah(t){return t.trim().toLowerCase()}function pr(t,s=!1){switch(t.kind){case"goal":return e.jsx(xe,{kind:"goal",label:t.label,compact:!0,gradient:!1});case"task":return e.jsx(xe,{kind:"task",label:t.label,compact:!0,gradient:!1});case"tag":return e.jsx(_,{className:"bg-white/[0.08] text-white/78",children:t.label});case"status":return e.jsx(_,{className:"bg-[rgba(192,193,255,0.12)] text-white/84",children:t.label});case"type":return e.jsx(_,{className:"bg-[rgba(86,170,255,0.12)] text-white/84",children:t.label});default:return t.label}}function Dh({query:t,onQueryChange:s,options:a,selectedOptionIds:r,onSelectedOptionIdsChange:i,resultSummary:n}){const[o,d]=g.useState(!1),[c,b]=g.useState(0),p=g.useMemo(()=>r.map(h=>a.find(P=>P.id===h)).filter(Boolean),[a,r]),f=Ah(t),m=g.useMemo(()=>{const h=a.filter(P=>!r.includes(P.id));return f?h.filter(P=>`${P.label} ${P.description??""} ${P.searchText??""}`.toLowerCase().includes(f)).slice(0,10):h.slice(0,10)},[f,a,r]),x=h=>{r.includes(h)||(i([...r,h]),s(""),b(0),d(!1))},v=h=>{i(r.filter(P=>P!==h))},w=()=>{s(""),i([]),b(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, statuses, or lightweight project-type chips as you narrow the list."})]}),t.trim().length>0||r.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:[p.length>0?e.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:p.map(h=>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:[pr(h,!0),e.jsx("button",{type:"button",className:"rounded-full text-white/52 transition hover:text-white",onClick:()=>v(h.id),"aria-label":`Remove ${h.label}`,children:e.jsx(yt,{className:"size-3.5"})})]},h.id))}):null,e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Tt,{className:"size-4 text-white/36"}),e.jsx("input",{value:t,onChange:h=>{s(h.target.value),d(!0),b(0)},onFocus:()=>d(!0),onBlur:()=>{window.setTimeout(()=>d(!1),120)},onKeyDown:h=>{if(h.key==="Backspace"&&!t&&r.length>0){v(r[r.length-1]);return}if(h.key==="ArrowDown"){h.preventDefault(),d(!0),b(P=>m.length===0?0:Math.min(m.length-1,P+1));return}if(h.key==="ArrowUp"){h.preventDefault(),b(P=>Math.max(0,P-1));return}if(h.key==="Escape"){d(!1);return}h.key==="Enter"&&m[c]&&(h.preventDefault(),x(m[c].id))},placeholder:"Type a project name, a goal, a task, or a tag",className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]}),o?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((h,P)=>e.jsx("button",{type:"button",className:te("flex w-full items-start justify-between gap-3 rounded-[18px] px-3 py-2.5 text-left transition",P===c?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>b(P),onMouseDown:T=>T.preventDefault(),onClick:()=>x(h.id),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:pr(h)}),h.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/46",children:h.description}):null]})},h.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, tag, status, or type chip when it appears."})}):null]})]}),e.jsx("div",{className:"mt-3 text-sm text-white/52",children:n})]})})}const Eh={execution:"Execution",value:"Value",category:"Category"};function Lh(t){return t.trim().toLowerCase()}function Fh(){const t=Xe(),[s,a]=g.useState("active"),[r,i]=g.useState(""),[n,o]=g.useState([]),[d,c]=g.useState(null),b=g.useMemo(()=>Pi(t.snapshot.dashboard.projects),[t.snapshot.dashboard.projects]),p=g.useMemo(()=>{const T=new Map(t.snapshot.dashboard.goals.map(C=>[C.id,C])),O=new Map(t.snapshot.tags.map(C=>[C.id,C])),y=new Map;for(const C of t.snapshot.tasks){if(!C.projectId)continue;const l=y.get(C.projectId)??[];l.push(C),y.set(C.projectId,l)}return new Map(t.snapshot.dashboard.projects.map(C=>{const l=T.get(C.goalId)??null,N=y.get(C.id)??[],u=new Map;for(const I of(l==null?void 0:l.tags)??[])u.set(I.id,{id:I.id,name:I.name,kind:I.kind});for(const I of N)for(const j of I.tagIds){const S=O.get(j);S&&u.set(S.id,{id:S.id,name:S.name,kind:S.kind})}const M=Array.from(new Set(Array.from(u.values()).map(I=>I.kind))),A=[C.title,C.description,C.goalTitle,(l==null?void 0:l.description)??"",C.nextTaskTitle??"",C.momentumLabel,C.status,N.map(I=>I.title).join(" "),Array.from(u.values()).map(I=>`${I.name} ${I.kind}`).join(" ")].join(" ").toLowerCase();return[C.id,{tagIds:Array.from(u.keys()),tags:Array.from(u.values()),taskIds:N.map(I=>I.id),typeKeys:M,searchText:A}]}))},[t.snapshot.dashboard.goals,t.snapshot.dashboard.projects,t.snapshot.tags,t.snapshot.tasks]),f=g.useMemo(()=>{var u,M,A,I;const T=new Map,O=new Map,y=new Map,C=new Map,l=new Map,N=new Map;for(const j of t.snapshot.dashboard.projects){const S=p.get(j.id);if(S){O.has(j.goalId)||O.set(j.goalId,new Set),O.get(j.goalId).add(j.id),l.has(j.status)||l.set(j.status,new Set),l.get(j.status).add(j.id);for(const E of S.taskIds)y.has(E)||y.set(E,new Set),y.get(E).add(j.id);for(const E of S.tags)C.has(E.id)||C.set(E.id,new Set),C.get(E.id).add(j.id);for(const E of S.typeKeys)N.has(E)||N.set(E,new Set),N.get(E).add(j.id)}}for(const j of t.snapshot.dashboard.goals){const S=((u=O.get(j.id))==null?void 0:u.size)??0;S!==0&&T.set(`goal:${j.id}`,{id:`goal:${j.id}`,kind:"goal",value:j.id,label:j.title,description:`${S} project${S===1?"":"s"} linked to this goal`,searchText:`${j.title} ${j.description}`})}for(const j of t.snapshot.tasks){const S=((M=y.get(j.id))==null?void 0:M.size)??0;S!==0&&T.set(`task:${j.id}`,{id:`task:${j.id}`,kind:"task",value:j.id,label:j.title,description:`${S} project${S===1?"":"s"} linked to this task`,searchText:`${j.title} ${j.description}`})}for(const j of t.snapshot.tags){const S=((A=C.get(j.id))==null?void 0:A.size)??0;S!==0&&T.set(`tag:${j.id}`,{id:`tag:${j.id}`,kind:"tag",value:j.id,label:j.name,description:`${S} project${S===1?"":"s"} touching this tag`,searchText:`${j.name} ${j.kind} ${j.description}`})}for(const[j,S]of Object.entries(b))j==="all"||S===0||T.set(`status:${j}`,{id:`status:${j}`,kind:"status",value:j,label:j==="paused"?"Suspended":j==="completed"?"Finished":"Active",description:`${S} project${S===1?"":"s"} currently ${j==="paused"?"suspended":j==="completed"?"finished":"active"}`,searchText:`${j} ${j==="paused"?"suspended":""} ${j==="completed"?"finished":""}`});for(const[j,S]of Object.entries(Eh)){const E=((I=N.get(j))==null?void 0:I.size)??0;E!==0&&T.set(`type:${j}`,{id:`type:${j}`,kind:"type",value:j,label:S,description:`${E} project${E===1?"":"s"} linked to ${S.toLowerCase()} tags`,searchText:`${S} ${j} project type`})}return Array.from(T.values()).sort((j,S)=>j.label.localeCompare(S.label))},[b,p,t.snapshot.dashboard.goals,t.snapshot.dashboard.projects,t.snapshot.tags,t.snapshot.tasks]),m=g.useMemo(()=>n.map(T=>f.find(O=>O.id===T)).filter(Boolean),[f,n]),x=g.useMemo(()=>{const T=Lh(r);return Mi(t.snapshot.dashboard.projects,s).filter(O=>{const y=p.get(O.id);return!y||!m.every(l=>{switch(l.kind){case"goal":return O.goalId===l.value;case"task":return y.taskIds.includes(l.value);case"tag":return y.tagIds.includes(l.value);case"status":return O.status===l.value;case"type":return y.typeKeys.includes(l.value);default:return!0}})?!1:T?y.searchText.includes(T):!0})},[s,p,r,m,t.snapshot.dashboard.projects]),v=s==="all"?b.all:b[s],h=r.trim().length>0||n.length>0?`${x.length} matching project${x.length===1?"":"s"} in the current collection view`:`${v} project${v===1?"":"s"} in ${s==="all"?"all project states":s==="paused"?"the suspended view":s==="completed"?"the finished view":"the active view"}`,P=async T=>{c(T);try{await t.patchProject(T,{status:"active"})}finally{c(null)}};return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Fe,{entityKind:"project",title:e.jsx(Te,{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(rt,{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(Ne,{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(Dh,{query:r,onQueryChange:i,options:f,selectedOptionIds:n,onSelectedOptionIdsChange:o,resultSummary:h}),e.jsx(Ii,{value:s,counts:b,onChange:a}),x.length===0?e.jsxs(Z,{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:x.map(T=>{const O=at(t.snapshot.dashboard.notesSummaryByEntity,"project",T.id),y=p.get(T.id),C=(y==null?void 0:y.tags.slice(0,3))??[];return e.jsxs(Z,{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.jsx(xe,{kind:"goal",label:T.goalTitle,compact:!0}),e.jsx(_,{className:T.status==="completed"?"text-emerald-300":T.status==="paused"?"text-amber-300":"text-[var(--primary)]",children:T.status==="paused"?"Suspended":T.status==="completed"?"Finished":"Active"})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Ne,{to:`/projects/${T.id}`,className:"transition hover:opacity-90",children:e.jsx(Te,{kind:"project",label:T.title,variant:"heading",size:"xl"})})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:T.description}),C.length>0?e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:C.map(l=>e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:l.name},l.id))}):null,e.jsx("div",{className:"mt-4",children:e.jsx(_t,{value:T.progress,tone:T.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:T.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:T.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:T.earnedPoints})]})]}),e.jsx("div",{className:"mt-5 text-[11px] uppercase tracking-[0.16em] text-white/40",children:T.nextTaskTitle?`Next move: ${T.nextTaskTitle}`:"Ready for the next task"}),e.jsx("div",{className:"mt-4",children:e.jsx(Ze,{entityType:"project",entityId:T.id,count:O.count})}),e.jsxs("div",{className:"mt-5 flex flex-wrap items-center justify-between gap-3 pt-1",children:[e.jsx(Ne,{to:`/projects/${T.id}`,children:e.jsx(K,{variant:"ghost",children:"Open project"})}),s!=="active"&&T.status!=="active"?e.jsx(K,{variant:"secondary",pending:d===T.id,pendingLabel:"Restarting…",onClick:()=>void P(T.id),children:"Restart"}):null]})]},T.id)})})]})]})}function Ei(t,s,a){return Math.min(Math.max(t,s),a)}function Li(t,s,a){return Math.min(a,Math.max(1,Math.ceil(t.trim().length/s)))}function Oh(t,{compact:s}){const a=Li(t,s?13:14,4),i=(s?114:156)+(a-1)*(s?12:18)+Math.min(24,Math.max(0,t.trim().length-18))*(s?.7:1);return Ei(i,s?118:164,s?154:210)}function Rh(t,{compact:s}){const a=Li(t,s?11:13,3),i=(s?40:48)+(a-1)*(s?6:8)+Math.min(s?18:26,Math.max(0,t.trim().length-(s?12:16)))*(s?.45:.55);return Ei(i,s?42:50,s?56:68)}function gs(t,{compact:s,emphasis:a=!1}){const i=Li(t,s?16:a?22:20,a?3:2);return{width:Ei((s?a?184:152:a?224:176)+Math.min(t.length,48)*(s?1.8:2.15),s?a?188:156:a?228:184,s?a?248:208:a?300:244),height:i===1?s?64:70:i===2?s?82:92:s?98:110}}function xr(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 _h(t,{compact:s}){const a=t.map(n=>({...n,homeX:n.x,homeY:n.y,locked:n.kind==="goal"||n.kind==="ghost"})),r=s?28:40,i=s?.08:.06;for(let n=0;n<180;n+=1){for(const o of a)o.locked||(o.x+=(o.homeX-o.x)*i,o.y+=(o.homeY-o.y)*i);for(let o=0;o<a.length;o+=1)for(let d=o+1;d<a.length;d+=1){const c=a[o],b=a[d],p=xr(c),f=xr(b),m=b.x-c.x,x=b.y-c.y,v=p.halfWidth+f.halfWidth+r-Math.abs(m),w=p.halfHeight+f.halfHeight+r-Math.abs(x);if(v<=0||w<=0)continue;const h=v<w?"x":"y",P=Math.sign(h==="x"?m||d-o||1:x||d-o||1),T=(h==="x"?v:w)/(c.locked||b.locked?1:2);c.locked||(h==="x"?c.x-=P*T:c.y-=P*T),b.locked||(h==="x"?b.x+=P*T:b.y+=P*T)}}return a.map(({homeX:n,homeY:o,locked:d,...c})=>c)}function $h(){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 Qo(t,{compact:s=!1}={}){var b;if(t.length===0)return $h();const a=[],r=[],i=[],n={},o=s?560:840,d=-((t.length-1)*o)/2;t.forEach((p,f)=>{const m=d+f*o,x=f%2===0?92:146,v=p.linkedBehaviors.length+p.linkedBeliefs.length+p.linkedReports.length+p.linkedHabits.length,w=`goal:${p.goal.id}`;a.push({id:w,kind:"goal",x:m,y:x,radius:Oh(p.goal.title,{compact:s}),tone:"amber",label:p.goal.title,href:`/goals/${p.goal.id}`}),n[w]={id:w,eyebrow:"Goal",title:p.goal.title,summary:p.goal.description,href:`/goals/${p.goal.id}`,ctaLabel:"Open goal",tone:"amber",entityKind:"goal",chips:p.linkedValues.slice(0,4).map(I=>I.title),stats:[`${p.linkedValues.length} linked value${p.linkedValues.length===1?"":"s"}`,`${p.linkedProjects.length} live project${p.linkedProjects.length===1?"":"s"}`,`${p.linkedHabits.length} linked habit${p.linkedHabits.length===1?"":"s"}`,`${v} friction signal${v===1?"":"s"}`]},v>0&&i.push({id:`field:${p.goal.id}`,x:m+18,y:x+20,radiusX:s?144:176,radiusY:s?104:132,tone:"rose",opacity:Math.min(.42,.14+v*.04)});const h=s?208:282;p.linkedValues.slice(0,s?4:5).forEach((I,j)=>{const S=(-95+j*(s?78:64))*(Math.PI/180),E=Rh(I.title,{compact:s}),X=m+Math.cos(S)*h,G=x+Math.sin(S)*h,z=`value:${I.id}`;a.push({id:z,kind:"value",x:X,y:G,radius:E,tone:"mint",label:I.title,meta:`${I.linkedGoalIds.length} goal${I.linkedGoalIds.length===1?"":"s"}`,href:`/psyche/values?focus=${I.id}#values-atlas`}),r.push({id:`${w}->${z}`,from:w,to:z,tone:"mint",strength:"medium"}),n[z]={id:z,eyebrow:"Value",title:I.title,summary:I.valuedDirection||I.whyItMatters||I.description,href:`/psyche/values?focus=${I.id}#values-atlas`,ctaLabel:"Open values",tone:"mint",entityKind:"value",chips:I.committedActions.slice(0,3),stats:[`${I.linkedProjectIds.length} linked project${I.linkedProjectIds.length===1?"":"s"}`,`${I.linkedTaskIds.length} linked task${I.linkedTaskIds.length===1?"":"s"}`]}});const P=p.linkedProjects.slice(0,s?2:3).map(I=>({project:I,size:gs(I.title,{compact:s,emphasis:!0})})),T=s?24:30;let y=-(P.reduce((I,j)=>I+j.size.width,0)+Math.max(0,P.length-1)*T)/2;P.forEach(({project:I,size:j},S)=>{const E=`project:${I.id}`,X=m+y+j.width/2,G=x-(s?330:434)-S*(s?16:20);y+=j.width+T,a.push({id:E,kind:"project",x:X,y:G,width:j.width,height:j.height,tone:"sky",label:I.title,meta:"Project",href:`/projects/${I.id}`}),r.push({id:`${w}->${E}`,from:w,to:E,tone:"sky",strength:"medium"}),n[E]={id:E,eyebrow:"Project",title:I.title,summary:I.description,href:`/projects/${I.id}`,ctaLabel:"Open project",tone:"sky",entityKind:"project",chips:[I.status,I.goalTitle],stats:[`${I.progress}% progress`,`${I.activeTaskCount} active task${I.activeTaskCount===1?"":"s"}`]}}),p.linkedHabits.slice(0,s?2:3).forEach((I,j)=>{const S=`habit:${I.id}`,E=gs(I.title,{compact:s}),X=m-(s?44:58),G=x+(s?228:294)+j*(s?92:104);a.push({id:S,kind:"habit",x:X,y:G,width:E.width,height:E.height,tone:"mint",label:I.title,meta:I.polarity,href:"/habits"}),r.push({id:`${w}->${S}`,from:w,to:S,tone:"mint",strength:I.dueToday?"high":"medium"}),n[S]={id:S,eyebrow:"Habit",title:I.title,summary:I.description||"Recurring operating record connected directly to this goal field.",href:"/habits",ctaLabel:"Open habits",tone:"mint",entityKind:"habit",chips:[I.polarity,I.frequency,I.dueToday?"due today":"checked in"],stats:[`${I.streakCount} streak`,`${I.rewardXp}/${I.penaltyXp} xp flow`]}});let C=x+(s?132:156);p.linkedBehaviors.slice(0,s?2:3).forEach(I=>{const j=`behavior:${I.id}`,S=gs(I.title,{compact:s}),E=m-(s?272:352);a.push({id:j,kind:"behavior",x:E,y:C,width:S.width,height:S.height,tone:"orange",label:I.title,meta:I.kind,href:`/psyche/behaviors?focus=${I.id}#behavior-columns`}),r.push({id:`${w}->${j}`,from:w,to:j,tone:"orange",dashed:I.kind!=="committed",strength:I.kind==="committed"?"medium":"low"}),n[j]={id:j,eyebrow:"Behavior",title:I.title,summary:I.replacementMove||I.description||I.urgeStory,href:`/psyche/behaviors?focus=${I.id}#behavior-columns`,ctaLabel:"Open behaviors",tone:"orange",entityKind:"behavior",chips:[I.kind,...I.commonCues.slice(0,2)],stats:[I.shortTermPayoff?"Short-term payoff mapped":"Payoff still to map",I.longTermCost?"Long-term cost mapped":"Cost still to map"]},C+=S.height+(s?18:22)});let l=x+(s?8:10);p.linkedBeliefs.slice(0,s?2:3).forEach(I=>{const j=`belief:${I.id}`,S=gs(I.statement,{compact:s,emphasis:!0}),E=m+(s?278:362);a.push({id:j,kind:"belief",x:E,y:l,width:S.width,height:S.height,tone:"violet",label:I.statement,meta:"belief",href:`/psyche/schemas-beliefs?focus=${I.id}`}),r.push({id:`${w}->${j}`,from:w,to:j,tone:"violet",dashed:!0,strength:"low"}),n[j]={id:j,eyebrow:"Belief",title:I.statement,summary:I.flexibleAlternative||I.originNote||"Belief script attached to this part of the map.",href:`/psyche/schemas-beliefs?focus=${I.id}`,ctaLabel:"Open beliefs",tone:"violet",entityKind:"belief",chips:[I.beliefType,`${I.confidence}% grip`],stats:[`${I.linkedBehaviorIds.length} linked behavior${I.linkedBehaviorIds.length===1?"":"s"}`,`${I.linkedReportIds.length} linked report${I.linkedReportIds.length===1?"":"s"}`]},l+=S.height+(s?18:22)});const N=p.linkedReports.slice(0,s?2:3).map(I=>({report:I,size:gs(I.title,{compact:s})})),u=s?20:26;let A=-(N.reduce((I,j)=>I+j.size.width,0)+Math.max(0,N.length-1)*u)/2;N.forEach(({report:I,size:j})=>{const S=`report:${I.id}`,E=m+A+j.width/2,X=x+(s?332:430);A+=j.width+u,a.push({id:S,kind:"report",x:E,y:X,width:j.width,height:j.height,tone:"blue",label:I.title,meta:I.status,href:`/psyche/reports/${I.id}`}),r.push({id:`${w}->${S}`,from:w,to:S,tone:"sky",strength:"medium"}),n[S]={id:S,eyebrow:"Report",title:I.title,summary:I.eventSituation||I.customEventType||"Reflective chain linked into this goal.",href:`/psyche/reports/${I.id}`,ctaLabel:"Open report",tone:"blue",entityKind:"report",chips:[I.status,...I.nextMoves.slice(0,2)],stats:[`${I.emotions.length} emotion${I.emotions.length===1?"":"s"}`,`${I.behaviors.length} move${I.behaviors.length===1?"":"s"}`]}})});const c=((b=a[0])==null?void 0:b.id)??"ghost_goal_center";return{nodes:_h(a,{compact:s}),edges:r,fields:i,inspectors:n,defaultSelectedId:c}}const qt={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)"},Qa={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)"},Kt={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 Xo(t){switch(t){case"goal":case"value":case"behavior":case"belief":case"report":case"project":case"habit":return t;default:return null}}function Bh(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 zh(t){if(t.kind==="ghost")return t.meta??null;const s=Xo(t.kind);return s?Ft(s).label:t.meta??null}function Xa(t,s,a){return Math.min(Math.max(t,s),a)}function Hs(t,s,a=3){const r=t.trim().split(/\s+/),i=[];let n="";for(let c=0;c<r.length;c+=1){const b=r[c],p=n?`${n} ${b}`:b;if(p.length>s&&n){if(i.push(n),i.length>=a-1){n=[b,...r.slice(c+1)].join(" ");break}n=b}else n=p}n&&i.push(n);const o=i.slice(0,a),d=o.length-1;return d>=0&&o[d].length>s&&(o[d]=`${o[d].slice(0,Math.max(1,s-1)).trimEnd()}…`),o}function qh(t,s){if(t.length===0&&s.length===0)return{minX:-360,maxX:360,minY:-240,maxY:240};let a=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,i=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(const o of t){const d=o.kind==="goal"||o.kind==="value"||o.kind==="ghost"?o.radius??32:(o.width??124)/2,c=o.kind==="goal"||o.kind==="value"||o.kind==="ghost"?o.radius??32:(o.height??56)/2,b=o.meta&&(o.kind==="goal"||o.kind==="ghost")?48:0;a=Math.min(a,o.x-d),r=Math.max(r,o.x+d),i=Math.min(i,o.y-c-b),n=Math.max(n,o.y+c)}for(const o of s)a=Math.min(a,o.x-o.radiusX),r=Math.max(r,o.x+o.radiusX),i=Math.min(i,o.y-o.radiusY),n=Math.max(n,o.y+o.radiusY);return{minX:a,maxX:r,minY:i,maxY:n}}function gr(t){return{x:t.x,y:t.y}}function Kh(t){if(t.kind==="goal"){const s=t.radius??112;return Hs(t.label,Math.max(14,Math.floor(s/7.2)),4)}if(t.kind==="value"||t.kind==="ghost"){const s=t.radius??40;return Hs(t.label,Math.max(12,Math.floor(s/3)),3)}return t.kind==="project"?Hs(t.label,Math.max(18,Math.floor((t.width??220)/10)),3):Hs(t.label,Math.max(16,Math.floor((t.width??180)/10.5)),2)}function Uh(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 Go({nodes:t,edges:s,fields:a=[],title:r,hint:i,action:n,legend:o,selectedNodeId:d,onSelectNode:c,minHeightClassName:b="min-h-[34rem] lg:min-h-[44rem]",compact:p=!1,testId:f}){const m=g.useRef(null),x=ht(),[v,w]=g.useState({width:0,height:0}),[h,P]=g.useState({scale:1,x:0,y:0}),[T,O]=g.useState(null),y=g.useRef(null),C=g.useRef({scale:1,x:0,y:0}),l=g.useRef(new Map),N=g.useRef(null),u=g.useRef(0),M=g.useRef(!1),A=g.useMemo(()=>new Map(t.map(L=>[L.id,L])),[t]),I=g.useMemo(()=>qh(t,a),[a,t]),j=v.width>0&&v.width<640;g.useEffect(()=>{if(!m.current||typeof ResizeObserver>"u")return;const L=new ResizeObserver(V=>{const le=V[0];w({width:le.contentRect.width,height:le.contentRect.height})});return L.observe(m.current),()=>L.disconnect()},[]);const S=g.useCallback(()=>{if(!v.width||!v.height)return;const L=j?132:p?140:190,V=Math.max(I.maxX-I.minX,1),le=Math.max(I.maxY-I.minY,1),ce=Xa(Math.min(v.width/(V+L),v.height/(le+L)),j?.24:p?.4:.46,j?.76:p?1.04:1.18),he=(I.minX+I.maxX)/2,je=(I.minY+I.maxY)/2;P({scale:ce,x:v.width/2-he*ce,y:v.height/2-je*ce})},[I.maxX,I.maxY,I.minX,I.minY,p,v.height,v.width,j]);g.useEffect(()=>{C.current=h},[h]),g.useEffect(()=>{M.current||S()},[S]);const E=g.useCallback((L,V,le)=>{const ce=Xa(L,.28,1.9);P(he=>{if(V==null||le==null)return{...he,scale:ce};const je=(V-he.x)/he.scale,W=(le-he.y)/he.scale;return{scale:ce,x:V-je*ce,y:le-W*ce}})},[]),X=g.useCallback(()=>{const L=[...l.current.values()];if(L.length<2){N.current=null;return}const[V,le]=L,ce=Math.hypot(le.x-V.x,le.y-V.y);if(!Number.isFinite(ce)||ce<=0){N.current=null;return}const he=C.current;N.current={startDistance:ce,startScale:he.scale,startViewportX:he.x,startViewportY:he.y,startMidpointX:(V.x+le.x)/2,startMidpointY:(V.y+le.y)/2}},[]),G=L=>{var ce;L.preventDefault();const V=(ce=m.current)==null?void 0:ce.getBoundingClientRect();if(!V)return;M.current=!0;const le=L.deltaY<0?1.1:.9;E(h.scale*le,L.clientX-V.left,L.clientY-V.top)},z=L=>{var he;const V=(he=m.current)==null?void 0:he.getBoundingClientRect(),le=L.clientX-((V==null?void 0:V.left)??0),ce=L.clientY-((V==null?void 0:V.top)??0);if(l.current.set(L.pointerId,{x:le,y:ce}),l.current.size===1){const je=C.current;y.current={pointerId:L.pointerId,originX:je.x,originY:je.y,startX:le,startY:ce}}else y.current=null,X();L.currentTarget.setPointerCapture(L.pointerId)},D=L=>{var W;const V=(W=m.current)==null?void 0:W.getBoundingClientRect(),le=L.clientX-((V==null?void 0:V.left)??0),ce=L.clientY-((V==null?void 0:V.top)??0);if(l.current.has(L.pointerId)&&l.current.set(L.pointerId,{x:le,y:ce}),N.current&&l.current.size>=2){const[$,k]=[...l.current.values()],R=Math.hypot(k.x-$.x,k.y-$.y);if(Number.isFinite(R)&&R>0){M.current=!0,u.current=Date.now()+240;const Q=($.x+k.x)/2,Ce=($.y+k.y)/2,ie=N.current,_e=Xa(ie.startScale*R/ie.startDistance,.24,1.42),J=(ie.startMidpointX-ie.startViewportX)/ie.startScale,H=(ie.startMidpointY-ie.startViewportY)/ie.startScale;P({scale:_e,x:Q-J*_e,y:Ce-H*_e})}return}if(!y.current||y.current.pointerId!==L.pointerId||l.current.size!==1)return;M.current=!0;const he=le-y.current.startX,je=ce-y.current.startY;(Math.abs(he)>3||Math.abs(je)>3)&&(u.current=Date.now()+240),P($=>{var k,R;return{...$,x:(((k=y.current)==null?void 0:k.originX)??$.x)+he,y:(((R=y.current)==null?void 0:R.originY)??$.y)+je}})},F=L=>{if(l.current.delete(L.pointerId),l.current.size<2&&(N.current=null),l.current.size===1){const[V,le]=[...l.current.entries()][0]??[];if(V!=null&&le){const ce=C.current;y.current={pointerId:V,originX:ce.x,originY:ce.y,startX:le.x,startY:le.y}}}else y.current=null;L.currentTarget.hasPointerCapture(L.pointerId)&&L.currentTarget.releasePointerCapture(L.pointerId)},q=T??d??null,Y=g.useCallback(L=>{Date.now()<u.current||(c==null||c(L.id),L.href&&x(L.href))},[x,c]);return e.jsxs("section",{"data-testid":f,className:te("overflow-hidden rounded-[32px] border border-white/8 bg-[radial-gradient(circle_at_top,rgba(125,211,252,0.12),transparent_32%),linear-gradient(180deg,rgba(11,18,31,0.985),rgba(7,12,23,0.98))] shadow-[0_26px_90px_rgba(2,6,16,0.38)]","px-3 py-3 sm:px-4 sm:py-4 lg:px-5 lg:py-5"),children:[e.jsxs("div",{className:"mb-3 flex min-w-0 flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-[rgba(125,211,252,0.82)]",children:"Gravity well"}),e.jsx("h2",{className:te("mt-2 font-display leading-none text-white",p?"text-[clamp(1.25rem,2vw,1.7rem)]":"text-[clamp(1.45rem,2.8vw,2.3rem)]"),children:r}),i?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.":i}):null]}),e.jsx("div",{className:"flex min-w-0 flex-wrap items-center justify-end gap-2",children:n})]}),e.jsxs("div",{ref:m,className:te("group relative overflow-hidden rounded-[30px] border border-white/6 bg-[radial-gradient(circle_at_center,rgba(255,255,255,0.04),transparent_46%)] touch-none",b),style:{touchAction:"none"},onWheel:G,onPointerDown:z,onPointerMove:D,onPointerUp:F,onPointerCancel:F,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:L=>L.stopPropagation(),children:[e.jsx(Ll,{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:L=>L.stopPropagation(),children:[e.jsx(K,{type:"button",variant:"secondary",size:"sm",className:"px-2.5 sm:px-3","aria-label":"Zoom in",onClick:()=>{M.current=!0,E(h.scale*1.12,v.width-96,72)},children:e.jsx(Ht,{className:"size-4"})}),e.jsx(K,{type:"button",variant:"secondary",size:"sm",className:"px-2.5 sm:px-3","aria-label":"Zoom out",onClick:()=>{M.current=!0,E(h.scale*.88,v.width-96,72)},children:e.jsx(Fl,{className:"size-4"})}),e.jsxs(K,{type:"button",variant:"secondary",size:"sm",className:"px-2.5 sm:min-w-[4.75rem] sm:px-3","aria-label":"Fit graph",onClick:()=>{M.current=!0,S()},children:[e.jsx(Ol,{className:"size-4"}),j?null:"Fit"]}),e.jsxs(K,{type:"button",variant:"secondary",size:"sm",className:"px-2.5 sm:min-w-[5.5rem] sm:px-3","aria-label":"Reset graph",onClick:()=>{M.current=!1,S()},children:[e.jsx(Rl,{className:"size-4"}),j?null:"Reset"]})]}),o&&o.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:o.map(L=>{const V=L.kind?Uh(L.kind):L.tone??"slate",le=L.kind?Ft(L.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:[le?e.jsx(le,{className:"size-3.5",color:Kt[V],strokeWidth:2.1}):e.jsx("span",{className:"size-2 rounded-full",style:{backgroundColor:qt[V]}}),L.label]},L.label)})}):null,e.jsxs("svg",{className:"relative z-[1] h-full w-full",viewBox:`0 0 ${v.width||1200} ${v.height||760}`,role:"img","aria-label":r,children:[e.jsx("defs",{children:e.jsx("filter",{id:"forge-graph-blur",children:e.jsx("feGaussianBlur",{stdDeviation:"34"})})}),e.jsxs("g",{transform:`translate(${h.x} ${h.y}) scale(${h.scale})`,children:[a.map(L=>e.jsx("ellipse",{cx:L.x,cy:L.y,rx:L.radiusX,ry:L.radiusY,fill:Qa[L.tone??"rose"],opacity:L.opacity??.42,filter:"url(#forge-graph-blur)"},L.id)),t.filter(L=>L.kind==="goal"||L.kind==="ghost").map(L=>{const V=L.radius??76;return e.jsx("g",{opacity:L.kind==="ghost"?.28:.55,children:[V+74,V+124].map((le,ce)=>e.jsx("circle",{cx:L.x,cy:L.y,r:le,fill:"none",stroke:ce===0?"rgba(255,255,255,0.08)":"rgba(255,255,255,0.045)",strokeDasharray:ce===0?"0":"10 10"},`${L.id}-ring-${le}`))},`${L.id}-orbital-lanes`)}),s.map(L=>{const V=A.get(L.from),le=A.get(L.to);if(!V||!le)return null;const ce=gr(V),he=gr(le),je=(ce.x+he.x)/2,W=(ce.y+he.y)/2,$=Math.max(24,Math.abs(ce.x-he.x)*.08),k=je,R=W-$;return e.jsx("path",{d:`M ${ce.x} ${ce.y} Q ${k} ${R} ${he.x} ${he.y}`,fill:"none",stroke:qt[L.tone??"slate"],strokeWidth:L.strength==="high"?3:L.strength==="medium"?2.2:1.6,strokeDasharray:L.dashed?"8 8":void 0,opacity:q&&L.from!==q&&L.to!==q?.18:.62},L.id)}),t.map(L=>{L.id;const V=T===L.id,le=q===L.id,ce=Bh(L),he=zh(L),je=Kh(L),W=Xo(L.kind),$=W?Ft(W).icon:null;if(L.kind==="goal"||L.kind==="value"||L.kind==="ghost"){const fe=L.radius??(L.kind==="goal"?76:34),ye=he?L.y-fe-(L.kind==="goal"?18:10):null,$e=L.kind==="goal"?20:14.5,ae=L.kind==="goal"?28:16,ot=L.kind==="goal"?L.y-fe*.34:L.kind==="value"?L.y-fe*.3:L.y-fe*.2,st=L.kind==="goal"?L.y+fe*.2:L.y+10;return e.jsxs("g",{tabIndex:0,role:"button",onPointerEnter:()=>{O(L.id),c==null||c(L.id)},onPointerLeave:()=>O(Je=>Je===L.id?null:Je),onFocus:()=>c==null?void 0:c(L.id),onClick:()=>Y(L),onKeyDown:Je=>{(Je.key==="Enter"||Je.key===" ")&&(Je.preventDefault(),Y(L))},className:"cursor-pointer outline-none",children:[e.jsx("circle",{cx:L.x,cy:L.y,r:fe+(le?14:0),fill:le?`${qt[ce]}22`:"transparent",stroke:le?qt[ce]:"transparent",opacity:V?.98:.9}),e.jsx("circle",{cx:L.x,cy:L.y,r:fe+(V?2:0),fill:L.kind==="ghost"?"rgba(255,255,255,0.03)":Qa[ce],stroke:L.kind==="ghost"?"rgba(255,255,255,0.18)":qt[ce],strokeDasharray:L.kind==="ghost"?"8 8":void 0,strokeWidth:le?2.8:1.6}),he?e.jsx("text",{x:L.x,y:ye??L.y-12,textAnchor:"middle",fontSize:L.kind==="goal"?"11.5":"10.5",fill:L.kind==="ghost"?"rgba(255,255,255,0.62)":Kt[ce],style:{letterSpacing:"0.18em",textTransform:"uppercase"},children:he}):null,$?e.jsx($,{x:L.x-ae/2,y:ot-ae/2,width:ae,height:ae,color:Kt[ce],strokeWidth:2.1}):null,je.map((Je,lt)=>e.jsx("text",{x:L.x,y:st+lt*$e-(je.length-1)*$e/2,textAnchor:"middle",fontSize:L.kind==="goal"?21:12.8,fontWeight:L.kind==="goal"?600:500,fill:L.kind==="ghost"?"rgba(255,255,255,0.92)":Kt[ce],children:Je},`${L.id}-${Je}-${lt}`))]},L.id)}const k=L.width??146,R=L.height??58,Q=L.x-k/2,Ce=L.y-R/2,ie=L.kind==="project"?14:13,_e=Q+14,J=Ce+13,H=Ce+22,pe=he?Ce+R*.65:Ce+R*.56,Ie=L.kind==="project"?16:15,Ye=L.kind==="project"?14.2:13.2;return e.jsxs("g",{tabIndex:0,role:"button",onPointerEnter:()=>{O(L.id),c==null||c(L.id)},onPointerLeave:()=>O(fe=>fe===L.id?null:fe),onFocus:()=>c==null?void 0:c(L.id),onClick:()=>Y(L),onKeyDown:fe=>{(fe.key==="Enter"||fe.key===" ")&&(fe.preventDefault(),Y(L))},className:"cursor-pointer outline-none",children:[e.jsx("rect",{x:Q-(le?6:0),y:Ce-(le?6:0),rx:"28",ry:"28",width:k+(le?12:0),height:R+(le?12:0),fill:le?`${qt[ce]}22`:"transparent"}),e.jsx("rect",{x:Q-(V?2:0),y:Ce-(V?2:0),rx:"22",ry:"22",width:k+(V?4:0),height:R+(V?4:0),fill:Qa[ce],stroke:qt[ce],strokeWidth:le?2.3:1.3}),$?e.jsx($,{x:_e,y:J,width:ie,height:ie,color:Kt[ce],strokeWidth:2.1}):null,he?e.jsx("text",{x:_e+ie+8,y:H,textAnchor:"start",fontSize:"9.5",fill:Kt[ce],style:{letterSpacing:"0.16em",textTransform:"uppercase",opacity:.82},children:he}):null,je.map((fe,ye)=>e.jsx("text",{x:L.x,y:pe+ye*Ie-(je.length-1)*Ie/2,textAnchor:"middle",fontSize:Ye,fontWeight:600,fill:Kt[ce],children:fe},`${L.id}-${fe}-${ye}`))]},L.id)})]})]})]})]})}const fr={intent:"trigger_report",linkedGoalId:"",linkedProjectId:"",linkedTaskId:""};function Qh({open:t,onOpenChange:s}){const a=ht(),r=Xe(),[i,n]=g.useState(fr),o=[{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:(c,b)=>e.jsx(Ke,{columns:3,value:c.intent,onChange:p=>b({intent:p}),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:(c,b)=>e.jsx("div",{className:"grid gap-4",children:e.jsx(B,{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(xe,{kind:"goal",label:"Goal",compact:!0,gradient:!1}),e.jsx(xe,{kind:"project",label:"Project",compact:!0,gradient:!1}),e.jsx(xe,{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:c.linkedGoalId,onChange:p=>b({linkedGoalId:p.target.value}),children:[e.jsx("option",{value:"",children:"No goal selected"}),r.snapshot.goals.map(p=>e.jsxs("option",{value:p.id,children:["Goal · ",p.title]},p.id))]}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:c.linkedProjectId,onChange:p=>b({linkedProjectId:p.target.value}),children:[e.jsx("option",{value:"",children:"No project selected"}),r.snapshot.dashboard.projects.map(p=>e.jsxs("option",{value:p.id,children:["Project · ",p.title]},p.id))]}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:c.linkedTaskId,onChange:p=>b({linkedTaskId:p.target.value}),children:[e.jsx("option",{value:"",children:"No task selected"}),r.snapshot.tasks.slice(0,40).map(p=>e.jsxs("option",{value:p.id,children:["Task · ",p.title]},p.id))]})]})})})}],d=async()=>{const c=new URLSearchParams({create:"1",intent:i.intent});switch(i.linkedGoalId&&c.set("goalId",i.linkedGoalId),i.linkedProjectId&&c.set("projectId",i.linkedProjectId),i.linkedTaskId&&c.set("taskId",i.linkedTaskId),i.intent){case"behavior":a(`/psyche/behaviors?${c.toString()}`);break;case"belief":a(`/psyche/schemas-beliefs?${c.toString()}`);break;case"pattern":a(`/psyche/patterns?${c.toString()}`);break;case"value":a(`/psyche/values?${c.toString()}`);break;case"execution_tension":case"trigger_report":default:a(`/psyche/reports?${c.toString()}`);break}s(!1),n(fr)};return e.jsx(He,{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:i,onChange:n,steps:o,submitLabel:"Open guided reflection",onSubmit:d})}const Ys=[{to:"/psyche",label:"Overview",icon:di},{to:"/psyche/values",label:"Values",icon:_l},{to:"/psyche/patterns",label:"Patterns",icon:$l},{to:"/psyche/behaviors",label:"Behaviors",icon:Bl},{to:"/psyche/reports",label:"Reports",icon:Gt},{to:"/psyche/goal-map",label:"Goal Map",icon:zl},{to:"/psyche/schemas-beliefs",label:"Schemas & Beliefs",icon:ql},{to:"/psyche/modes",label:"Modes",icon:Kl}];function Ga(t,s){return t===s||t.startsWith(`${s}/`)}function wt({className:t}){const s=pi(),[a,r]=g.useState(!1),i=g.useMemo(()=>[...Ys].sort((n,o)=>o.to.length-n.to.length).find(n=>Ga(s.pathname,n.to))??Ys[0],[s.pathname]);return e.jsxs(e.Fragment,{children:[e.jsxs(Z,{className:te("overflow-hidden bg-[linear-gradient(180deg,rgba(15,24,31,0.94),rgba(10,18,25,0.92))] p-2",t),children:[e.jsx("div",{className:"hidden items-center gap-3 lg:flex",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:Ys.map(n=>e.jsxs(Wt,{to:n.to,className:({isActive:o})=>te("inline-flex items-center gap-2 whitespace-nowrap rounded-full px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] transition",o||Ga(s.pathname,n.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(n.icon,{className:"size-3.5"}),e.jsx("span",{children:n.label})]},n.to))})}),e.jsx("div",{className:"flex items-center justify-between gap-3 lg:hidden",children:e.jsxs("button",{type:"button",className:"inline-flex min-w-0 flex-1 items-center justify-between rounded-full bg-white/[0.06] px-4 py-3 text-left",onClick:()=>r(!0),children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(i.icon,{className:"size-4 shrink-0 text-[var(--tertiary)]"}),e.jsx("span",{className:"truncate text-sm font-medium text-white",children:i.label})]}),e.jsx("span",{className:"text-[10px] uppercase tracking-[0.16em] text-white/42",children:"Switch"})]})})]}),a?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(K,{variant:"secondary",onClick:()=>r(!1),children:"Close"})]}),e.jsx("div",{className:"mt-6 grid gap-3 overflow-y-auto",children:Ys.map(n=>e.jsxs(Wt,{to:n.to,onClick:()=>r(!1),className:te("flex items-center justify-between rounded-[24px] px-4 py-4 transition",Ga(s.pathname,n.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(n.icon,{className:"size-4 text-[var(--tertiary)]"}),e.jsx("span",{className:"text-base font-medium",children:n.label})]}),e.jsx("span",{className:"text-[10px] uppercase tracking-[0.16em] text-white/36",children:"Open"})]},n.to))})]})}):null]})}function Xh(){var v;const t=Xe(),[s,a]=ut(),[r,i]=g.useState(s.get("reflect")==="1"),[n,o]=g.useState(null),d=oe({queryKey:["forge-psyche-overview"],queryFn:ka}),c=(v=d.data)==null?void 0:v.overview,b=g.useMemo(()=>c?t.snapshot.goals.slice(0,3).map(w=>{const h=c.values.filter(l=>l.linkedGoalIds.includes(w.id)),P=t.snapshot.dashboard.projects.filter(l=>l.goalId===w.id),T=t.snapshot.habits.filter(l=>l.linkedGoalIds.includes(w.id)||l.linkedValueIds.some(N=>h.some(u=>u.id===N))),O=c.reports.filter(l=>l.linkedGoalIds.includes(w.id)),y=c.behaviors.filter(l=>l.linkedValueIds.some(N=>h.some(u=>u.id===N))),C=c.beliefs.filter(l=>l.linkedValueIds.some(N=>h.some(u=>u.id===N)));return{goal:w,linkedValues:h,linkedProjects:P,linkedHabits:T,linkedReports:O,linkedBehaviors:y,linkedBeliefs:C}}):[],[c,t.snapshot.dashboard.projects,t.snapshot.goals,t.snapshot.habits]),p=g.useMemo(()=>Qo(b,{compact:!0}),[b]);if(g.useEffect(()=>{o(p.defaultSelectedId)},[p.defaultSelectedId]),d.isLoading)return e.jsx(xt,{});if(d.isError||!c)return e.jsx(Le,{eyebrow:"Psyche",error:d.error,onRetry:()=>void d.refetch()});const f=p.inspectors[n??p.defaultSelectedId]??p.inspectors[p.defaultSelectedId],m=c.patterns[0]??null,x=c.reports[0]??null;return e.jsxs("div",{className:"grid min-w-0 gap-4 overflow-x-clip",children:[e.jsx(Fe,{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:`${c.domain.title} active`,actions:e.jsx(e.Fragment,{children:e.jsx(Ne,{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(wt,{}),e.jsxs("section",{className:"grid min-w-0 gap-4 xl:grid-cols-[minmax(0,1fr)_19rem]",children:[e.jsx(Go,{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:p.nodes,edges:p.edges,fields:p.fields,selectedNodeId:n,onSelectNode:o,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(Ne,{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(K,{size:"sm",className:"min-w-0 sm:min-w-[6.5rem]",onClick:()=>i(!0),children:"Reflect"})]})}),e.jsxs(Z,{className:"h-fit min-w-0 xl:sticky xl:top-24",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:f.entityKind?e.jsx(xe,{kind:f.entityKind,compact:!0,gradient:!1,iconOnly:!0}):e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:f.eyebrow})}),e.jsx("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:f.entityKind?e.jsx(Te,{kind:f.entityKind,label:f.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:f.title})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/60",children:f.summary}),f.chips.length>0?e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:f.chips.map(w=>e.jsx(_,{className:"bg-white/[0.08] text-white/74",children:w},w))}):null,f.stats.length>0?e.jsx("div",{className:"mt-4 grid gap-2",children:f.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(Ne,{to:f.href,className:te("inline-flex min-h-11 w-full items-center justify-center rounded-[var(--radius-control)] px-4 py-2.5 text-sm font-medium whitespace-nowrap shadow-[0_12px_30px_rgba(192,193,255,0.08)]",f.entityKind?ws(f.entityKind,!0):"bg-[linear-gradient(135deg,rgba(192,193,255,0.36),rgba(192,193,255,0.22))] text-white"),children:f.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(At,{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(At,{to:x?`/psyche/reports/${x.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:c.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:c.openNotes})]})]}),e.jsx("div",{className:"mt-4 text-sm text-white/60",children:(x==null?void 0:x.title)||"Open the next chain and keep the report field live without adding more dashboard noise."})]})]}),e.jsx(Qh,{open:r,onOpenChange:w=>{i(w);const h=new URLSearchParams(s);h.delete("reflect"),a(h,{replace:!0})}})]})}function St({eyebrow:t,title:s,description:a,titleHelp:r,tone:i="default",children:n,className:o}){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:te("min-w-0 overflow-hidden rounded-[30px] border border-white/8 px-4 py-5 shadow-[0_24px_70px_rgba(4,8,18,0.28)] sm:px-5 lg:px-6",d[i],o),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}),r?e.jsx(Oe,{content:r,label:`Explain ${s.toLowerCase()}`,className:"mt-1 shrink-0"}):null]}),a?e.jsx("p",{className:"mt-3 max-w-3xl text-sm leading-7 text-white/60",children:a}):null,e.jsx("div",{className:"mt-5 min-w-0",children:n})]})}function Gh({entries:t}){const s={away:"border-rose-400/20 bg-[rgba(251,113,133,0.08)]",committed:"border-emerald-400/20 bg-[rgba(110,231,183,0.08)]",recovery:"border-amber-400/20 bg-[rgba(251,191,36,0.08)]"};return e.jsx("div",{className:"grid gap-3 lg:grid-cols-3",children:t.map(a=>e.jsxs(Ne,{to:a.href,className:`rounded-[22px] border px-4 py-4 transition hover:-translate-y-0.5 ${s[a.tone]}`,children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:a.tone}),e.jsx("div",{className:"mt-2 font-medium text-white",children:a.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:a.summary}),e.jsxs("div",{className:"mt-4 inline-flex items-center gap-2 text-sm text-white/54",children:["Open",e.jsx(Jt,{className:"size-3.5"})]})]},a.id))})}const Wh={maladaptive:"Maladaptive schema",adaptive:"Adaptive schema"},Hh={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."},Yh={disconnection_rejection:"Disconnection & rejection",impaired_autonomy:"Autonomy & competence",other_directedness:"Boundaries & mutuality",overvigilance_inhibition:"Standards & inhibition",healthy_selfhood:"Healthy selfhood"};function Aa(t){return Wh[t]}function Ns(t){return Hh[t]}function Fi(t){return Yh[t]??t.replaceAll("_"," ")}function os(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 br(t){return t.trim().toLowerCase()}function Wo(t,s){const a=br(s);return[t.id,t.slug,t.title].some(r=>br(r)===a)}function ls(t,s){return s.find(a=>Wo(a,t))??null}function Ho(t,s){const a=t.filter(r=>!Wo(s,r));return a.length===t.length?[...a,s.id]:a}function Lt({label:t,schemaType:s,compact:a=!1,showType:r=!1,className:i}){const n=os(s);return e.jsxs("span",{className:te("inline-flex max-w-full min-w-0 items-center gap-2 rounded-full border px-3 py-1.5 text-sm leading-tight shadow-[inset_0_1px_0_rgba(255,255,255,0.04)]",a?"min-h-8":"min-h-9",n.badgeTone,i),children:[r?e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/58",children:Aa(s)}):null,e.jsx("span",{className:"min-w-0 break-words whitespace-normal",children:t})]})}function Jh(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Rs(t){g.useEffect(()=>{if(!t||typeof document>"u")return;const s=window.requestAnimationFrame(()=>{const a=document.querySelector(`[data-psyche-focus-id="${Jh(t)}"]`);a&&a.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"})});return()=>window.cancelAnimationFrame(s)},[t])}function _s(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 et(t,s,a,r){t.setQueryData(s,i=>{const n=(i==null?void 0:i[a])??[];return n.some(o=>o.id===r.id)?i:{...i??{},[a]:[r,...n]}})}const Se=re().trim(),Ue=Se.min(1),Vh=be(Ue).transform(t=>Array.from(new Set(t))),vr=Re({title:Ue,description:Se,valuedDirection:Ue,whyItMatters:Se,linkedGoalIds:be(re()).default([]),linkedProjectIds:be(re()).default([]),linkedTaskIds:be(re()).default([]),committedActions:be(Se).default([])}),yr=Re({title:Ue,description:Se,targetBehavior:Ue,cueContexts:be(Se).default([]),shortTermPayoff:Se,longTermCost:Se,preferredResponse:Ue,linkedValueIds:be(re()).default([]),linkedSchemaLabels:Vh.default([]),linkedModeIds:be(re()).default([]),linkedBeliefIds:be(re()).default([])}),wr=Re({kind:Ge(["away","committed","recovery"]),title:Ue,description:Se,commonCues:be(Se).default([]),urgeStory:Se,shortTermPayoff:Se,longTermCost:Se,replacementMove:Se,repairPlan:Se,linkedPatternIds:be(re()).default([]),linkedValueIds:be(re()).default([]),linkedSchemaIds:be(re()).default([]),linkedModeIds:be(re()).default([])}),jr=Re({schemaId:re().nullable(),statement:Ue,beliefType:Ge(["absolute","conditional"]),originNote:Se,confidence:hi().int().min(0).max(100),evidenceFor:be(Se).default([]),evidenceAgainst:be(Se).default([]),flexibleAlternative:Se,linkedValueIds:be(re()).default([]),linkedBehaviorIds:be(re()).default([]),linkedModeIds:be(re()).default([]),linkedReportIds:be(re()).default([])}),kr=Re({family:Ge(["coping","child","critic_parent","healthy_adult","happy_child"]),archetype:Se,title:Ue,persona:Se,imagery:Se,symbolicForm:Se,facialExpression:Se,fear:Se,burden:Se,protectiveJob:Se,originContext:Se,firstAppearanceAt:re().trim().nullable(),linkedPatternIds:be(re()).default([]),linkedBehaviorIds:be(re()).default([]),linkedValueIds:be(re()).default([])}),Zh=Re({summary:Ue,answers:be(Re({questionKey:Ue,value:Ue})).min(1)});Re({label:Ue,description:Se});Re({label:Ue,description:Se,category:Se});const eu=Re({id:Ue,emotionDefinitionId:re().nullable(),label:Ue,intensity:hi().int().min(0).max(100),note:Se}),tu=Re({id:Ue,text:Ue,parentMode:Se,criticMode:Se,beliefId:re().nullable()}),su=Re({id:Ue,text:Ue,mode:Se,behaviorId:re().nullable()}),au=Re({id:Ue,stage:Ue,modeId:re().nullable(),label:Ue,note:Se}),ri=Re({title:Ue,status:Ge(["draft","reviewed","integrated"]).default("draft"),eventTypeId:re().nullable(),customEventType:Se,eventSituation:Ue,occurredAt:re().trim().nullable(),emotions:be(eu).default([]),thoughts:be(tu).default([]),behaviors:be(su).default([]),consequences:Re({selfShortTerm:be(Se).default([]),selfLongTerm:be(Se).default([]),othersShortTerm:be(Se).default([]),othersLongTerm:be(Se).default([])}),linkedPatternIds:be(re()).default([]),linkedValueIds:be(re()).default([]),linkedGoalIds:be(re()).default([]),linkedProjectIds:be(re()).default([]),linkedTaskIds:be(re()).default([]),linkedBehaviorIds:be(re()).default([]),linkedBeliefIds:be(re()).default([]),linkedModeIds:be(re()).default([]),modeOverlays:be(Se).default([]),schemaLinks:be(Se).default([]),modeTimeline:be(au).default([]),nextMoves:be(Se).default([])}),Js={kind:"away",title:"",description:"",commonCues:[],urgeStory:"",shortTermPayoff:"",longTermCost:"",replacementMove:"",repairPlan:"",linkedPatternIds:[],linkedValueIds:[],linkedSchemaIds:[],linkedModeIds:[]};function iu(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}}const Nr={away:"Away moves",committed:"Committed actions",recovery:"Recovery moves"};function nu(){var F,q,Y,L,V,le,ce,he,je,W,$;const t=Xe(),s=Qe(),[a,r]=ut(),[i,n]=g.useState(!1),[o,d]=g.useState(null),[c,b]=g.useState(Js),[p,f]=g.useState(null),m=oe({queryKey:["forge-psyche-behaviors"],queryFn:Bt}),x=oe({queryKey:["forge-psyche-patterns"],queryFn:Es}),v=oe({queryKey:["forge-psyche-values"],queryFn:$t}),w=oe({queryKey:["forge-psyche-schema-catalog"],queryFn:Ls}),h=oe({queryKey:["forge-psyche-modes"],queryFn:zt}),P=((F=m.data)==null?void 0:F.behaviors)??[],T=((q=x.data)==null?void 0:q.patterns)??[],O=((Y=v.data)==null?void 0:Y.values)??[],y=((L=w.data)==null?void 0:L.schemas)??[],C=((V=h.data)==null?void 0:V.modes)??[],l=a.get("focus"),N=t.snapshot.dashboard.notesSummaryByEntity;Rs(l),g.useEffect(()=>{if(a.get("create")==="1"){n(!0),d(null),b(Js);const k=new URLSearchParams(a);k.delete("create"),r(k,{replace:!0})}},[a,r]);const u=ue({mutationFn:async k=>{const R=wr.parse(k);return o?nc(o.id,R):Na(R)},onSuccess:async()=>{n(!1),d(null),b(Js),f(null),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-behaviors"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]})])}}),M=T.map(k=>({value:k.id,label:k.title,description:k.preferredResponse||k.targetBehavior,kind:"pattern"})),A=O.map(k=>({value:k.id,label:k.title,description:k.valuedDirection,kind:"value"})),I=y.map(k=>({value:k.id,label:k.title,description:`${k.description} ${Fi(k.family)}`,searchText:`${k.slug} ${k.family} ${k.schemaType}`,badge:e.jsx(Lt,{label:k.title,schemaType:k.schemaType,compact:!0}),menuBadge:e.jsx(Lt,{label:k.title,schemaType:k.schemaType,compact:!0})})),j=C.map(k=>({value:k.id,label:k.title,description:k.archetype||k.family,kind:"mode"})),S=async k=>{const{pattern:R}=await ki({title:k,description:"",targetBehavior:k,cueContexts:[],shortTermPayoff:"",longTermCost:"",preferredResponse:"",linkedValueIds:[],linkedSchemaLabels:[],linkedModeIds:[],linkedBeliefIds:[]});return et(s,["forge-psyche-patterns"],"patterns",R),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:R.id,label:R.title,description:R.preferredResponse||R.targetBehavior,kind:"pattern"}},E=async k=>{const{value:R}=await ms({title:k,description:"",valuedDirection:k,whyItMatters:"",linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],committedActions:[]});return et(s,["forge-psyche-values"],"values",R),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:R.id,label:R.title,description:R.valuedDirection,kind:"value"}},X=async k=>{const{mode:R}=await Fs({family:"coping",archetype:"",title:k,persona:"",imagery:"",symbolicForm:"",facialExpression:"",fear:"",burden:"",protectiveJob:"",originContext:"",firstAppearanceAt:null,linkedPatternIds:[],linkedBehaviorIds:[],linkedValueIds:[]});return et(s,["forge-psyche-modes"],"modes",R),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:R.id,label:R.title,description:R.archetype||R.family,kind:"mode"}},G=[{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:(k,R)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Behavior title",children:e.jsx(se,{value:k.title,onChange:Q=>R({title:Q.target.value}),placeholder:"Scroll to numb the impact"})}),e.jsx(B,{label:"What does the move look like?",children:e.jsx(ve,{value:k.description,onChange:Q=>R({description:Q.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:(k,R)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Common cues",children:e.jsx(ve,{value:k.commonCues.join(`
11
+ `),onChange:Q=>R({commonCues:Q.target.value.split(`
12
+ `).map(Ce=>Ce.trim()).filter(Boolean)}),placeholder:`One line per cue
13
+ Late-night ambiguity
14
+ Feedback after a hard week`})}),e.jsx(B,{label:"What inner push or story shows up?",children:e.jsx(ve,{value:k.urgeStory,onChange:Q=>R({urgeStory:Q.target.value}),placeholder:"What inner push or justification tends to appear?"})}),e.jsx(B,{label:"What do you get right away from this move?",children:e.jsx(ve,{value:k.shortTermPayoff,onChange:Q=>R({shortTermPayoff:Q.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:(k,R)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Move type",children:e.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:["away","committed","recovery"].map(Q=>e.jsx("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${k.kind===Q?"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:()=>R({kind:Q}),children:Nr[Q]},Q))})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(B,{label:"What does it cost over time?",children:e.jsx(ve,{value:k.longTermCost,onChange:Q=>R({longTermCost:Q.target.value}),placeholder:"What does this move cost over time?"})}),e.jsx(B,{label:"What move should replace or steady it?",children:e.jsx(ve,{value:k.replacementMove,onChange:Q=>R({replacementMove:Q.target.value}),placeholder:"What move should replace this one when possible?"})})]}),e.jsx(B,{label:"If the slip happens, how do you repair and return?",children:e.jsx(ve,{value:k.repairPlan,onChange:Q=>R({repairPlan:Q.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:(k,R)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Linked patterns",children:e.jsx(We,{options:M,selectedValues:k.linkedPatternIds,onChange:Q=>R({linkedPatternIds:Q}),placeholder:"Search or create a pattern…",emptyMessage:"No patterns match yet.",createLabel:"Create pattern",onCreate:S})}),e.jsx(B,{label:"Linked values",children:e.jsx(We,{options:A,selectedValues:k.linkedValueIds,onChange:Q=>R({linkedValueIds:Q}),placeholder:"Search or create a value…",emptyMessage:"No values match yet.",createLabel:"Create value",onCreate:E})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(B,{label:"Linked schemas",children:e.jsx(We,{options:I,selectedValues:k.linkedSchemaIds,onChange:Q=>R({linkedSchemaIds:Q}),placeholder:"Search schema themes…",emptyMessage:"No schema themes match."})}),e.jsx(B,{label:"Linked modes",children:e.jsx(We,{options:j,selectedValues:k.linkedModeIds,onChange:Q=>R({linkedModeIds:Q}),placeholder:"Search or create a mode…",emptyMessage:"No modes match yet.",createLabel:"Create mode",onCreate:X})})]})]})}];if(m.isLoading||x.isLoading||v.isLoading||w.isLoading||h.isLoading)return e.jsx(pt,{eyebrow:"Behaviors",title:"Loading behaviors",description:"Getting behaviors, patterns, values, schemas, and modes ready."});const z=m.error??x.error??v.error??w.error??h.error;if(z)return e.jsx(Le,{eyebrow:"Psyche behaviors",error:z,onRetry:()=>void Promise.all([m.refetch(),x.refetch(),v.refetch(),w.refetch(),h.refetch()])});const D={away:P.filter(k=>k.kind==="away"),committed:P.filter(k=>k.kind==="committed"),recovery:P.filter(k=>k.kind==="recovery")};return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Fe,{entityKind:"behavior",title:e.jsx(Te,{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:`${P.length} mapped`,actions:e.jsx(K,{onClick:()=>{d(null),b(Js),n(!0)},children:"Add behavior"})}),e.jsx(wt,{}),e.jsx(St,{eyebrow:"Overview",title:"Behavior summary",description:"This summary keeps the three behavior types visible together: away, committed, and recovery.",tone:"amber",children:e.jsx(Gh,{entries:[{id:"away",title:((le=D.away[0])==null?void 0:le.title)??"No away move mapped yet",summary:((ce=D.away[0])==null?void 0:ce.replacementMove)||"Map the move that tends to pull you away first.",href:"#behavior-columns",tone:"away"},{id:"committed",title:((he=D.committed[0])==null?void 0:he.title)??"No committed action mapped yet",summary:((je=D.committed[0])==null?void 0:je.replacementMove)||"Map the move you want to practice instead.",href:"#behavior-columns",tone:"committed"},{id:"recovery",title:((W=D.recovery[0])==null?void 0:W.title)??"No recovery move mapped yet",summary:(($=D.recovery[0])==null?void 0:$.repairPlan)||"Map how you return after a slip without turning it into collapse.",href:"#behavior-columns",tone:"recovery"}]})}),e.jsx(St,{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(k=>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:Nr[k]}),e.jsx(_,{children:D[k].length})]}),D[k].length===0?e.jsx("div",{className:"flex",children:e.jsxs(K,{variant:"secondary",onClick:()=>n(!0),children:["Add ",k==="away"?"away move":k==="committed"?"committed action":"recovery move"]})}):D[k].map(R=>e.jsxs("div",{"data-psyche-focus-id":R.id,className:`rounded-[22px] border border-white/8 bg-white/[0.04] p-4 text-left transition hover:bg-white/[0.08] ${_s(l===R.id)}`,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:R.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Ze,{entityType:"behavior",entityId:R.id,count:at(N,"behavior",R.id).count}),e.jsx(K,{variant:"secondary",size:"sm",onClick:()=>{d(R),b(iu(R)),n(!0)},children:"Edit"})]})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:R.description}),e.jsx("div",{className:"mt-3 text-sm text-white/46",children:R.replacementMove||R.repairPlan||"No recovery step recorded yet."})]},R.id))]},k))})}),e.jsx(He,{open:i,onOpenChange:n,eyebrow:"Behavior",title:o?"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:c,onChange:b,steps:G,submitLabel:o?"Save behavior":"Create behavior",pending:u.isPending,error:p,onSubmit:async()=>{f(null);const k=wr.safeParse(c);if(!k.success){f("This behavior still needs a kind and a title before it can be saved.");return}try{await u.mutateAsync(k.data)}catch(R){f(R instanceof Error?R.message:"Unable to save this behavior right now.")}}})]})}function ru(){var c;const t=Xe(),[s,a]=g.useState(null),r=oe({queryKey:["forge-psyche-overview"],queryFn:ka}),i=(c=r.data)==null?void 0:c.overview,n=g.useMemo(()=>i?t.snapshot.goals.map(b=>{const p=i.values.filter(h=>h.linkedGoalIds.includes(b.id)),f=t.snapshot.dashboard.projects.filter(h=>h.goalId===b.id),m=t.snapshot.habits.filter(h=>h.linkedGoalIds.includes(b.id)||h.linkedValueIds.some(P=>p.some(T=>T.id===P))),x=i.reports.filter(h=>h.linkedGoalIds.includes(b.id)),v=i.behaviors.filter(h=>h.linkedValueIds.some(P=>p.some(T=>T.id===P))),w=i.beliefs.filter(h=>h.linkedValueIds.some(P=>p.some(T=>T.id===P)));return{goal:b,linkedValues:p,linkedProjects:f,linkedHabits:m,linkedReports:x,linkedBehaviors:v,linkedBeliefs:w}}):[],[i,t.snapshot.dashboard.projects,t.snapshot.goals,t.snapshot.habits]),o=g.useMemo(()=>Qo(n),[n]);if(g.useEffect(()=>{a(o.defaultSelectedId)},[o.defaultSelectedId]),r.isLoading)return e.jsx(pt,{eyebrow:"Goal map",title:"Loading the gravity well",description:"Linking goals, values, reports, beliefs, behaviors, and projects back into execution."});if(r.isError||!i)return e.jsx(Le,{eyebrow:"Goal map",error:r.error??new Error("Forge returned an empty Psyche overview payload."),onRetry:()=>void r.refetch()});const d=o.inspectors[s??o.defaultSelectedId]??o.inspectors[o.defaultSelectedId];return e.jsxs("div",{className:"grid min-w-0 gap-4",children:[e.jsx(Fe,{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:`${n.length} goal${n.length===1?"":"s"}`,actions:e.jsxs(e.Fragment,{children:[e.jsx(Ne,{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(Ne,{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(wt,{}),e.jsxs("section",{className:"grid min-w-0 gap-4 xl:grid-cols-[minmax(0,1fr)_20rem]",children:[e.jsx(Go,{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:o.nodes,edges:o.edges,fields:o.fields,selectedNodeId:s,onSelectNode:a,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:n.length===0?e.jsx(Ne,{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(Ne,{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(Z,{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(xe,{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(Te,{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(_,{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(b=>e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/68",children:b},b))}):null,d.chips.length>0?e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:d.chips.map(b=>e.jsx(_,{className:"bg-white/[0.08] text-white/74",children:b},b))}):null,e.jsx("div",{className:"mt-5",children:e.jsx(Ne,{to:d.href,className:te("inline-flex min-h-11 w-full items-center justify-center rounded-[var(--radius-control)] px-4 py-2.5 text-sm font-medium whitespace-nowrap shadow-[0_12px_30px_rgba(192,193,255,0.08)]",d.entityKind?ws(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 ou(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 lu(t){const s=t.find(a=>a.isError);return{isLoading:t.some(a=>a.isPending||a.isLoading),error:s?ou(s.error):null}}async function du(t){await Promise.all(t.map(s=>s.refetch()))}const Vs={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 cu(){var d,c,b,p,f,m;const t=Qe(),s=oe({queryKey:["forge-psyche-mode-guide-sessions"],queryFn:lc}),a=la({defaultValues:{summary:"What mode was most present in this moment?",copingResponse:"none",childState:"none",criticStyle:"none",healthyContact:"none"}}),r=ue({mutationFn:async x=>{const v=Zh.parse({summary:x.summary,answers:[{questionKey:"coping_response",value:x.copingResponse},{questionKey:"child_state",value:x.childState},{questionKey:"critic_style",value:x.criticStyle},{questionKey:"healthy_contact",value:x.healthyContact}]});return dc(v)},onSuccess:async()=>{await t.invalidateQueries({queryKey:["forge-psyche-mode-guide-sessions"]})}}),i=[s],n=lu(i),o=((d=r.data)==null?void 0:d.session)??((b=(c=s.data)==null?void 0:c.sessions)==null?void 0:b[0]);return n.isLoading?e.jsx(pt,{eyebrow:"Mode guide",title:"Loading guided sessions",description:"Hydrating previous mode-guide runs and the latest stored readings."}):n.error?e.jsx(Le,{eyebrow:"Mode guide",error:n.error,onRetry:()=>void du(i)}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Fe,{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:`${((p=s.data)==null?void 0:p.sessions.length)??0} sessions`,actions:e.jsx(Ne,{to:"/psyche/modes",children:e.jsx(K,{variant:"secondary",children:"Back to mode map"})})}),e.jsx(wt,{}),e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]",children:[e.jsxs(Z,{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:a.handleSubmit(async x=>r.mutateAsync(x)),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",...a.register("summary")})]}),e.jsxs(Z,{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:Vs.copingResponse.map(x=>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:x.value,...a.register("copingResponse")}),e.jsx("span",{className:"text-white/74",children:x.label})]},x.value))})]}),e.jsxs(Z,{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:Vs.childState.map(x=>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:x.value,...a.register("childState")}),e.jsx("span",{className:"text-white/74",children:x.label})]},x.value))})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(Z,{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:Vs.criticStyle.map(x=>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:x.value,...a.register("criticStyle")}),e.jsx("span",{className:"text-white/74",children:x.label})]},x.value))})]}),e.jsxs(Z,{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:Vs.healthyContact.map(x=>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:x.value,...a.register("healthyContact")}),e.jsx("span",{className:"text-white/74",children:x.label})]},x.value))})]})]}),e.jsx(K,{type:"submit",children:"Run guide"})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(Z,{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"}),o?e.jsxs("div",{className:"mt-4 grid gap-3",children:[o.results.map(x=>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:x.label}),e.jsxs(_,{className:"text-white/70",children:[Math.round(x.confidence*100),"%"]})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:x.family.replaceAll("_"," ")}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/66",children:x.reasoning})]},`${x.family}:${x.label}`)),e.jsx(Ne,{to:"/psyche/modes",children:e.jsx(K,{variant:"secondary",children:"Use this in the mode map"})})]}):e.jsx("div",{className:"mt-4",children:e.jsx(rt,{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(Z,{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:(((f=s.data)==null?void 0:f.sessions)??[]).length===0?e.jsx(rt,{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(x=>e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:x.summary}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:x.results.map(v=>e.jsx(_,{className:"text-white/72",children:v.label},`${x.id}:${v.label}`))})]},x.id))})]})]})]})]})}const mu={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 hu({family:t,label:s,className:a}){return e.jsx("span",{className:te("inline-flex items-center rounded-full px-3 py-1.5 text-xs",mu[t],a),children:s})}const Zs={family:"coping",archetype:"",title:"",persona:"",imagery:"",symbolicForm:"",facialExpression:"",fear:"",burden:"",protectiveJob:"",originContext:"",firstAppearanceAt:null,linkedPatternIds:[],linkedBehaviorIds:[],linkedValueIds:[]};function uu(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}}const Wa={coping:"Coping",child:"Child",critic_parent:"Critic / parent",healthy_adult:"Healthy adult",happy_child:"Happy child"};function pu(){var G,z,D,F;const t=Xe(),s=Qe(),[a,r]=ut(),[i,n]=g.useState(!1),[o,d]=g.useState(null),[c,b]=g.useState(Zs),[p,f]=g.useState(null),m=oe({queryKey:["forge-psyche-modes"],queryFn:zt}),x=oe({queryKey:["forge-psyche-patterns"],queryFn:Es}),v=oe({queryKey:["forge-psyche-behaviors"],queryFn:Bt}),w=oe({queryKey:["forge-psyche-values"],queryFn:$t}),h=((G=m.data)==null?void 0:G.modes)??[],P=((z=x.data)==null?void 0:z.patterns)??[],T=((D=v.data)==null?void 0:D.behaviors)??[],O=((F=w.data)==null?void 0:F.values)??[],y=a.get("focus"),C=t.snapshot.dashboard.notesSummaryByEntity;Rs(y),g.useEffect(()=>{if(a.get("create")==="1"){n(!0),d(null),b(Zs);const q=new URLSearchParams(a);q.delete("create"),r(q,{replace:!0})}},[a,r]);const l=ue({mutationFn:async q=>{const Y=kr.parse(q);return o?oc(o.id,Y):Fs(Y)},onSuccess:async()=>{n(!1),d(null),b(Zs),f(null),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-modes"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]})])}}),N=P.map(q=>({value:q.id,label:q.title,description:q.preferredResponse||q.targetBehavior,kind:"pattern"})),u=T.map(q=>({value:q.id,label:q.title,description:q.kind,kind:"behavior"})),M=O.map(q=>({value:q.id,label:q.title,description:q.valuedDirection,kind:"value"})),A=async q=>{const{pattern:Y}=await ki({title:q,description:"",targetBehavior:q,cueContexts:[],shortTermPayoff:"",longTermCost:"",preferredResponse:"",linkedValueIds:[],linkedSchemaLabels:[],linkedModeIds:[],linkedBeliefIds:[]});return et(s,["forge-psyche-patterns"],"patterns",Y),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:Y.id,label:Y.title,description:Y.preferredResponse||Y.targetBehavior,kind:"pattern"}},I=async q=>{const{behavior:Y}=await Na({kind:"away",title:q,description:"",commonCues:[],urgeStory:"",shortTermPayoff:"",longTermCost:"",replacementMove:"",repairPlan:"",linkedPatternIds:[],linkedValueIds:[],linkedSchemaIds:[],linkedModeIds:[]});return et(s,["forge-psyche-behaviors"],"behaviors",Y),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:Y.id,label:Y.title,description:Y.kind,kind:"behavior"}},j=async q=>{const{value:Y}=await ms({title:q,description:"",valuedDirection:q,whyItMatters:"",linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],committedActions:[]});return et(s,["forge-psyche-values"],"values",Y),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:Y.id,label:Y.title,description:Y.valuedDirection,kind:"value"}},S=[{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:(q,Y)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{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(L=>e.jsx("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${q.family===L?"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:()=>Y({family:L}),children:Wa[L]},L))})}),e.jsx(B,{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(se,{value:q.title,onChange:L=>Y({title:L.target.value}),placeholder:"The Friday Vigil, The Scanner, The Good Son"})}),e.jsx(B,{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(se,{value:q.archetype,onChange:L=>Y({archetype:L.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:(q,Y)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(B,{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(ve,{value:q.persona,onChange:L=>Y({persona:L.target.value}),placeholder:"Quiet, hyper-alert, always scanning for threat and trying to stay one step ahead."})}),e.jsx(B,{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(ve,{value:q.imagery,onChange:L=>Y({imagery:L.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(B,{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(se,{value:q.symbolicForm,onChange:L=>Y({symbolicForm:L.target.value}),placeholder:"A locked visor, a fox, a steel shield"})}),e.jsx(B,{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(se,{value:q.facialExpression,onChange:L=>Y({facialExpression:L.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:(q,Y)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(B,{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(ve,{value:q.fear,onChange:L=>Y({fear:L.target.value}),placeholder:"If I relax, I will miss the threat and get hurt."})}),e.jsx(B,{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(ve,{value:q.burden,onChange:L=>Y({burden:L.target.value}),placeholder:"It believes it must never let the guard down, even when that means constant tension."})}),e.jsx(B,{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(ve,{value:q.protectiveJob,onChange:L=>Y({protectiveJob:L.target.value}),placeholder:"Keeps me prepared so I never get blindsided or look naive."})})]}),e.jsx(B,{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(ve,{value:q.originContext,onChange:L=>Y({originContext:L.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:(q,Y)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Linked patterns",description:"Choose the loops this mode tends to activate or maintain.",children:e.jsx(We,{options:N,selectedValues:q.linkedPatternIds,onChange:L=>Y({linkedPatternIds:L}),placeholder:"Search or create a pattern…",emptyMessage:"No patterns match yet.",createLabel:"Create pattern",onCreate:A})}),e.jsx(B,{label:"Linked behaviors",description:"Choose the moves this mode tends to trigger, justify, or amplify.",children:e.jsx(We,{options:u,selectedValues:q.linkedBehaviorIds,onChange:L=>Y({linkedBehaviorIds:L}),placeholder:"Search or create a behavior…",emptyMessage:"No behaviors match yet.",createLabel:"Create behavior",onCreate:I})}),e.jsx(B,{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(We,{options:M,selectedValues:q.linkedValueIds,onChange:L=>Y({linkedValueIds:L}),placeholder:"Search or create a value…",emptyMessage:"No values match yet.",createLabel:"Create value",onCreate:j})})]})}];if(m.isLoading||x.isLoading||v.isLoading||w.isLoading)return e.jsx(pt,{eyebrow:"Modes",title:"Loading modes",description:"Getting modes, linked patterns, behaviors, and values ready."});const E=m.error??x.error??v.error??w.error;if(E)return e.jsx(Le,{eyebrow:"Modes",error:E,onRetry:()=>void Promise.all([m.refetch(),x.refetch(),v.refetch(),w.refetch()])});const X={coping:h.filter(q=>q.family==="coping"),child:h.filter(q=>q.family==="child"),critic_parent:h.filter(q=>q.family==="critic_parent"),healthy_adult:h.filter(q=>q.family==="healthy_adult"),happy_child:h.filter(q=>q.family==="happy_child")};return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Fe,{entityKind:"mode",title:e.jsx(Te,{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:`${h.length} modes`,actions:e.jsx(K,{onClick:()=>{d(null),b(Zs),n(!0)},children:"Add mode"})}),e.jsx(wt,{}),e.jsx(St,{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:h.length===0?e.jsx("div",{className:"flex justify-start",children:e.jsx(K,{onClick:()=>n(!0),children:"Add mode"})}):e.jsx("div",{className:"grid gap-4 xl:grid-cols-2",children:Object.keys(X).map(q=>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(hu,{family:q,label:Wa[q]}),e.jsx(_,{children:X[q].length})]}),X[q].length===0?e.jsx("div",{className:"flex",children:e.jsxs(K,{variant:"secondary",onClick:()=>n(!0),children:["Add ",Wa[q].toLowerCase()]})}):X[q].map(Y=>e.jsxs("div",{"data-psyche-focus-id":Y.id,className:`rounded-[22px] bg-white/[0.04] p-4 text-left transition hover:bg-white/[0.08] ${_s(y===Y.id)}`,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(xe,{kind:"mode",compact:!0,gradient:!1}),e.jsx(Te,{kind:"mode",label:Y.title,variant:"heading",size:"lg"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Ze,{entityType:"mode_profile",entityId:Y.id,count:at(C,"mode_profile",Y.id).count}),e.jsx(K,{variant:"secondary",size:"sm",onClick:()=>{d(Y),b(uu(Y)),n(!0)},children:"Edit"})]})]}),e.jsx("div",{className:"mt-2 text-sm text-white/52",children:Y.archetype}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/62",children:Y.persona||Y.protectiveJob||"Open the mode to add persona and protective details."})]},Y.id))]},q))})}),e.jsx(He,{open:i,onOpenChange:n,eyebrow:"Mode",title:o?"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:c,onChange:b,steps:S,submitLabel:o?"Save mode":"Create mode",pending:l.isPending,error:p,onSubmit:async()=>{f(null);const q=kr.safeParse(c);if(!q.success){f("This mode still needs a family and a name before it can be saved.");return}try{await l.mutateAsync(q.data)}catch(Y){f(Y instanceof Error?Y.message:"Unable to save this mode right now.")}}})]})}const xu={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 Ha(t,s,a){return Math.min(Math.max(t,s),a)}function gu(t){const s=t.detail.trim().length;return s>84?130:s>44?118:106}function fu(t,s,a){const r=s/2,i=a/2,n=Ha(Math.min(s/620,a/430),.64,1.06),o=t.map(m=>{const x=m.angle*Math.PI/180,v=m.radius*n,w=Math.min(184,Math.max(154,s-48)),h=gu(m),P=r+Math.cos(x)*v,T=i+Math.sin(x)*v;return{...m,x:P,y:T,width:w,height:h,homeX:P,homeY:T}}),d=s<720?16:22,c=20,b=s-20,p=18,f=a-18;for(let m=0;m<220;m+=1){for(const x of o)x.x+=(x.homeX-x.x)*.065,x.y+=(x.homeY-x.y)*.065;for(let x=0;x<o.length;x+=1)for(let v=x+1;v<o.length;v+=1){const w=o[x],h=o[v],P=h.x-w.x,T=h.y-w.y,O=w.width/2+h.width/2+d-Math.abs(P),y=w.height/2+h.height/2+d-Math.abs(T);if(O<=0||y<=0)continue;const C=O<y?"x":"y",l=Math.sign(C==="x"?P||v-x||1:T||v-x||1),N=(C==="x"?O:y)/2;C==="x"?(w.x-=l*N,h.x+=l*N):(w.y-=l*N,h.y+=l*N)}for(const x of o)x.x=Ha(x.x,c+x.width/2,b-x.width/2),x.y=Ha(x.y,p+x.height/2,f-x.height/2)}return o}function Yo({title:t,description:s,centerLabel:a,centerValue:r,nodes:i,action:n}){const o=g.useRef(null),[d,c]=g.useState({width:0,height:0});g.useEffect(()=>{if(!o.current||typeof ResizeObserver>"u")return;const f=new ResizeObserver(m=>{const x=m[0];c({width:x.contentRect.width,height:x.contentRect.height})});return f.observe(o.current),()=>f.disconnect()},[]);const b=i.length>0?i:[{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"}],p=g.useMemo(()=>fu(b,Math.max(d.width,320),Math.max(d.height,320)),[b,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:a}),e.jsx("span",{className:"text-sm font-medium text-white",children:r})]}),n?e.jsx("div",{className:"shrink-0",children:n}):null]})]}),e.jsxs("div",{ref:o,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(f=>e.jsx("div",{className:"absolute left-1/2 top-1/2 rounded-full border border-white/[0.05]",style:{width:`${f*2}px`,height:`${f*2}px`,transform:"translate(-50%, -50%)"}},f)),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:a}),e.jsx("div",{className:"mt-2 font-display text-2xl text-white",children:r})]})}),p.map((f,m)=>e.jsx(Ve.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:`${f.x}px`,top:`${f.y}px`},whileHover:{y:-6,scale:1.03},children:e.jsxs(Ne,{to:f.href,className:te("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)]",xu[f.tone??"mint"]),children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/45",children:f.label}),e.jsx("div",{className:"mt-1.5 font-medium text-white",children:f.title}),e.jsx("div",{className:"mt-1.5 text-sm leading-5 text-white/62",children:f.detail})]})},f.id))]})]})}const ea={title:"",description:"",targetBehavior:"",cueContexts:[],shortTermPayoff:"",longTermCost:"",preferredResponse:"",linkedValueIds:[],linkedSchemaLabels:[],linkedModeIds:[],linkedBeliefIds:[]};function bu(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}}function vu(){var L,V,le,ce,he,je;const t=Xe(),s=Qe(),[a,r]=ut(),[i,n]=g.useState(!1),[o,d]=g.useState(null),[c,b]=g.useState(ea),[p,f]=g.useState(null),m=oe({queryKey:["forge-psyche-patterns"],queryFn:Es}),x=oe({queryKey:["forge-psyche-values"],queryFn:$t}),v=oe({queryKey:["forge-psyche-schema-catalog"],queryFn:Ls}),w=oe({queryKey:["forge-psyche-modes"],queryFn:zt}),h=oe({queryKey:["forge-psyche-beliefs"],queryFn:hs}),P=oe({queryKey:["forge-psyche-behaviors"],queryFn:Bt}),T=((L=m.data)==null?void 0:L.patterns)??[],O=((V=x.data)==null?void 0:V.values)??[],y=((le=v.data)==null?void 0:le.schemas)??[],C=((ce=w.data)==null?void 0:ce.modes)??[],l=((he=h.data)==null?void 0:he.beliefs)??[],N=((je=P.data)==null?void 0:je.behaviors)??[],u=a.get("focus"),M=t.snapshot.dashboard.notesSummaryByEntity;Rs(u),g.useEffect(()=>{if(a.get("create")==="1"){n(!0),d(null),b(ea);const W=new URLSearchParams(a);W.delete("create"),r(W,{replace:!0})}},[a,r]);const A=ue({mutationFn:async W=>{const $=yr.parse(W);return o?ic(o.id,$):ki($)},onSuccess:async()=>{n(!1),d(null),b(ea),f(null),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-patterns"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]})])}}),I=O.map(W=>({value:W.id,label:W.title,description:W.valuedDirection,kind:"value"})),j=y.map(W=>({value:W.title,label:W.title,description:`${W.description} ${Fi(W.family)}`,searchText:`${W.slug} ${W.family} ${W.schemaType}`,badge:e.jsx(Lt,{label:W.title,schemaType:W.schemaType,compact:!0}),menuBadge:e.jsx(Lt,{label:W.title,schemaType:W.schemaType,compact:!0})})),S=C.map(W=>({value:W.id,label:W.title,description:W.archetype||W.family,kind:"mode"})),E=l.map(W=>({value:W.id,label:W.statement,description:W.flexibleAlternative||W.originNote,kind:"belief"})),X=async W=>{const{mode:$}=await Fs({family:"coping",archetype:"",title:W,persona:"",imagery:"",symbolicForm:"",facialExpression:"",fear:"",burden:"",protectiveJob:"",originContext:"",firstAppearanceAt:null,linkedPatternIds:[],linkedBehaviorIds:[],linkedValueIds:[]});return et(s,["forge-psyche-modes"],"modes",$),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:$.id,label:$.title,description:$.archetype||$.family,kind:"mode"}},G=async W=>{const{value:$}=await ms({title:W,description:"",valuedDirection:W,whyItMatters:"",linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],committedActions:[]});return et(s,["forge-psyche-values"],"values",$),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:$.id,label:$.title,description:$.valuedDirection,kind:"value"}},z=async W=>{const{belief:$}=await Ni({schemaId:null,statement:W,beliefType:"absolute",originNote:"",confidence:60,evidenceFor:[],evidenceAgainst:[],flexibleAlternative:"",linkedValueIds:[],linkedBehaviorIds:[],linkedModeIds:[],linkedReportIds:[]});return et(s,["forge-psyche-beliefs"],"beliefs",$),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:$.id,label:$.statement,description:$.flexibleAlternative||$.originNote,kind:"belief"}},D=g.useMemo(()=>T.filter(W=>!N.some($=>$.kind==="away"&&$.linkedPatternIds.includes(W.id))),[T,N]),F=T.slice(0,5).map((W,$)=>({id:W.id,label:`${W.linkedValueIds.length} values`,title:W.title,detail:W.preferredResponse,href:`/psyche/patterns?focus=${W.id}#pattern-lanes`,angle:-92+$*70,radius:150+$%2*14,tone:["rose","sky","violet","mint"][$%4]})),q=[{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:(W,$)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Pattern name",description:"Give the loop a name you will recognize quickly later.",children:e.jsx(se,{value:W.title,onChange:k=>$({title:k.target.value}),placeholder:"Anxious reassurance loop"})}),e.jsx(B,{label:"What happens in the loop",description:"Describe the actual sequence of behavior, not the diagnosis.",children:e.jsx(ve,{value:W.targetBehavior,onChange:k=>$({targetBehavior:k.target.value}),placeholder:"What do you actually do when the trigger hits?"})}),e.jsx(B,{label:"Description",description:"Write the loop in plain language so it stays usable in the future.",children:e.jsx(ve,{value:W.description,onChange:k=>$({description:k.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:(W,$)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Common cues",description:"Add one cue per line so the trigger pattern stays easy to scan.",children:e.jsx(ve,{value:W.cueContexts.join(`
15
+ `),onChange:k=>$({cueContexts:k.target.value.split(`
16
+ `).map(R=>R.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(B,{label:"Short-term payoff",description:"What relief, certainty, control, or distance do you get right away?",children:e.jsx(ve,{value:W.shortTermPayoff,onChange:k=>$({shortTermPayoff:k.target.value}),placeholder:"What relief do you get right away?"})}),e.jsx(B,{label:"Long-term cost",description:"What does the loop cost you later in closeness, energy, values, or progress?",children:e.jsx(ve,{value:W.longTermCost,onChange:k=>$({longTermCost:k.target.value}),placeholder:"What does this cost over time?"})})]}),e.jsx(B,{label:"Preferred response",description:"Name the return-path response you want to practice instead.",children:e.jsx(ve,{value:W.preferredResponse,onChange:k=>$({preferredResponse:k.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:(W,$)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Linked values",description:"Choose the values this loop pulls against or tries to protect badly.",children:e.jsx(We,{options:I,selectedValues:W.linkedValueIds,onChange:k=>$({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(B,{label:"Schema labels",description:"Attach the schema themes that define the pressure in this loop.",children:e.jsx(We,{options:j,selectedValues:W.linkedSchemaLabels,onChange:k=>$({linkedSchemaLabels:k}),placeholder:"Search schema themes…",emptyMessage:"No schema themes match."})}),e.jsx(B,{label:"Linked modes",description:"Search for an existing mode or press Enter to create and link one immediately.",children:e.jsx(We,{options:S,selectedValues:W.linkedModeIds,onChange:k=>$({linkedModeIds:k}),placeholder:"Search or create a mode…",emptyMessage:"No modes match yet.",createLabel:"Create mode",onCreate:X})})]}),e.jsx(B,{label:"Linked beliefs",description:"Search for a belief, or type a new one and press Enter to create it inline.",children:e.jsx(We,{options:E,selectedValues:W.linkedBeliefIds,onChange:k=>$({linkedBeliefIds:k}),placeholder:"Search or create a belief…",emptyMessage:"No beliefs match yet.",createLabel:"Create belief",onCreate:z})})]})}];if(m.isLoading||x.isLoading||v.isLoading||w.isLoading||h.isLoading||P.isLoading)return e.jsx(pt,{eyebrow:"Patterns",title:"Loading patterns",description:"Getting patterns, values, schemas, beliefs, modes, and linked behaviors ready."});const Y=m.error??x.error??v.error??w.error??h.error??P.error;return Y?e.jsx(Le,{eyebrow:"Psyche patterns",error:Y,onRetry:()=>void Promise.all([m.refetch(),x.refetch(),v.refetch(),w.refetch(),h.refetch(),P.refetch()])}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Fe,{entityKind:"pattern",title:e.jsx(Te,{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:`${T.length} patterns`,actions:e.jsx(K,{onClick:()=>{d(null),b(ea),n(!0)},children:"Add pattern"})}),e.jsx(wt,{}),e.jsx(Yo,{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:`${T.length} tracked`,nodes:F,action:e.jsx(K,{onClick:()=>n(!0),children:"Add pattern"})}),D.length>0?e.jsx(St,{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:D.slice(0,8).map(W=>e.jsx(xe,{kind:"pattern",label:W.title,compact:!0},W.id))})}):null,e.jsx(St,{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:T.length===0?e.jsx("div",{className:"flex justify-start",children:e.jsx(K,{onClick:()=>n(!0),children:"Add pattern"})}):T.map(W=>{const $=O.filter(ie=>W.linkedValueIds.includes(ie.id)),k=C.filter(ie=>W.linkedModeIds.includes(ie.id)),R=l.filter(ie=>W.linkedBeliefIds.includes(ie.id)),Q=u===W.id,Ce=at(M,"behavior_pattern",W.id).count;return e.jsxs("div",{"data-psyche-focus-id":W.id,className:`rounded-[28px] border border-white/8 bg-white/[0.04] p-5 transition ${_s(Q)}`,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(Te,{kind:"pattern",label:W.title,variant:"heading",size:"xl"}),e.jsx("div",{className:"mt-2 text-sm leading-7 text-white/58",children:W.description})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Ze,{entityType:"behavior_pattern",entityId:W.id,count:Ce}),e.jsx(K,{variant:"secondary",onClick:()=>{d(W),b(bu(W)),n(!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:W.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:W.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:W.shortTermPayoff||"No payoff note yet."}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/52",children:W.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:W.preferredResponse})]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[$.map(ie=>e.jsx(xe,{kind:"value",label:ie.title,compact:!0},ie.id)),k.map(ie=>e.jsx(xe,{kind:"mode",label:ie.title,compact:!0},ie.id)),W.linkedModeLabels.map(ie=>e.jsx(_,{className:"text-violet-100",children:ie},`legacy-${ie}`)),W.linkedSchemaLabels.map(ie=>{var _e,J;return e.jsx(Lt,{label:((_e=ls(ie,y))==null?void 0:_e.title)??ie,schemaType:((J=ls(ie,y))==null?void 0:J.schemaType)??"maladaptive",compact:!0},ie)}),R.map(ie=>e.jsx(xe,{kind:"belief",label:ie.statement,compact:!0},ie.id))]})]},W.id)})})}),e.jsx(He,{open:i,onOpenChange:n,eyebrow:"Behavior pattern",title:o?"Refine pattern lane":"Create pattern",description:"Pattern capture should feel like mapping a loop, not filling an admin form.",value:c,onChange:b,steps:q,submitLabel:o?"Save pattern":"Create pattern",pending:A.isPending,error:p,onSubmit:async()=>{f(null);const W=yr.safeParse(c);if(!W.success){f("This pattern still needs a title, a loop description, and a preferred response.");return}try{await A.mutateAsync(W.data)}catch($){f($ instanceof Error?$.message:"Unable to save this pattern right now.")}}})]})}const Cr="(max-width: 1023px)";function yu(){const[t,s]=g.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(Cr).matches);return g.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const a=window.matchMedia(Cr),r=i=>s(i.matches);return s(a.matches),typeof a.addEventListener=="function"?(a.addEventListener("change",r),()=>a.removeEventListener("change",r)):(a.addListener(r),()=>a.removeListener(r))},[]),t}function wu({stages:t,activeStageId:s,onStageChange:a,stageContent:r,inspector:i}){const n=yu(),[o,d]=g.useState(!1),c=t.find(b=>b.id===s);return g.useEffect(()=>{d(!n)},[n]),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:c==null?void 0:c.summary})]}),i?e.jsxs(K,{variant:"secondary",size:"sm",onClick:()=>d(b=>!b),children:[o?e.jsx(Ul,{className:"size-4"}):e.jsx(Ql,{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((b,p)=>e.jsxs("button",{type:"button",className:te("rounded-[22px] px-4 py-3 text-left transition",b.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:()=>a(b.id),children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/34",children:[p+1,". ",b.label]}),n?null:e.jsx("div",{className:"mt-1.5 text-sm leading-5",children:b.summary})]},b.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:c==null?void 0:c.label}),e.jsx("span",{className:"text-sm text-white/54",children:c==null?void 0:c.summary})]}),e.jsx(Yt,{mode:"wait",children:e.jsx(Ve.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},exit:{opacity:0,y:-14},transition:{duration:.26,ease:"easeOut"},children:r},s)})]})]}),i?e.jsx(Yt,{initial:!1,children:o?e.jsxs(Ve.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:i})]}):null}):null]})}function Da(t){return`${t}_${Math.random().toString(36).slice(2,10)}`}function ju(){return{id:Da("emotion"),emotionDefinitionId:null,label:"",intensity:55,note:""}}function ku(){return{id:Da("thought"),text:"",parentMode:"",criticMode:"",beliefId:null}}function Nu(){return{id:Da("behavior"),text:"",mode:"",behaviorId:null}}function Cu(){return{id:Da("timeline"),stage:"",modeId:null,label:"",note:""}}function $s({title:t,description:s,onAdd:a,addLabel:r}){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(K,{type:"button",variant:"secondary",size:"sm",onClick:a,children:[e.jsx(Ht,{className:"size-4"}),r]})]})}function Bs({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(yt,{className:"size-4"})})}function ft({title:t,description:s,addLabel:a,items:r,onChange:i,placeholder:n}){return e.jsxs("div",{className:"grid gap-3",children:[e.jsx($s,{title:t,description:s,addLabel:a,onAdd:()=>i([...r,""])}),e.jsx("div",{className:"grid gap-3",children:r.map((o,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(se,{value:o,onChange:c=>i(r.map((b,p)=>p===d?c.target.value:b)),placeholder:n}),e.jsx(Bs,{onClick:()=>i(r.filter((c,b)=>b!==d))})]},`${t}-${d}`))})]})}function Jo({items:t,onChange:s,definitions:a}){return e.jsxs("div",{className:"grid gap-3",children:[e.jsx($s,{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,ju()])}),e.jsx("div",{className:"grid gap-3",children:t.map(r=>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:r.emotionDefinitionId??"",onChange:i=>{const n=a.find(o=>o.id===i.target.value);s(t.map(o=>o.id===r.id?{...o,emotionDefinitionId:i.target.value||null,label:(n==null?void 0:n.label)??o.label}:o))},children:[e.jsx("option",{value:"",children:"Choose or type your own"}),a.map(i=>e.jsx("option",{value:i.id,children:i.label},i.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:r.intensity,onChange:i=>s(t.map(n=>n.id===r.id?{...n,intensity:Number(i.target.value)}:n))}),e.jsxs("div",{className:"mt-2 text-sm text-white/52",children:[r.intensity,"%"]})]})]})]}),e.jsx(Bs,{onClick:()=>s(t.filter(i=>i.id!==r.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(se,{value:r.label,onChange:i=>s(t.map(n=>n.id===r.id?{...n,label:i.target.value}:n)),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(ve,{value:r.note,onChange:i=>s(t.map(n=>n.id===r.id?{...n,note:i.target.value}:n)),placeholder:"Short note about what made this emotion stand out."})]})]},r.id))})]})}function Vo({items:t,onChange:s,beliefs:a,modes:r}){return e.jsxs("div",{className:"grid gap-3",children:[e.jsx($s,{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,ku()])}),e.jsx("div",{className:"grid gap-3",children:t.map(i=>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(ve,{value:i.text,onChange:n=>s(t.map(o=>o.id===i.id?{...o,text:n.target.value}:o)),placeholder:"What sentence, image, or conclusion showed up?"})]}),e.jsx(Bs,{onClick:()=>s(t.filter(n=>n.id!==i.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:i.parentMode,onChange:n=>s(t.map(o=>o.id===i.id?{...o,parentMode:n.target.value}:o)),children:[e.jsx("option",{value:"",children:"None"}),r.map(n=>e.jsx("option",{value:n.title,children:n.title},n.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:i.criticMode,onChange:n=>s(t.map(o=>o.id===i.id?{...o,criticMode:n.target.value}:o)),children:[e.jsx("option",{value:"",children:"None"}),r.map(n=>e.jsx("option",{value:n.title,children:n.title},n.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:i.beliefId??"",onChange:n=>s(t.map(o=>o.id===i.id?{...o,beliefId:n.target.value||null}:o)),children:[e.jsx("option",{value:"",children:"None"}),a.map(n=>e.jsx("option",{value:n.id,children:n.statement},n.id))]})]})]})]},i.id))})]})}function Zo({items:t,onChange:s,behaviors:a,modes:r}){return e.jsxs("div",{className:"grid gap-3",children:[e.jsx($s,{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,Nu()])}),e.jsx("div",{className:"grid gap-3",children:t.map(i=>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(ve,{value:i.text,onChange:n=>s(t.map(o=>o.id===i.id?{...o,text:n.target.value}:o)),placeholder:"What did you do, or what move did you feel pulled toward?"})]}),e.jsx(Bs,{onClick:()=>s(t.filter(n=>n.id!==i.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:i.behaviorId??"",onChange:n=>{const o=a.find(d=>d.id===n.target.value);s(t.map(d=>d.id===i.id?{...d,behaviorId:n.target.value||null,text:o&&!d.text?o.title:d.text}:d))},children:[e.jsx("option",{value:"",children:"None"}),a.map(n=>e.jsx("option",{value:n.id,children:n.title},n.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:i.mode,onChange:n=>s(t.map(o=>o.id===i.id?{...o,mode:n.target.value}:o)),children:[e.jsx("option",{value:"",children:"None"}),r.map(n=>e.jsx("option",{value:n.title,children:n.title},n.id))]})]})]})]},i.id))})]})}function el({items:t,onChange:s,modes:a,stages:r}){return e.jsxs("div",{className:"grid gap-3",children:[e.jsx($s,{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,Cu()])}),e.jsx("div",{className:"grid gap-3",children:t.map(i=>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:i.stage,onChange:n=>s(t.map(o=>o.id===i.id?{...o,stage:n.target.value}:o)),children:[e.jsx("option",{value:"",children:"Choose stage"}),r.map(n=>e.jsx("option",{value:n,children:n},n))]})]}),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:i.modeId??"",onChange:n=>{const o=a.find(d=>d.id===n.target.value);s(t.map(d=>d.id===i.id?{...d,modeId:n.target.value||null,label:o&&!d.label?o.title:d.label}:d))},children:[e.jsx("option",{value:"",children:"Choose mode"}),a.map(n=>e.jsx("option",{value:n.id,children:n.title},n.id))]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"Moment label"}),e.jsx(se,{value:i.label,onChange:n=>s(t.map(o=>o.id===i.id?{...o,label:n.target.value}:o)),placeholder:"What was happening in this moment?"})]})]}),e.jsx(Bs,{onClick:()=>s(t.filter(n=>n.id!==i.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(ve,{value:i.note,onChange:n=>s(t.map(o=>o.id===i.id?{...o,note:n.target.value}:o)),placeholder:"Short note about how the mode showed up or what it was protecting."})]})]},i.id))})]})}function Su(t){return t.join(`
19
+ `)}function Ya(t,s){return t.includes(s)?t.filter(a=>a!==s):[...t,s]}function Tu(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:Su(t.modeOverlays),schemaLinks:t.schemaLinks,modeTimeline:t.modeTimeline,nextMoves:t.nextMoves,linkedBehaviorIds:t.linkedBehaviorIds,linkedBeliefIds:t.linkedBeliefIds,linkedModeIds:t.linkedModeIds}}function Iu(){var S,E,X,G,z,D;const{reportId:t}=fa(),s=Qe(),[a,r]=g.useState("spark"),[i,n]=g.useState(null),[o,d]=g.useState(!1),c=oe({queryKey:["forge-psyche-report",t],queryFn:()=>cc(t),enabled:!!t}),b=oe({queryKey:["forge-psyche-behaviors"],queryFn:Bt}),p=oe({queryKey:["forge-psyche-beliefs"],queryFn:hs}),f=oe({queryKey:["forge-psyche-modes"],queryFn:zt}),m=oe({queryKey:["forge-psyche-schema-catalog"],queryFn:Ls}),x=oe({queryKey:["forge-psyche-event-types"],queryFn:so}),v=oe({queryKey:["forge-psyche-emotions"],queryFn:ao});g.useEffect(()=>{var F;(F=c.data)!=null&&F.report&&n(Tu(c.data.report))},[c.data]);const w=ue({mutationFn:async F=>{var L;const q=(L=c.data)==null?void 0:L.report,Y=ri.parse({title:F.title,status:F.status,eventTypeId:F.eventTypeId||null,customEventType:F.customEventType,eventSituation:F.eventSituation,occurredAt:F.occurredAt?new Date(F.occurredAt).toISOString():null,emotions:F.emotions.filter(V=>V.label.trim().length>0),thoughts:F.thoughts.filter(V=>V.text.trim().length>0),behaviors:F.behaviors.filter(V=>V.text.trim().length>0),consequences:{selfShortTerm:F.selfShortTerm,selfLongTerm:F.selfLongTerm,othersShortTerm:F.othersShortTerm,othersLongTerm:F.othersLongTerm},linkedPatternIds:(q==null?void 0:q.linkedPatternIds)??[],linkedValueIds:(q==null?void 0:q.linkedValueIds)??[],linkedGoalIds:(q==null?void 0:q.linkedGoalIds)??[],linkedProjectIds:(q==null?void 0:q.linkedProjectIds)??[],linkedTaskIds:(q==null?void 0:q.linkedTaskIds)??[],linkedBehaviorIds:F.linkedBehaviorIds,linkedBeliefIds:F.linkedBeliefIds,linkedModeIds:F.linkedModeIds,modeOverlays:F.modeOverlaysText.split(`
20
+ `).map(V=>V.trim()).filter(Boolean),schemaLinks:F.schemaLinks.filter(Boolean),modeTimeline:F.modeTimeline.filter(V=>V.stage.trim().length>0&&V.label.trim().length>0),nextMoves:F.nextMoves.filter(Boolean)});return mc(t,Y)},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"]})])}}),h=ue({mutationFn:lo,onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-psyche-report",t]}),await s.invalidateQueries({queryKey:["forge-insights"]})}}),P=c.error??b.error??p.error??f.error??m.error??x.error??v.error??null;if(c.isLoading||!i)return e.jsx(xt,{});if(P)return e.jsx(Le,{eyebrow:"Trigger report",error:P,onRetry:()=>void Promise.all([c.refetch(),b.refetch(),p.refetch(),f.refetch(),m.refetch(),x.refetch(),v.refetch()])});if(!c.data)return e.jsx(Le,{eyebrow:"Trigger report",error:new Error("Forge returned an empty trigger report payload."),onRetry:()=>void c.refetch()});const T=c.data,O=T.report,y=((S=b.data)==null?void 0:S.behaviors)??[],C=((E=p.data)==null?void 0:E.beliefs)??[],l=((X=f.data)==null?void 0:X.modes)??[],N=((G=m.data)==null?void 0:G.schemas)??[],u=((z=x.data)==null?void 0:z.eventTypes)??[],M=((D=v.data)==null?void 0:D.emotions)??[],A=[{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?"}],I={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(se,{value:i.title,onChange:F=>n({...i,title:F.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:i.status,onChange:F=>n({...i,status:F.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:i.eventTypeId,onChange:F=>n({...i,eventTypeId:F.target.value}),children:[e.jsx("option",{value:"",children:"Custom or uncategorized"}),u.map(F=>e.jsx("option",{value:F.id,children:F.label},F.id))]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Occurred at"}),e.jsx(se,{type:"datetime-local",value:i.occurredAt,onChange:F=>n({...i,occurredAt:F.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(se,{value:i.customEventType,onChange:F=>n({...i,customEventType:F.target.value})})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Situation"}),e.jsx(ve,{value:i.eventSituation,onChange:F=>n({...i,eventSituation:F.target.value})})]})]}),wave:e.jsx(Jo,{items:i.emotions,onChange:F=>n({...i,emotions:F}),definitions:M}),script:e.jsx(Vo,{items:i.thoughts,onChange:F=>n({...i,thoughts:F}),beliefs:C,modes:l}),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(Oe,{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(Ot,{children:"Choose the schemas that were active here or that you want the repair move to strengthen."}),[{title:"Maladaptive schemas",schemas:N.filter(F=>F.schemaType==="maladaptive"),schemaType:"maladaptive",description:"Recurring old patterns that felt active in this moment."},{title:"Adaptive schemas",schemas:N.filter(F=>F.schemaType==="adaptive"),schemaType:"adaptive",description:"Healthier stable themes you want this chain to strengthen."}].map(F=>{const q=os(F.schemaType);return e.jsxs("div",{className:`rounded-[22px] border p-4 ${q.cardTone}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:F.title}),e.jsx(Oe,{content:Ns(F.schemaType),label:`Explain ${Aa(F.schemaType)}`})]}),e.jsx(Ot,{className:"mt-2",children:F.description}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:F.schemas.map(Y=>{const L=i.schemaLinks.some(V=>{var le;return((le=ls(V,[Y]))==null?void 0:le.id)===Y.id});return e.jsx("button",{type:"button",className:`rounded-full border px-3 py-2 text-sm transition ${L?`${q.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:()=>n({...i,schemaLinks:Ho(i.schemaLinks,Y)}),children:Y.title},Y.id)})})]},F.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:C.map(F=>{const q=i.linkedBeliefIds.includes(F.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${q?"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:()=>n({...i,linkedBeliefIds:Ya(i.linkedBeliefIds,F.id)}),children:F.statement},F.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(ve,{value:i.modeOverlaysText,onChange:F=>n({...i,modeOverlaysText:F.target.value})})]}),e.jsx(el,{items:i.modeTimeline,onChange:F=>n({...i,modeTimeline:F}),modes:l,stages:A.map(F=>F.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:l.map(F=>{const q=i.linkedModeIds.includes(F.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${q?"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:()=>n({...i,linkedModeIds:Ya(i.linkedModeIds,F.id)}),children:F.title},F.id)})})]})]}),move:e.jsxs("div",{className:"grid gap-4",children:[e.jsx(Zo,{items:i.behaviors,onChange:F=>n({...i,behaviors:F}),behaviors:y,modes:l}),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:y.map(F=>{const q=i.linkedBehaviorIds.includes(F.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${q?"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:()=>n({...i,linkedBehaviorIds:Ya(i.linkedBehaviorIds,F.id)}),children:F.title},F.id)})})]})]}),horizon:e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(ft,{title:"Short-term impact on you",description:"What happened to you right away?",addLabel:"Add self effect",items:i.selfShortTerm,onChange:F=>n({...i,selfShortTerm:F}),placeholder:"I shut down and lost the evening."}),e.jsx(ft,{title:"Long-term impact on you",description:"What does this cost if it keeps repeating?",addLabel:"Add self cost",items:i.selfLongTerm,onChange:F=>n({...i,selfLongTerm:F}),placeholder:"It keeps training the same abandonment script."}),e.jsx(ft,{title:"Short-term impact on others",description:"What happened to other people right away?",addLabel:"Add other effect",items:i.othersShortTerm,onChange:F=>n({...i,othersShortTerm:F}),placeholder:"They felt shut out."}),e.jsx(ft,{title:"Long-term impact on others",description:"What pattern does this create over time?",addLabel:"Add other cost",items:i.othersLongTerm,onChange:F=>n({...i,othersLongTerm:F}),placeholder:"Trust gets thinner each time."})]}),pivot:e.jsxs("div",{className:"grid gap-4",children:[e.jsx(ft,{title:"What is the next move now?",description:"Finish with concrete repairs, boundaries, or committed actions.",addLabel:"Add next move",items:i.nextMoves,onChange:F=>n({...i,nextMoves:F}),placeholder:"Send one honest repair message tomorrow morning."}),e.jsx("div",{className:"flex justify-end",children:e.jsx(K,{pending:w.isPending,onClick:()=>void w.mutateAsync(i),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:[l.filter(F=>i.linkedModeIds.includes(F.id)).map(F=>e.jsx(xe,{kind:"mode",label:F.title,compact:!0},F.id)),i.linkedModeIds.length===0?e.jsx(K,{variant:"secondary",size:"sm",onClick:()=>r("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:[C.filter(F=>i.linkedBeliefIds.includes(F.id)).map(F=>e.jsx("div",{className:"rounded-[16px] bg-white/[0.04] px-3 py-3",children:e.jsx(xe,{kind:"belief",label:F.statement,compact:!0})},F.id)),i.linkedBeliefIds.length===0?e.jsx(K,{variant:"secondary",size:"sm",onClick:()=>r("lens"),children:"Link belief"}):null]})]}),e.jsx(Ia,{entityType:"trigger_report",entityId:O.id,anchorKey:a,includeAnchorlessWhenAnchored:!0,compact:!0,title:`Stage notes on ${a}`,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:[T.insights.map(F=>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:F.title}),e.jsx("div",{className:"mt-2 text-white/62",children:F.summary})]},F.id)),e.jsx(K,{variant:"secondary",pending:h.isPending,onClick:()=>d(!0),children:"Store insight"})]})]})]});return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Fe,{eyebrow:"Trigger report",title:O.title,description:"Move through Spark to Pivot in one chain canvas.",badge:O.status}),e.jsx(wt,{}),e.jsx(wu,{stages:A,activeStageId:a,onStageChange:r,stageContent:I[a],inspector:j}),e.jsx(Fo,{open:o,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:h.isPending,lockedEntity:{entityType:"trigger_report",entityId:O.id,kind:"report",label:O.title,description:`Anchored to the ${a} stage of this reflective chain.`},initialValue:{originType:"user",originLabel:"Forge Psyche",timeframeLabel:"Current trigger report",rationale:`Captured from the ${a} stage of the Psyche chain canvas.`},onSubmit:async F=>{await h.mutateAsync(F)}})]})}const ta={title:"",status:"draft",eventTypeId:"",customEventType:"",eventSituation:"",occurredAt:"",emotions:[],thoughts:[],behaviors:[],selfShortTerm:[],selfLongTerm:[],othersShortTerm:[],othersLongTerm:[],linkedValueIds:[],linkedBehaviorIds:[],linkedBeliefIds:[],linkedModeIds:[],linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],schemaLinks:[],modeTimeline:[],nextMoves:[]};function Pu(){var L,V,le,ce,he,je,W,$;const t=Xe(),s=Qe(),[a,r]=ut(),[i,n]=g.useState(!1),[o,d]=g.useState(ta),[c,b]=g.useState(null),p=oe({queryKey:["forge-psyche-reports"],queryFn:Ca}),f=oe({queryKey:["forge-psyche-values"],queryFn:$t}),m=oe({queryKey:["forge-psyche-behaviors"],queryFn:Bt}),x=oe({queryKey:["forge-psyche-beliefs"],queryFn:hs}),v=oe({queryKey:["forge-psyche-modes"],queryFn:zt}),w=oe({queryKey:["forge-psyche-schema-catalog"],queryFn:Ls}),h=oe({queryKey:["forge-psyche-event-types"],queryFn:so}),P=oe({queryKey:["forge-psyche-emotions"],queryFn:ao}),T=((L=p.data)==null?void 0:L.reports)??[],O=((V=f.data)==null?void 0:V.values)??[],y=((le=m.data)==null?void 0:le.behaviors)??[],C=((ce=x.data)==null?void 0:ce.beliefs)??[],l=((he=v.data)==null?void 0:he.modes)??[],N=((je=w.data)==null?void 0:je.schemas)??[],u=((W=h.data)==null?void 0:W.eventTypes)??[],M=(($=P.data)==null?void 0:$.emotions)??[],A=t.snapshot.dashboard.notesSummaryByEntity;g.useEffect(()=>{if(a.get("create")==="1"){n(!0),d({...ta,customEventType:a.get("intent")==="execution_tension"?"Execution tension":a.get("intent")==="belief"?"Belief script activation":a.get("intent")==="behavior"?"Behavior spike":a.get("intent")==="pattern"?"Recurring pattern":a.get("intent")==="value"?"Blocked value":"",linkedValueIds:a.get("valueId")?[a.get("valueId")]:[],linkedBehaviorIds:a.get("behaviorId")?[a.get("behaviorId")]:[],linkedBeliefIds:a.get("beliefId")?[a.get("beliefId")]:[],linkedGoalIds:a.get("goalId")?[a.get("goalId")]:[],linkedProjectIds:a.get("projectId")?[a.get("projectId")]:[],linkedTaskIds:a.get("taskId")?[a.get("taskId")]:[]});const k=new URLSearchParams(a);k.delete("create"),k.delete("intent"),k.delete("valueId"),k.delete("behaviorId"),k.delete("beliefId"),k.delete("goalId"),k.delete("projectId"),k.delete("taskId"),r(k,{replace:!0})}},[a,r]);const I=ue({mutationFn:async k=>{const R=ri.parse({title:k.title,status:k.status,eventTypeId:k.eventTypeId||null,customEventType:k.customEventType,eventSituation:k.eventSituation,occurredAt:k.occurredAt?new Date(k.occurredAt).toISOString():null,emotions:k.emotions.filter(Q=>Q.label.trim().length>0),thoughts:k.thoughts.filter(Q=>Q.text.trim().length>0),behaviors:k.behaviors.filter(Q=>Q.text.trim().length>0),consequences:{selfShortTerm:k.selfShortTerm,selfLongTerm:k.selfLongTerm,othersShortTerm:k.othersShortTerm,othersLongTerm:k.othersLongTerm},linkedPatternIds:[],linkedValueIds:k.linkedValueIds,linkedGoalIds:k.linkedGoalIds,linkedProjectIds:k.linkedProjectIds,linkedTaskIds:k.linkedTaskIds,linkedBehaviorIds:k.linkedBehaviorIds,linkedBeliefIds:k.linkedBeliefIds,linkedModeIds:k.linkedModeIds,modeOverlays:[],schemaLinks:k.schemaLinks.filter(Boolean),modeTimeline:k.modeTimeline.filter(Q=>Q.stage.trim().length>0&&Q.label.trim().length>0),nextMoves:k.nextMoves.filter(Boolean)});return io(R)},onSuccess:async()=>{n(!1),d(ta),b(null),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-reports"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]}),s.invalidateQueries({queryKey:["forge-xp-metrics"]})])}}),j=O.map(k=>({value:k.id,label:k.title,description:k.valuedDirection,kind:"value"})),S=y.map(k=>({value:k.id,label:k.title,description:k.kind,kind:"behavior"})),E=C.map(k=>({value:k.id,label:k.statement,description:k.flexibleAlternative||k.originNote,kind:"belief"})),X=l.map(k=>({value:k.id,label:k.title,description:k.archetype||k.family,kind:"mode"})),G=async k=>{const{value:R}=await ms({title:k,description:"",valuedDirection:k,whyItMatters:"",linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],committedActions:[]});return et(s,["forge-psyche-values"],"values",R),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:R.id,label:R.title,description:R.valuedDirection,kind:"value"}},z=async k=>{const{behavior:R}=await Na({kind:"away",title:k,description:"",commonCues:[],urgeStory:"",shortTermPayoff:"",longTermCost:"",replacementMove:"",repairPlan:"",linkedPatternIds:[],linkedValueIds:[],linkedSchemaIds:[],linkedModeIds:[]});return et(s,["forge-psyche-behaviors"],"behaviors",R),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:R.id,label:R.title,description:R.kind,kind:"behavior"}},D=async k=>{const{belief:R}=await Ni({schemaId:null,statement:k,beliefType:"absolute",originNote:"",confidence:60,evidenceFor:[],evidenceAgainst:[],flexibleAlternative:"",linkedValueIds:[],linkedBehaviorIds:[],linkedModeIds:[],linkedReportIds:[]});return et(s,["forge-psyche-beliefs"],"beliefs",R),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:R.id,label:R.statement,description:R.flexibleAlternative||R.originNote,kind:"belief"}},F=async k=>{const{mode:R}=await Fs({family:"coping",archetype:"",title:k,persona:"",imagery:"",symbolicForm:"",facialExpression:"",fear:"",burden:"",protectiveJob:"",originContext:"",firstAppearanceAt:null,linkedPatternIds:[],linkedBehaviorIds:[],linkedValueIds:[]});return et(s,["forge-psyche-modes"],"modes",R),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:R.id,label:R.title,description:R.archetype||R.family,kind:"mode"}},q=[{id:"spark",eyebrow:"Spark",title:"Capture the trigger and the situation",description:"Start with what happened concretely before interpretation takes over.",render:(k,R)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Report title",children:e.jsx(se,{value:k.title,onChange:Q=>R({title:Q.target.value}),placeholder:"Friday silence spiral"})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(B,{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:k.eventTypeId,onChange:Q=>R({eventTypeId:Q.target.value}),children:[e.jsx("option",{value:"",children:"Custom or uncategorized"}),u.map(Q=>e.jsx("option",{value:Q.id,children:Q.label},Q.id))]})}),e.jsx(B,{label:"Occurred at",children:e.jsx(se,{type:"datetime-local",value:k.occurredAt,onChange:Q=>R({occurredAt:Q.target.value})})})]}),e.jsx(B,{label:"Custom event label",children:e.jsx(se,{value:k.customEventType,onChange:Q=>R({customEventType:Q.target.value}),placeholder:"Unexpected distance after vulnerability"})}),e.jsx(B,{label:"Situation",children:e.jsx(ve,{value:k.eventSituation,onChange:Q=>R({eventSituation:Q.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:(k,R)=>e.jsxs(e.Fragment,{children:[e.jsx(Jo,{items:k.emotions,onChange:Q=>R({emotions:Q}),definitions:M}),e.jsx(Vo,{items:k.thoughts,onChange:Q=>R({thoughts:Q}),beliefs:C,modes:l}),e.jsx(Zo,{items:k.behaviors,onChange:Q=>R({behaviors:Q}),behaviors:y,modes:l})]})},{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:(k,R)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Linked values",children:e.jsx(We,{options:j,selectedValues:k.linkedValueIds,onChange:Q=>R({linkedValueIds:Q}),placeholder:"Search or create a value…",emptyMessage:"No values match yet.",createLabel:"Create value",onCreate:G})}),e.jsx(B,{label:"Linked behaviors",children:e.jsx(We,{options:S,selectedValues:k.linkedBehaviorIds,onChange:Q=>R({linkedBehaviorIds:Q}),placeholder:"Search or create a behavior…",emptyMessage:"No behaviors match yet.",createLabel:"Create behavior",onCreate:z})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(B,{label:"Linked beliefs",children:e.jsx(We,{options:E,selectedValues:k.linkedBeliefIds,onChange:Q=>R({linkedBeliefIds:Q}),placeholder:"Search or create a belief…",emptyMessage:"No beliefs match yet.",createLabel:"Create belief",onCreate:D})}),e.jsx(B,{label:"Linked modes",children:e.jsx(We,{options:X,selectedValues:k.linkedModeIds,onChange:Q=>R({linkedModeIds:Q}),placeholder:"Search or create a mode…",emptyMessage:"No modes match yet.",createLabel:"Create mode",onCreate:F})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[k.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 ",k.linkedGoalIds.length," goal tension"]}):null,k.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 ",k.linkedProjectIds.length," project tension"]}):null,k.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 ",k.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:(k,R)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(ft,{title:"Short-term impact on you",description:"Add the immediate effects on your body, mood, or direction.",addLabel:"Add self effect",items:k.selfShortTerm,onChange:Q=>R({selfShortTerm:Q}),placeholder:"I shut down and lost the rest of the evening."}),e.jsx(ft,{title:"Long-term impact on you",description:"Capture what this pattern costs when it keeps repeating.",addLabel:"Add self cost",items:k.selfLongTerm,onChange:Q=>R({selfLongTerm:Q}),placeholder:"It keeps reinforcing the same abandonment story."}),e.jsx(ft,{title:"Short-term impact on others",description:"Note what happened to the people around you right away.",addLabel:"Add other effect",items:k.othersShortTerm,onChange:Q=>R({othersShortTerm:Q}),placeholder:"They felt pushed away and confused."}),e.jsx(ft,{title:"Long-term impact on others",description:"Capture the longer pattern this creates in relationships.",addLabel:"Add other cost",items:k.othersLongTerm,onChange:Q=>R({othersLongTerm:Q}),placeholder:"Trust gets thinner every time this loop takes over."})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsx(B,{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(Q=>Q.schemaType==="maladaptive"),schemaType:"maladaptive",description:"Recurring old patterns that felt active in this moment."},{title:"Adaptive schemas",schemas:N.filter(Q=>Q.schemaType==="adaptive"),schemaType:"adaptive",description:"Healthier stable themes you want this repair move to strengthen."}].map(Q=>{const Ce=os(Q.schemaType);return e.jsxs("div",{className:`rounded-[24px] border p-4 ${Ce.cardTone}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:Q.title}),e.jsx(Oe,{content:Ns(Q.schemaType),label:`Explain ${Aa(Q.schemaType)}`})]}),e.jsx(Ot,{className:"mt-2",children:Q.description}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:Q.schemas.map(ie=>{const _e=k.schemaLinks.some(J=>{var H;return((H=ls(J,[ie]))==null?void 0:H.id)===ie.id});return e.jsx("button",{type:"button",className:`rounded-full border px-3 py-2 text-sm transition ${_e?`${Ce.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({schemaLinks:Ho(k.schemaLinks,ie)}),children:ie.title},ie.id)})})]},Q.schemaType)})})}),e.jsx(el,{items:k.modeTimeline,onChange:Q=>R({modeTimeline:Q}),modes:l,stages:["Spark","Wave","Script","Lens","State","Move","Horizon","Pivot"]}),e.jsx(ft,{title:"Next moves",description:"Finish with concrete next moves that protect the value or repair the situation.",addLabel:"Add next move",items:k.nextMoves,onChange:Q=>R({nextMoves:Q}),placeholder:"Send one honest repair message tomorrow morning."})]})]})}];if(p.isLoading||f.isLoading||m.isLoading||x.isLoading||v.isLoading||w.isLoading||h.isLoading||P.isLoading)return e.jsx(pt,{eyebrow:"Reports",title:"Loading reports",description:"Getting reports, values, behaviors, beliefs, modes, event labels, and emotions ready."});const Y=p.error??f.error??m.error??x.error??v.error??w.error??h.error??P.error;return Y?e.jsx(Le,{eyebrow:"Trigger reports",error:Y,onRetry:()=>void Promise.all([p.refetch(),f.refetch(),m.refetch(),x.refetch(),v.refetch(),w.refetch(),h.refetch(),P.refetch()])}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Fe,{entityKind:"report",title:e.jsx(Te,{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:`${T.length} reports`,actions:e.jsx(K,{onClick:()=>{d(ta),n(!0)},children:"Reflect"})}),e.jsx(wt,{}),e.jsx(St,{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:T.length===0?e.jsx(rt,{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."}):T.map(k=>{var R;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(Te,{kind:"report",label:k.title,variant:"heading",size:"xl"}),e.jsx("div",{className:"mt-2 text-sm text-white/54",children:k.customEventType||k.eventSituation})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Ze,{entityType:"trigger_report",entityId:k.id,count:at(A,"trigger_report",k.id).count}),e.jsx(_,{children:k.status}),e.jsx(Ne,{to:`/psyche/reports/${k.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:k.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:((R=k.emotions[0])==null?void 0:R.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:k.schemaLinks[0]?(()=>{const Q=ls(k.schemaLinks[0],N);return Q?e.jsx(Lt,{label:Q.title,schemaType:Q.schemaType,compact:!0}):e.jsx("div",{className:"text-sm leading-6 text-white/66",children:k.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:k.nextMoves[0]??"No next move yet"})]})]})]},k.id)})})}),e.jsx(He,{open:i,onOpenChange:n,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:o,onChange:d,steps:q,submitLabel:"Create report",pending:I.isPending,error:c,onSubmit:async()=>{if(b(null),!ri.safeParse({title:o.title,status:o.status,eventTypeId:o.eventTypeId||null,customEventType:o.customEventType,eventSituation:o.eventSituation,occurredAt:o.occurredAt?new Date(o.occurredAt).toISOString():null,emotions:o.emotions.filter(R=>R.label.trim().length>0),thoughts:o.thoughts.filter(R=>R.text.trim().length>0),behaviors:o.behaviors.filter(R=>R.text.trim().length>0),consequences:{selfShortTerm:o.selfShortTerm,selfLongTerm:o.selfLongTerm,othersShortTerm:o.othersShortTerm,othersLongTerm:o.othersLongTerm},linkedPatternIds:[],linkedValueIds:o.linkedValueIds,linkedGoalIds:o.linkedGoalIds,linkedProjectIds:o.linkedProjectIds,linkedTaskIds:o.linkedTaskIds,linkedBehaviorIds:o.linkedBehaviorIds,linkedBeliefIds:o.linkedBeliefIds,linkedModeIds:o.linkedModeIds,modeOverlays:[],schemaLinks:o.schemaLinks.filter(Boolean),modeTimeline:o.modeTimeline.filter(R=>R.stage.trim().length>0&&R.label.trim().length>0),nextMoves:o.nextMoves.filter(Boolean)}).success){b("This report still needs a title and concrete triggering situation.");return}try{await I.mutateAsync(o)}catch(R){b(R instanceof Error?R.message:"Unable to create this report right now.")}}})]})}const fs={schemaId:null,statement:"",beliefType:"absolute",originNote:"",confidence:60,evidenceFor:[],evidenceAgainst:[],flexibleAlternative:"",linkedValueIds:[],linkedBehaviorIds:[],linkedModeIds:[],linkedReportIds:[]};function Ja(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}}function Mu({schema:t,beliefs:s,behaviors:a,reports:r}){const i=s.filter(d=>d.schemaId===t.id).length,n=a.filter(d=>d.linkedSchemaIds.includes(t.id)).length,o=r.filter(d=>d.schemaLinks.some(c=>{const b=ls(c,[t]);return(b==null?void 0:b.id)===t.id})).length;return{beliefCount:i,behaviorCount:n,reportCount:o,total:i+n+o}}function Sr({title:t,description:s,titleHelp:a,schemas:r,beliefs:i,behaviors:n,reports:o,onOpenBelief:d}){if(r.length===0)return null;const c=os(r[0].schemaType);return e.jsxs("section",{className:`min-w-0 grid gap-4 rounded-[30px] border p-4 md:p-5 ${c.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] ${c.sectionEyebrow}`,children:[e.jsx("span",{children:t}),a?e.jsx(Oe,{content:a,label:`Explain ${t.toLowerCase()}`}):null]}),e.jsx("div",{className:"max-w-3xl text-sm leading-6 text-white/60",children:s})]}),e.jsxs(_,{children:[r.length," schemas"]})]}),e.jsx("div",{className:"grid gap-4 xl:grid-cols-2",children:r.map(b=>{const p=Mu({schema:b,beliefs:i,behaviors:n,reports:o}),f=i.filter(x=>x.schemaId===b.id),m=os(b.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(Lt,{label:b.title,schemaType:b.schemaType}),e.jsx("div",{className:"mt-3 text-sm text-white/46",children:Fi(b.family)}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/62",children:b.description})]}),e.jsxs(_,{children:[p.total," ",m.countLabel]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsxs(_,{className:"bg-white/[0.06] text-white/68",children:[p.beliefCount," beliefs"]}),e.jsxs(_,{className:"bg-white/[0.06] text-white/68",children:[p.behaviorCount," behaviors"]}),e.jsxs(_,{className:"bg-white/[0.06] text-white/68",children:[p.reportCount," reports"]})]}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[f.length>0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] p-4 text-sm text-white/58",children:`${f.length} ${m.linkSummary}${f.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}),f.slice(0,2).map(x=>e.jsxs("button",{type:"button",className:"rounded-[20px] bg-white/[0.04] p-4 text-left transition hover:bg-white/[0.08]",onClick:()=>d(x),children:[e.jsx("div",{className:"font-medium text-white",children:x.statement}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:x.flexibleAlternative||"No flexible alternative recorded yet."})]},x.id))]})]},b.id)})})]})}function Au(){var le,ce,he,je,W,$;const t=Xe(),s=Qe(),[a,r]=ut(),[i,n]=g.useState(!1),[o,d]=g.useState(null),[c,b]=g.useState(fs),[p,f]=g.useState(null),m=oe({queryKey:["forge-psyche-schema-catalog"],queryFn:Ls}),x=oe({queryKey:["forge-psyche-beliefs"],queryFn:hs}),v=oe({queryKey:["forge-psyche-behaviors"],queryFn:Bt}),w=oe({queryKey:["forge-psyche-modes"],queryFn:zt}),h=oe({queryKey:["forge-psyche-values"],queryFn:$t}),P=oe({queryKey:["forge-psyche-reports"],queryFn:Ca}),T=((le=m.data)==null?void 0:le.schemas)??[],O=((ce=x.data)==null?void 0:ce.beliefs)??[],y=((he=v.data)==null?void 0:he.behaviors)??[],C=((je=w.data)==null?void 0:je.modes)??[],l=((W=h.data)==null?void 0:W.values)??[],N=(($=P.data)==null?void 0:$.reports)??[],u=a.get("focus"),M=t.snapshot.dashboard.notesSummaryByEntity;Rs(u),g.useEffect(()=>{if(a.get("create")==="1"){n(!0),d(null),b(fs);const k=new URLSearchParams(a);k.delete("create"),r(k,{replace:!0})}},[a,r]);const A=ue({mutationFn:async k=>{const R=jr.parse(k);return o?rc(o.id,R):Ni(R)},onSuccess:async()=>{n(!1),d(null),b(fs),f(null),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-beliefs"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]})])}}),I=l.map(k=>({value:k.id,label:k.title,description:k.valuedDirection,kind:"value"})),j=y.map(k=>({value:k.id,label:k.title,description:k.kind,kind:"behavior"})),S=C.map(k=>({value:k.id,label:k.title,description:k.archetype||k.family,kind:"mode"})),E=N.map(k=>({value:k.id,label:k.title,description:k.customEventType||k.eventSituation,kind:"report"})),X=g.useMemo(()=>new Map(T.map(k=>[k.id,k])),[T]),G=g.useMemo(()=>T.filter(k=>k.schemaType==="maladaptive"),[T]),z=g.useMemo(()=>T.filter(k=>k.schemaType==="adaptive"),[T]),D=async k=>{const{value:R}=await ms({title:k,description:"",valuedDirection:k,whyItMatters:"",linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],committedActions:[]});return et(s,["forge-psyche-values"],"values",R),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:R.id,label:R.title,description:R.valuedDirection,kind:"value"}},F=async k=>{const{behavior:R}=await Na({kind:"away",title:k,description:"",commonCues:[],urgeStory:"",shortTermPayoff:"",longTermCost:"",replacementMove:"",repairPlan:"",linkedPatternIds:[],linkedValueIds:[],linkedSchemaIds:[],linkedModeIds:[]});return et(s,["forge-psyche-behaviors"],"behaviors",R),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:R.id,label:R.title,description:R.kind,kind:"behavior"}},q=async k=>{const{mode:R}=await Fs({family:"coping",archetype:"",title:k,persona:"",imagery:"",symbolicForm:"",facialExpression:"",fear:"",burden:"",protectiveJob:"",originContext:"",firstAppearanceAt:null,linkedPatternIds:[],linkedBehaviorIds:[],linkedValueIds:[]});return et(s,["forge-psyche-modes"],"modes",R),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:R.id,label:R.title,description:R.archetype||R.family,kind:"mode"}},Y=async k=>{const{report:R}=await io({title:k,status:"draft",eventTypeId:null,customEventType:"",eventSituation:k,occurredAt:null,emotions:[],thoughts:[],behaviors:[],consequences:{selfShortTerm:[],selfLongTerm:[],othersShortTerm:[],othersLongTerm:[]},linkedPatternIds:[],linkedValueIds:[],linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],linkedBehaviorIds:[],linkedBeliefIds:[],linkedModeIds:[],modeOverlays:[],schemaLinks:[],modeTimeline:[],nextMoves:[]});return et(s,["forge-psyche-reports"],"reports",R),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:R.id,label:R.title,description:R.customEventType||R.eventSituation,kind:"report"}};g.useEffect(()=>{i&&f(null)},[i]);const L=[{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:(k,R)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{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:G,description:"Recurring old patterns that tend to get activated and distort how the situation feels.",schemaType:"maladaptive"},{title:"Adaptive schemas",schemas:z,description:"Healthier stable themes you want to strengthen, trust, and live from more often.",schemaType:"adaptive"}].map(Q=>{const Ce=os(Q.schemaType);return e.jsxs("div",{className:`rounded-[24px] border p-4 ${Ce.cardTone}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:Q.title}),e.jsx(Oe,{content:Ns(Q.schemaType),label:`Explain ${Aa(Q.schemaType)}`})]}),e.jsx(Ot,{className:"mt-2",children:Q.description}),e.jsx("div",{className:"mt-4 grid gap-2 sm:flex sm:flex-wrap",children:Q.schemas.map(ie=>{const _e=k.schemaId===ie.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 ${_e?`${Ce.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({schemaId:ie.id}),children:ie.title},ie.id)})})]},Q.schemaType)})})}),e.jsx(B,{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(se,{value:k.statement,onChange:Q=>R({statement:Q.target.value}),placeholder:"If they go quiet, I am already being left."})}),e.jsx(B,{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(Q=>e.jsx("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${k.beliefType===Q?"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:()=>R({beliefType:Q}),children:Q==="absolute"?"Absolute: this is simply true":"Conditional: if this happens, then..."},Q))})})]})},{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:(k,R)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Origin context",description:"Capture where this script learned its force or usefulness.",children:e.jsx(ve,{value:k.originNote,onChange:Q=>R({originNote:Q.target.value}),placeholder:"It got stronger in periods where silence usually meant anger, distance, or punishment."})}),e.jsxs(B,{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:k.confidence,onChange:Q=>R({confidence:Number(Q.target.value)})}),e.jsxs("div",{className:"text-sm text-white/48",children:[k.confidence,"% grip"]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(B,{label:"Evidence for",description:"Add one supporting memory, sign, or interpretation per line.",children:e.jsx(ve,{value:k.evidenceFor.join(`
21
+ `),onChange:Q=>R({evidenceFor:Q.target.value.split(`
22
+ `).map(Ce=>Ce.trim()).filter(Boolean)}),placeholder:`One line per sign
23
+ They stopped replying for days
24
+ I was ignored when I asked directly`})}),e.jsx(B,{label:"Evidence against",description:"Add one counterexample, nuance, or disconfirming sign per line.",children:e.jsx(ve,{value:k.evidenceAgainst.join(`
25
+ `),onChange:Q=>R({evidenceAgainst:Q.target.value.split(`
26
+ `).map(Ce=>Ce.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:(k,R)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{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(ve,{value:k.flexibleAlternative,onChange:Q=>R({flexibleAlternative:Q.target.value}),placeholder:"Silence can mean many things. I can check the facts before deciding I am being left."})}),e.jsx(B,{label:"Linked values",description:"Choose the valued directions this belief interferes with most.",children:e.jsx(We,{options:I,selectedValues:k.linkedValueIds,onChange:Q=>R({linkedValueIds:Q}),placeholder:"Search or create a value…",emptyMessage:"No values match yet.",createLabel:"Create value",onCreate:D})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(B,{label:"Linked behaviors",description:"Choose the moves this belief tends to trigger or justify.",children:e.jsx(We,{options:j,selectedValues:k.linkedBehaviorIds,onChange:Q=>R({linkedBehaviorIds:Q}),placeholder:"Search or create a behavior…",emptyMessage:"No behaviors match yet.",createLabel:"Create behavior",onCreate:F})}),e.jsx(B,{label:"Linked modes",description:"Choose the inner states that most often carry this script.",children:e.jsx(We,{options:S,selectedValues:k.linkedModeIds,onChange:Q=>R({linkedModeIds:Q}),placeholder:"Search or create a mode…",emptyMessage:"No modes match yet.",createLabel:"Create mode",onCreate:q})}),e.jsx(B,{label:"Linked reports",description:"Choose the reflective chains where this script has already shown up.",children:e.jsx(We,{options:E,selectedValues:k.linkedReportIds,onChange:Q=>R({linkedReportIds:Q}),placeholder:"Search or create a report…",emptyMessage:"No reports match yet.",createLabel:"Create report",onCreate:Y})})]})]})}];if(m.isLoading||x.isLoading||v.isLoading||w.isLoading||h.isLoading||P.isLoading)return e.jsx(pt,{eyebrow:"Schemas & beliefs",title:"Loading schemas and beliefs",description:"Getting schemas, beliefs, behaviors, modes, values, and linked reports ready."});const V=m.error??x.error??v.error??w.error??h.error??P.error;return V?e.jsx(Le,{eyebrow:"Schemas & beliefs",error:V,onRetry:()=>void Promise.all([m.refetch(),x.refetch(),v.refetch(),w.refetch(),h.refetch(),P.refetch()])}):e.jsxs("div",{className:"grid min-w-0 gap-5",children:[e.jsx(Fe,{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:`${O.length} beliefs`,actions:e.jsx(K,{onClick:()=>{d(null),b(fs),n(!0)},children:"Add belief"})}),e.jsx(wt,{}),e.jsxs("section",{className:"grid min-w-0 gap-5 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]",children:[e.jsx(St,{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:T.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(Sr,{title:"Maladaptive schemas",titleHelp:Ns("maladaptive"),description:"These schemas describe recurring old patterns that can change how you read situations and react.",schemas:G,beliefs:O,behaviors:y,reports:N,onOpenBelief:k=>{d(k),b(Ja(k)),n(!0)}}),e.jsx(Sr,{title:"Adaptive schemas",titleHelp:Ns("adaptive"),description:"These schemas describe healthier patterns you want to trust, practice, and strengthen over time.",schemas:z,beliefs:O,behaviors:y,reports:N,onOpenBelief:k=>{d(k),b(Ja(k)),n(!0)}})]})}),e.jsx(St,{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(K,{onClick:()=>{d(null),b(fs),n(!0)},children:"Add belief"}),O.length===0?e.jsx("div",{className:"text-sm text-white/56",children:"Your beliefs will appear here after you add the first one."}):O.map(k=>{const R=k.schemaId?X.get(k.schemaId)??null:null,Q=u===k.id;return e.jsxs("div",{"data-psyche-focus-id":k.id,className:`rounded-[24px] border border-white/8 bg-white/[0.04] p-4 text-left transition hover:bg-white/[0.08] ${_s(Q)}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:k.statement}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e.jsx(Ze,{entityType:"belief_entry",entityId:k.id,count:at(M,"belief_entry",k.id).count}),e.jsxs(_,{children:[k.confidence,"% grip"]}),e.jsx(K,{variant:"secondary",size:"sm",onClick:()=>{d(k),b(Ja(k)),n(!0)},children:"Edit"})]})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:k.flexibleAlternative||"No flexible alternative recorded yet."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[R?e.jsx(Lt,{label:R.title,schemaType:R.schemaType,compact:!0,showType:!0}):null,C.filter(Ce=>k.linkedModeIds.includes(Ce.id)).slice(0,2).map(Ce=>e.jsx(xe,{kind:"mode",label:Ce.title,compact:!0},Ce.id))]})]},k.id)})]})})]}),e.jsx(He,{open:i,onOpenChange:n,eyebrow:"Belief",title:o?"Refine belief":"Create belief",description:"Use this guided flow to capture the belief, what seems to support it, and a more flexible alternative.",value:c,onChange:b,steps:L,submitLabel:o?"Save belief":"Create belief",pending:A.isPending,error:p,onSubmit:async()=>{f(null);const k=jr.safeParse(c);if(!k.success){f("This belief still needs a statement before it can be saved.");return}try{await A.mutateAsync(k.data)}catch(R){f(R instanceof Error?R.message:"Unable to save this belief right now.")}}})]})}const sa={title:"",description:"",valuedDirection:"",whyItMatters:"",linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],committedActions:[]};function Va(t,s){return t.includes(s)?t.filter(a=>a!==s):[...t,s]}function Du(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}}function Eu(){var O;const t=Xe(),s=Qe(),[a,r]=ut(),[i,n]=g.useState(!1),[o,d]=g.useState(null),[c,b]=g.useState(sa),[p,f]=g.useState(null),m=oe({queryKey:["forge-psyche-values"],queryFn:$t}),x=((O=m.data)==null?void 0:O.values)??[],v=a.get("focus"),w=t.snapshot.dashboard.notesSummaryByEntity;Rs(v),g.useEffect(()=>{if(a.get("create")==="1"){n(!0),d(null),b(sa);const y=new URLSearchParams(a);y.delete("create"),r(y,{replace:!0})}},[a,r]);const h=ue({mutationFn:async y=>{const C=vr.parse(y);return o?ac(o.id,C):ms(C)},onSuccess:async()=>{n(!1),d(null),b(sa),f(null),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-values"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]})])}}),P=g.useMemo(()=>x.slice(0,5).map((y,C)=>({id:y.id,label:`${y.linkedGoalIds.length} goals`,title:y.title,detail:y.valuedDirection,href:`/psyche/values?focus=${y.id}#values-atlas`,angle:-90+C*68,radius:150+C%2*20,tone:["mint","sky","violet","rose"][C%4]})),[x]),T=[{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:(y,C)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Value name",children:e.jsx(se,{value:y.title,onChange:l=>C({title:l.target.value}),placeholder:"Repair with steadiness"})}),e.jsx(B,{label:"Valued direction",children:e.jsx(se,{value:y.valuedDirection,onChange:l=>C({valuedDirection:l.target.value}),placeholder:"Warm, brave, and honest connection"})}),e.jsx(B,{label:"Why it matters",children:e.jsx(ve,{value:y.whyItMatters,onChange:l=>C({whyItMatters:l.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:(y,C)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Description",children:e.jsx(ve,{value:y.description,onChange:l=>C({description:l.target.value}),placeholder:"Describe what this value looks like in daily behavior, not just in theory."})}),e.jsx(B,{label:"Committed action ideas",children:e.jsx(ve,{value:y.committedActions.join(`
29
+ `),onChange:l=>C({committedActions:l.target.value.split(`
30
+ `).map(N=>N.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:(y,C)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Linked goals",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:t.snapshot.goals.map(l=>{const N=y.linkedGoalIds.includes(l.id);return e.jsx("button",{type:"button",className:`rounded-full px-2.5 py-2 text-sm transition ${ws("goal",N)}`,onClick:()=>C({linkedGoalIds:Va(y.linkedGoalIds,l.id)}),children:e.jsx(xe,{kind:"goal",label:l.title,compact:!0,gradient:!1})},l.id)})})}),e.jsx(B,{label:"Linked projects",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:t.snapshot.dashboard.projects.map(l=>{const N=y.linkedProjectIds.includes(l.id);return e.jsx("button",{type:"button",className:`rounded-full px-2.5 py-2 text-sm transition ${ws("project",N)}`,onClick:()=>C({linkedProjectIds:Va(y.linkedProjectIds,l.id)}),children:e.jsx(xe,{kind:"project",label:l.title,compact:!0,gradient:!1})},l.id)})})}),e.jsx(B,{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(l=>{const N=y.linkedTaskIds.includes(l.id);return e.jsx("button",{type:"button",className:`rounded-full px-2.5 py-2 text-sm transition ${ws("task",N)}`,onClick:()=>C({linkedTaskIds:Va(y.linkedTaskIds,l.id)}),children:e.jsx(xe,{kind:"task",label:l.title,compact:!0,gradient:!1})},l.id)})})})]})}];return m.isLoading?e.jsx(pt,{eyebrow:"Psyche values",title:"Loading value constellation",description:"Hydrating values, linked goals, projects, and tasks."}):m.isError?e.jsx(Le,{eyebrow:"Psyche values",error:m.error,onRetry:()=>void m.refetch()}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Fe,{entityKind:"value",title:e.jsx(Te,{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:`${x.length} values`,actions:e.jsx(K,{onClick:()=>{d(null),b(sa),n(!0)},children:"Add value"})}),e.jsx(wt,{}),e.jsx(Yo,{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:`${x.length} mapped`,nodes:P,action:e.jsx(K,{onClick:()=>n(!0),children:"Add value"})}),e.jsx(St,{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:x.length===0?e.jsx("div",{className:"flex justify-start",children:e.jsx(K,{onClick:()=>n(!0),children:"Add value"})}):x.map(y=>{const C=t.snapshot.goals.filter(A=>y.linkedGoalIds.includes(A.id)),l=t.snapshot.dashboard.projects.filter(A=>y.linkedProjectIds.includes(A.id)),N=t.snapshot.tasks.filter(A=>y.linkedTaskIds.includes(A.id)),u=v===y.id,M=at(w,"psyche_value",y.id).count;return e.jsxs("div",{"data-psyche-focus-id":y.id,className:`rounded-[26px] border border-white/8 bg-white/[0.04] p-5 transition ${_s(u)}`,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(Te,{kind:"value",label:y.title,variant:"heading",size:"xl"}),e.jsx("div",{className:"mt-2 text-sm text-[var(--tertiary)]",children:y.valuedDirection})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Ze,{entityType:"psyche_value",entityId:y.id,count:M}),e.jsx(K,{variant:"secondary",onClick:()=>{d(y),b(Du(y)),n(!0)},children:"Edit"})]})]}),e.jsx("p",{className:"mt-4 max-w-3xl text-sm leading-7 text-white/60",children:y.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:y.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:C.length===0?e.jsx("span",{className:"text-sm text-white/44",children:"None linked"}):C.map(A=>e.jsx(xe,{kind:"goal",label:A.title,compact:!0},A.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:l.length===0?e.jsx("span",{className:"text-sm text-white/44",children:"None linked"}):l.map(A=>e.jsx(xe,{kind:"project",label:A.title,compact:!0},A.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:N.length===0?e.jsx("span",{className:"text-sm text-white/44",children:"None linked"}):N.slice(0,4).map(A=>e.jsx(xe,{kind:"task",label:A.title,compact:!0},A.id))})]})]})]}),e.jsx("div",{className:"mt-4 grid gap-2 md:grid-cols-2",children:y.committedActions.map(A=>e.jsx("div",{className:"rounded-[18px] bg-[rgba(110,231,183,0.08)] px-4 py-3 text-sm text-white/72",children:A},A))})]},y.id)})})}),e.jsx(He,{open:i,onOpenChange:n,eyebrow:"Value",title:o?"Refine value placement":"Create value",description:"Forge should capture values through guided placement, not a raw admin form.",value:c,onChange:b,steps:T,submitLabel:o?"Save value":"Create value",pending:h.isPending,error:p,onSubmit:async()=>{f(null);const y=vr.safeParse(c);if(!y.success){f("This value still needs a title and valued direction before it can be saved.");return}try{await h.mutateAsync(y.data)}catch(C){f(C instanceof Error?C.message:"Unable to save this value right now.")}}})]})}const aa=[{to:"/settings",label:"General",icon:Ur},{to:"/settings/calendar",label:"Calendar",icon:Ct},{to:"/settings/agents",label:"Agents",icon:Xl},{to:"/settings/rewards",label:"Rewards",icon:Gl},{to:"/settings/bin",label:"Bin",icon:ai}];function Za(t,s){return s==="/settings"?t==="/settings":t===s||t.startsWith(`${s}/`)}function zs({className:t}){const s=pi(),[a,r]=g.useState(!1),i=g.useMemo(()=>[...aa].sort((n,o)=>o.to.length-n.to.length).find(n=>Za(s.pathname,n.to))??aa[0],[s.pathname]);return e.jsxs(e.Fragment,{children:[e.jsxs(Z,{className:te("overflow-hidden bg-[linear-gradient(180deg,rgba(15,24,31,0.94),rgba(10,18,25,0.92))] p-2",t),children:[e.jsx("div",{className:"hidden items-center gap-3 lg:flex",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:aa.map(n=>e.jsxs(Wt,{to:n.to,end:n.to==="/settings",className:({isActive:o})=>te("inline-flex items-center gap-2 whitespace-nowrap rounded-full px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] transition",o||Za(s.pathname,n.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(n.icon,{className:"size-3.5"}),e.jsx("span",{children:n.label})]},n.to))})}),e.jsx("div",{className:"flex items-center justify-between gap-3 lg:hidden",children:e.jsxs("button",{type:"button",className:"inline-flex min-w-0 flex-1 items-center justify-between rounded-full bg-white/[0.06] px-4 py-3 text-left",onClick:()=>r(!0),children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(i.icon,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"truncate text-sm font-medium text-white",children:i.label})]}),e.jsx("span",{className:"text-[10px] uppercase tracking-[0.16em] text-white/42",children:"Switch"})]})})]}),a?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(K,{variant:"secondary",onClick:()=>r(!1),children:"Close"})]}),e.jsx("div",{className:"mt-6 grid gap-3 overflow-y-auto",children:aa.map(n=>e.jsxs(Wt,{to:n.to,end:n.to==="/settings",onClick:()=>r(!1),className:te("flex items-center justify-between rounded-[24px] px-4 py-4 transition",Za(s.pathname,n.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(n.icon,{className:"size-4 text-[var(--primary)]"}),e.jsx("span",{className:"text-base font-medium",children:n.label})]}),e.jsx("span",{className:"text-[10px] uppercase tracking-[0.16em] text-white/36",children:"Open"})]},n.to))})]})}):null]})}function Lu(){var p,f;const{t}=qe(),s=Qe(),a=oe({queryKey:["forge-operator-session"],queryFn:cs}),r=a.isSuccess,i=oe({queryKey:["forge-settings"],queryFn:Ta,enabled:r}),n=la({defaultValues:{profile:{operatorName:"",operatorEmail:"",operatorTitle:""},notifications:{goalDriftAlerts:!0,dailyQuestReminders:!0,achievementCelebrations:!0},execution:{maxActiveTasks:2,timeAccountingMode:"split"},themePreference:"obsidian",localePreference:"en"}}),o=async()=>{await Promise.all([s.invalidateQueries({queryKey:["forge-operator-session"]}),s.invalidateQueries({queryKey:["forge-settings"]})])},d=ue({mutationFn:m=>mo(m),onSuccess:o}),c=ue({mutationFn:ec,onSuccess:async()=>{await o(),await a.refetch()}});g.useEffect(()=>{var m;(m=i.data)!=null&&m.settings&&n.reset(Ld.parse(i.data.settings))},[i.data,n]);const b=(p=i.data)==null?void 0:p.settings;return a.isLoading||i.isLoading?e.jsx(xt,{eyebrow:"Settings",title:"Loading settings",description:"Establishing the operator session and fetching current configuration.",columns:2,blocks:6}):a.isError?e.jsx(Le,{eyebrow:"Settings",error:a.error,onRetry:()=>void a.refetch()}):i.isError||!b?e.jsx(Le,{eyebrow:"Settings",error:i.error??new Error("Forge returned an empty settings payload."),onRetry:()=>void i.refetch()}):e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(Fe,{title:"Settings",description:"Tune execution policy, timer behaviour, and personal preferences.",badge:`${b.security.integrityScore}% integrity`}),e.jsx(zs,{}),(f=a.data)!=null&&f.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:a.data.session.actorLabel}),"."]}),e.jsx(K,{variant:"secondary",size:"sm",pending:c.isPending,pendingLabel:"Resetting session",onClick:()=>void c.mutateAsync(),children:"Reset operator session"})]}):null,e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Z,{children:e.jsxs("form",{className:"grid gap-4",onSubmit:n.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(se,{...n.register("profile.operatorName")})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Email"}),e.jsx(se,{...n.register("profile.operatorEmail")})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Title"}),e.jsx(se,{...n.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(se,{type:"number",min:1,max:8,...n.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,...n.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",...n.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",...n.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",...n.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,...n.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,...n.register("localePreference")}),e.jsx("span",{className:"text-white/72",children:m.label})]},m.value))}),e.jsx(K,{type:"submit",pending:d.isPending,pendingLabel:"Saving settings",children:"Save settings"})]})}),e.jsxs(Z,{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:b.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(b.security.lastAuditAt).toLocaleString()})]})]})]})]})]})}const pa=["read","write","insights","rewards.manage","psyche.read","psyche.write","psyche.note","psyche.insight","psyche.mode"],Fu=[{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 tl(t,s,a){return s==="review"?{...t,preset:s,trustLevel:"trusted",autonomyMode:"approval_required",approvalMode:"approval_by_default",scopes:[...a]}:s==="operator"?{...t,preset:s,trustLevel:"trusted",autonomyMode:"scoped_write",approvalMode:"high_impact_only",scopes:[...pa]}:s==="autonomous"?{...t,preset:s,trustLevel:"autonomous",autonomyMode:"autonomous",approvalMode:"none",scopes:[...pa]}:{...t,preset:s}}function Tr(t,s,a){const r={preset:t,label:"Forge Pilot Token",agentLabel:s,agentType:"assistant",description:"Collaborative planning agent.",trustLevel:"trusted",autonomyMode:"scoped_write",approvalMode:"high_impact_only",scopes:[...pa]};return tl(r,t,a)}function Ou({open:t,onOpenChange:s,pending:a=!1,initialPreset:r="operator",defaultAgentLabel:i="OpenClaw",recommendedScopes:n=[...pa],onSubmit:o}){const[d,c]=g.useState(()=>Tr(r,i,n)),[b,p]=g.useState(null);g.useEffect(()=>{t&&(c(Tr(r,i,n)),p(null))},[t,r,i,n]);const f=[{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,x)=>e.jsx(Ke,{columns:3,value:m.preset,onChange:v=>x(tl(m,v,n)),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,x)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Agent name",labelHelp:"This label identifies the agent in every log entry, approval notification, and XP attribution. Pick something memorable.",children:e.jsx(se,{value:m.agentLabel,placeholder:"OpenClaw",onChange:v=>x({agentLabel:v.target.value})})}),e.jsx(B,{label:"Token label",description:"A short name for this credential — mainly for your reference in the token list.",children:e.jsx(se,{value:m.label,placeholder:"Forge Pilot Token",onChange:v=>x({label:v.target.value})})}),e.jsxs("div",{className:"grid gap-5 md:grid-cols-2",children:[e.jsx(B,{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:v=>x({agentType:v.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(B,{label:"Description",description:"Optional note about what this agent does.",children:e.jsx(se,{value:m.description,placeholder:"Collaborative planning agent.",onChange:v=>x({description:v.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,x)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{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(Ke,{columns:3,value:m.trustLevel,onChange:v=>x({trustLevel:v}),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(B,{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(Ke,{columns:3,value:m.autonomyMode,onChange:v=>x({autonomyMode:v}),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(B,{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(Ke,{columns:3,value:m.approvalMode,onChange:v=>x({approvalMode:v}),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,x)=>e.jsxs(B,{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:Fu.map(v=>{const w=m.scopes.includes(v.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;x({scopes:m.scopes.filter(h=>h!==v.value)})}else x({scopes:[...m.scopes,v.value]})},children:[e.jsx("div",{className:"font-medium",children:v.label}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/58",children:v.description})]},v.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(He,{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:c,steps:f,submitLabel:"Issue token",pending:a,pendingLabel:"Issuing token…",error:b,onSubmit:async()=>{p(null);const m=Fd.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 x=m.error.issues[0];p((x==null?void 0:x.message)??"Check the agent name and at least one scope before issuing.");return}try{await o(m.data),s(!1)}catch(x){p(x instanceof Error?x.message:"Could not issue the token right now.")}}})}function Ir(t){return{source:"new",taskId:"",title:"",description:"",owner:t,projectId:"",status:"done",points:40}}function Ru({open:t,onOpenChange:s,pending:a=!1,defaultOwner:r="",availableTasks:i=[],availableProjects:n=[],onSubmit:o}){const[d,c]=g.useState(()=>Ir(r)),[b,p]=g.useState(null);g.useEffect(()=>{t&&(c(Ir(r)),p(null))},[t,r]);const f=[{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,x)=>e.jsxs(e.Fragment,{children:[e.jsx(Ke,{columns:2,value:m.source,onChange:v=>x({source:v,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"&&i.length>0?e.jsx(B,{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:v=>x({taskId:v.target.value}),children:[e.jsx("option",{value:"",children:"— choose a task —"}),i.map(v=>e.jsxs("option",{value:v.id,children:[v.title," · ",v.status.replaceAll("_"," ")]},v.id))]})}):m.source==="existing"&&i.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,x)=>e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Title",labelHelp:"Write the title like a short achievement: what was completed, not what was started.",children:e.jsx(se,{value:m.title,placeholder:"Write postmortem draft",onChange:v=>x({title:v.target.value})})}),e.jsx(B,{label:"Owner",description:"Who did this work? Defaults to the operator name.",children:e.jsx(se,{value:m.owner,placeholder:"Your name",onChange:v=>x({owner:v.target.value})})}),e.jsx(B,{label:"Description",description:"What moved forward? What should remain visible in the project history?",children:e.jsx(ve,{className:"min-h-28",value:m.description,placeholder:"Wrote the full incident timeline and drafted the three key learnings for the team retrospective.",onChange:v=>x({description:v.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,x)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-5 md:grid-cols-2",children:[e.jsx(B,{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:v=>x({projectId:v.target.value}),children:[e.jsx("option",{value:"",children:"No project link"}),n.map(v=>e.jsx("option",{value:v.id,children:v.title},v.id))]})}),e.jsx(B,{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(Ke,{columns:2,value:m.status,onChange:v=>x({status:v}),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(B,{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(se,{type:"number",min:5,max:500,className:"w-36",value:m.points,onChange:v=>x({points:Number(v.target.value)})}),e.jsx("div",{className:"flex gap-2",children:[20,40,80,120].map(v=>e.jsxs("button",{type:"button",className:`rounded-full px-3 py-1.5 text-xs transition ${m.points===v?"bg-white/18 text-white":"bg-white/[0.06] text-white/55 hover:bg-white/[0.10]"}`,onClick:()=>x({points:v}),children:[v," xp"]},v))})]})})]})}];return e.jsx(He,{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:c,steps:f,submitLabel:"Log work",pending:a,pendingLabel:"Logging work…",error:b,onSubmit:async()=>{if(p(null),d.source==="new"&&d.title.trim().length===0){p("Add a title so Forge knows what work to create.");return}if(d.source==="existing"&&!d.taskId){p("Pick an existing task or switch to New task.");return}try{await o({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){p(m instanceof Error?m.message:"Could not log the work right now.")}}})}function sl({text:t}){const[s,a]=g.useState(!1),r=async()=>{try{await navigator.clipboard.writeText(t),a(!0),setTimeout(()=>a(!1),2200)}catch{}};return e.jsxs("button",{type:"button",onClick:()=>void r(),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(mi,{className:"size-3 text-emerald-400"}):e.jsx(Br,{className:"size-3"}),s?"Copied":"Copy"]})}function ei({label:t,children:s,copyText:a}){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(sl,{text:a??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 _u({open:t,onOpenChange:s,state:a}){if(!a)return null;const{tokenString:r,agentLabel:i,onboarding:n}=a,o=JSON.stringify({baseUrl:n.forgeBaseUrl,apiToken:r,actorLabel:i,timeoutMs:n.defaultTimeoutMs},null,2),d=[`curl -s ${n.healthUrl} \\`,` -H "Authorization: Bearer ${r}" \\`,' -H "X-Forge-Source: agent" \\',` -H "X-Forge-Actor: ${i}"`].join(`
33
+ `),c=["openclaw gateway restart",'openclaw agent --message "forge_get_operator_overview"'].join(`
34
+ `);return e.jsx(Ps,{open:t,onOpenChange:s,children:e.jsxs(Ms,{children:[e.jsx(As,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.82)] backdrop-blur-xl"}),e.jsxs(Ds,{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(ba,{className:"sr-only",children:"Token issued — setup instructions"}),e.jsx(va,{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(Ts,{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(ca,{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(yt,{className:"size-4"})})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-5",children:e.jsxs(Ve.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(_,{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:r}),e.jsx(sl,{text:r})]}),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(ei,{label:"Plugin params — paste into openclaw.json → plugins → forge → params",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:"2"}),e.jsx("span",{className:"text-sm font-medium text-white",children:"Restart the gateway and confirm the agent can connect"})]}),e.jsx(ei,{label:"Run in terminal",copyText:c,children:c})]}),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:i})," is authenticated."]}),e.jsx("div",{className:"mt-3",children:e.jsx(ei,{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(K,{onClick:()=>s(!1),children:[e.jsx(mi,{className:"size-4"}),"Done"]})]})})]})]})})}function ia(t,s){return s.every(a=>t.scopes.includes(a))}function $u(){var le,ce,he,je,W;const t=Qe(),[s,a]=g.useState(!1),[r,i]=g.useState("operator"),[n,o]=g.useState(null),[d,c]=g.useState(!1),[b,p]=g.useState(!1),[f,m]=g.useState(!1),x=oe({queryKey:["forge-operator-session"],queryFn:cs}),v=x.isSuccess,w=oe({queryKey:["forge-settings"],queryFn:Ta,enabled:v}),h=oe({queryKey:["forge-approval-requests"],queryFn:Kc,enabled:v}),P=oe({queryKey:["forge-agent-onboarding"],queryFn:qc}),T=oe({queryKey:["forge-operator-context"],queryFn:Bc,enabled:v}),O=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"]})])},y=ue({mutationFn:$=>Yc($),onSuccess:O}),C=ue({mutationFn:$=>Jc($),onSuccess:async($,k)=>{if(await O(),j){const R=$.token;o({tokenString:R.token,agentLabel:R.tokenSummary.agentLabel??"forge-agent",onboarding:j}),c(!0)}}}),l=ue({mutationFn:$=>Vc($),onSuccess:O}),N=ue({mutationFn:$=>Uc($),onSuccess:O}),u=ue({mutationFn:$=>Qc($),onSuccess:O}),M=ue({mutationFn:am,onSuccess:O}),A=(le=w.data)==null?void 0:le.settings,I=((ce=h.data)==null?void 0:ce.approvalRequests)??[],j=(he=P.data)==null?void 0:he.onboarding,S=(je=T.data)==null?void 0:je.context,E=(A==null?void 0:A.agentTokens.filter($=>$.status==="active"))??[],X=(j==null?void 0:j.recommendedScopes)??[],G=E.some($=>ia($,X)),z=E.some($=>ia($,["rewards.manage"])),D=E.some($=>ia($,["psyche.write"])),F=E.some($=>$.autonomyMode!=="approval_required"&&ia($,["write"])),q=E.length>0,Y=g.useMemo(()=>{if(!S)return[];const $=[...S.focusTasks,...S.currentBoard.backlog,...S.currentBoard.focus,...S.currentBoard.inProgress,...S.currentBoard.blocked,...S.currentBoard.done],k=new Map;for(const R of $)k.set(R.id,R);return[...k.values()]},[S]),L=(A==null?void 0:A.profile.operatorName)??"",V=[{label:"Operator session",ok:!0,badge:"active",badgeTone:"emerald",detail:(W=x.data)!=null&&W.session?`Session open as ${x.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:q,badge:q?`${E.length} active`:"none issued",badgeTone:q?"emerald":"amber",detail:q?`${E.length} active token${E.length===1?"":"s"} allow external agents and scripts to authenticate.`:"No token yet. Issue one to let external agents connect via the API.",action:q?null:{label:"Issue token",preset:"operator",onClick:()=>{i("operator"),a(!0)}}},{label:"Full operator bundle",ok:G,badge:G?"ready":"optional",badgeTone:G?"emerald":"neutral",detail:G?"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:G?null:{label:"Set up",preset:"operator",onClick:()=>{i("operator"),a(!0)}}},{label:"Reward control",ok:z,badge:z?"ready":"optional",badgeTone:z?"emerald":"neutral",detail:z?"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:z?null:{label:"Add scope",preset:"operator",onClick:()=>{i("operator"),a(!0)}}},{label:"Psyche writes",ok:D,badge:D?"ready":"optional",badgeTone:D?"emerald":"neutral",detail:D?"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:D?null:{label:"Add scope",preset:"operator",onClick:()=>{i("operator"),a(!0)}}},{label:"Scoped writes",ok:F,badge:F?"ready":"optional",badgeTone:F?"emerald":"neutral",detail:F?"A trusted agent can write without constant approval prompts.":"All write tokens are approval-required. Agents must queue every mutation for your review.",action:F?null:{label:"Configure",preset:"operator",onClick:()=>{i("operator"),a(!0)}}}];return x.isLoading||w.isLoading?e.jsx(xt,{eyebrow:"Settings · Agents",title:"Loading agent console",description:"Establishing the operator session and loading agent configuration.",columns:2,blocks:6}):x.isError?e.jsx(Le,{eyebrow:"Settings · Agents",error:x.error,onRetry:()=>void x.refetch()}):w.isError||!A?e.jsx(Le,{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(Fe,{title:"Agents",description:"Connection status, capability access, tokens, approval queue, and work logging."}),e.jsx(zs,{}),e.jsx(Ou,{open:s,onOpenChange:a,pending:y.isPending,initialPreset:r,defaultAgentLabel:(j==null?void 0:j.defaultActorLabel)??"OpenClaw",recommendedScopes:X,onSubmit:async $=>{const k=await y.mutateAsync($);a(!1),j&&(o({tokenString:k.token.token,agentLabel:$.agentLabel,onboarding:j}),c(!0))}}),e.jsx(_u,{open:d,onOpenChange:c,state:n}),e.jsx(Ru,{open:b,onOpenChange:p,pending:M.isPending,defaultOwner:L,availableTasks:Y,availableProjects:(S==null?void 0:S.activeProjects)??[],onSubmit:async $=>{await M.mutateAsync($)}}),e.jsxs("div",{className:"grid gap-5",children:[S?e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsx(Dt,{label:"Active projects",value:S.activeProjects.length,tone:"core"}),e.jsx(Dt,{label:"Focus tasks",value:S.focusTasks.length,tone:"core"}),e.jsx(Dt,{label:"Pending approvals",value:I.filter($=>$.status==="pending").length,tone:"core"}),e.jsx(Dt,{label:"Operator level",value:S.xp.profile.level,tone:"core",detail:`${S.xp.profile.totalXp} total XP`})]}):null,e.jsxs(Z,{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:V.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(_,{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(Jt,{className:"size-3"})]}):null]},$.label))})]}),e.jsxs(Z,{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(K,{size:"sm",variant:"secondary",onClick:()=>{i("operator"),a(!0)},children:[e.jsx(Ht,{className:"size-3.5"}),"Issue token"]})]}),e.jsx("div",{className:"mt-4 grid gap-3",children:A.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."}):A.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(_,{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(k=>e.jsx(_,{className:$.scopes.includes(k)?"text-emerald-300":"text-white/30",children:k},k))}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(K,{variant:"secondary",size:"sm",pending:C.isPending,pendingLabel:"Rotating",onClick:()=>void C.mutateAsync($.id),children:"Rotate & reveal new token"}),e.jsx(K,{variant:"ghost",size:"sm",pending:l.isPending,pendingLabel:"Revoking",onClick:()=>void l.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."})]}),A.agents.length>0?e.jsxs(Z,{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:A.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(_,{className:"text-white/60",children:$.trustLevel})]},$.id))})]}):null,S?e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1.05fr)_minmax(0,0.95fr)]",children:[e.jsxs(Z,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Recommended next move"}),S.recommendedNextTask?e.jsxs("div",{className:"mt-4 grid gap-2",children:[e.jsx(Te,{kind:"task",label:S.recommendedNextTask.title,variant:"heading",size:"lg"}),e.jsx("div",{className:"text-sm leading-6 text-white/58",children:S.recommendedNextTask.description||"No extra notes yet."}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-2",children:[e.jsx(_,{children:S.recommendedNextTask.status.replaceAll("_"," ")}),e.jsxs(_,{children:[S.recommendedNextTask.points," xp"]}),e.jsx(_,{children:S.recommendedNextTask.owner})]})]}):e.jsx("div",{className:"mt-4 text-sm text-white/55",children:"Board is clear. No recommended task right now."})]}),e.jsxs(Z,{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:S.currentBoard.backlog.length},{label:"Focus",value:S.currentBoard.focus.length},{label:"In progress",value:S.currentBoard.inProgress.length},{label:"Blocked",value:S.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,S&&S.activeProjects.length>0?e.jsxs(Z,{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:S.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(Te,{kind:"project",label:$.title}),e.jsxs(_,{children:[$.progress,"%"]})]}),e.jsx("div",{className:"mt-2",children:e.jsx(xe,{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(Z,{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"}),I.filter($=>$.status==="pending").length>0?e.jsxs(_,{className:"text-amber-300",children:[I.filter($=>$.status==="pending").length," pending"]}):null]}),e.jsx("div",{className:"mt-4 grid gap-3",children:I.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."}):I.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(_,{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(K,{variant:"secondary",size:"sm",pending:N.isPending,pendingLabel:"Approving",onClick:()=>void N.mutateAsync($.id),children:"Approve"}),e.jsx(K,{variant:"ghost",size:"sm",pending:u.isPending,pendingLabel:"Rejecting",onClick:()=>void u.mutateAsync($.id),children:"Reject"})]}):null]},$.id))})]}),e.jsxs(Z,{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(K,{variant:"secondary",size:"sm",onClick:()=>p(!0),children:[e.jsx(Wl,{className:"size-3.5"}),"Log work"]})]}),M.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(Te,{kind:"task",label:M.data.task.title,showKind:!1})}),". Operator XP updated to ",M.data.xp.profile.totalXp,"."]}):null]}),e.jsxs(Z,{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]}),f?e.jsx(qr,{className:"size-4 shrink-0 text-white/38"}):e.jsx(Kr,{className:"size-4 shrink-0 text-white/38"})]}),f&&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(_,{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(_,{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(_,{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:"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})]})]})]}):f&&P.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."}):f?e.jsx("div",{className:"mt-4 text-sm text-white/50",children:"Loading…"}):null]})]})]})}const Ut={goal:"Goals",project:"Projects",task:"Tasks",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"},Bu={goal:"goal",project:"project",task:"task",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 zu(t){return new Date(t).toLocaleString()}function qu(){var y,C;const t=Qe(),[s,a]=g.useState(""),[r,i]=g.useState([]),n=oe({queryKey:["forge-operator-session"],queryFn:cs}),o=n.isSuccess,d=oe({queryKey:["forge-settings-bin"],queryFn:zc,enabled:o}),c=async()=>{await t.invalidateQueries({predicate:l=>Array.isArray(l.queryKey)&&typeof l.queryKey[0]=="string"&&l.queryKey[0].startsWith("forge-")})},b=ue({mutationFn:l=>Bn({operations:[{entityType:l.entityType,id:l.entityId}]}),onSuccess:c}),p=ue({mutationFn:l=>$n({operations:[{entityType:l.entityType,id:l.entityId,mode:"hard"}]}),onSuccess:c}),f=ue({mutationFn:l=>Bn({operations:l.map(N=>({entityType:N.entityType,id:N.entityId}))}),onSuccess:c}),m=ue({mutationFn:l=>$n({operations:l.map(N=>({entityType:N.entityType,id:N.entityId,mode:"hard"}))}),onSuccess:c}),x=((y=d.data)==null?void 0:y.bin.records)??[],v=s.trim().toLowerCase(),w=g.useMemo(()=>x.filter(l=>r.length===0||r.includes(l.entityType)?v?[l.title,l.subtitle??"",l.entityType,l.entityId,l.deletedByActor??"",l.deletedSource??"",l.deleteReason??""].join(" ").toLowerCase().includes(v):!0:!1),[v,x,r]),h=g.useMemo(()=>{const l=new Map;for(const N of w){const u=l.get(N.entityType)??[];u.push(N),l.set(N.entityType,u)}return[...l.entries()].sort((N,u)=>Ut[N[0]].localeCompare(Ut[u[0]]))},[w]),P=g.useMemo(()=>[...new Set(x.map(l=>l.entityType))].sort((l,N)=>Ut[l].localeCompare(Ut[N])),[x]);function T(l){i(N=>N.includes(l)?N.filter(u=>u!==l):[...N,l])}async function O(){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 n.isLoading||d.isLoading?e.jsx(xt,{eyebrow:"Settings",title:"Loading bin",description:"Loading deleted items and restore controls.",columns:2,blocks:6}):n.isError?e.jsx(Le,{eyebrow:"Settings",error:n.error,onRetry:()=>void n.refetch()}):d.isError?e.jsx(Le,{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(Fe,{title:"Bin",description:"Restore soft-deleted items or permanently remove them when you really mean it.",badge:`${((C=d.data)==null?void 0:C.bin.totalCount)??0} deleted items`}),e.jsx(zs,{}),e.jsxs(Z,{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(Tt,{className:"pointer-events-none absolute left-4 top-1/2 size-4 -translate-y-1/2 text-white/35"}),e.jsx(se,{value:s,onChange:l=>a(l.target.value),placeholder:"Search title, id, reason, or source",className:"pl-11"})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:P.map(l=>{const N=r.includes(l);return e.jsx("button",{type:"button",onClick:()=>T(l),className:te("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:Ut[l]},l)})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 lg:max-w-[22rem] lg:justify-end",children:[e.jsxs(K,{variant:"secondary",size:"sm",disabled:w.length===0,pending:f.isPending,pendingLabel:"Restoring",onClick:()=>void f.mutateAsync(w),children:[e.jsx(ai,{className:"size-4"}),e.jsx("span",{children:"Restore visible"})]}),e.jsxs(K,{variant:"secondary",size:"sm",disabled:w.length===0,pending:m.isPending,pendingLabel:"Deleting",onClick:()=>void O(),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"]}),r.length>0?e.jsxs("span",{children:[r.length," type filters active"]}):null,v?e.jsxs("span",{children:["Search: “",s.trim(),"”"]}):null]})]}),x.length===0?e.jsxs(Z,{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."})]}):h.length===0?e.jsxs(Z,{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:h.map(([l,N])=>{const u=Bu[l];return e.jsxs(Z,{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:[u?e.jsx(xe,{kind:u,label:Ut[l],compact:!0}):null,u?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:Ut[l]}),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(M=>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:M.title}),M.subtitle?e.jsx("div",{className:"mt-1 text-sm text-white/62",children:M.subtitle}):null,e.jsxs("div",{className:"mt-3 flex flex-wrap gap-3 text-xs text-white/45",children:[e.jsxs("span",{children:["Deleted ",zu(M.deletedAt)]}),M.deletedByActor?e.jsxs("span",{children:["By ",M.deletedByActor]}):null,M.deletedSource?e.jsxs("span",{children:["Source ",M.deletedSource]}):null,M.deleteReason?e.jsxs("span",{children:["Reason: ",M.deleteReason]}):null]})]}),e.jsxs("div",{className:"flex flex-wrap items-start justify-end gap-2",children:[e.jsxs(K,{variant:"secondary",size:"sm",pending:b.isPending,pendingLabel:"Restoring",onClick:()=>void b.mutateAsync(M),children:[e.jsx(ai,{className:"size-4"}),e.jsx("span",{children:"Restore"})]}),e.jsxs(K,{variant:"secondary",size:"sm",pending:p.isPending,pendingLabel:"Deleting",onClick:()=>void p.mutateAsync(M),children:[e.jsx(bt,{className:"size-4"}),e.jsx("span",{children:"Delete forever"})]})]})]},`${M.entityType}:${M.entityId}`))})]},l)})})]})}const Pr=[{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:Ts,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:Fr,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:Ts,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 Ku(t){if(!t)return Pr;const s=t==="google"?"Google Calendar setup":t==="apple"?"Apple Calendar setup":t==="microsoft"?"Exchange Online setup":"Custom CalDAV setup";return Pr.filter(a=>a.title==="Before you connect anything"||a.title===s)}function Uu({section:t,compact:s}){const a=t.icon;return e.jsxs(Z,{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(a,{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(r=>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:r},r))}),t.links.length>0?e.jsx("div",{className:"flex flex-wrap gap-2",children:t.links.map(r=>e.jsxs("a",{href:r.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(da,{className:"size-3.5"}),r.label]},r.href))}):null]})}function Qu({provider:t,compact:s=!1}){const a=Ku(t);return e.jsx("div",{className:"grid gap-4",children:a.map(r=>e.jsx(Uu,{section:r,compact:s},r.title))})}const xa={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 ti(t){return{provider:t,label:xa[t].label,serverUrl:xa[t].serverUrl,username:"",password:"",clientId:"",clientSecret:"",refreshToken:"",selectedCalendarUrls:[],forgeCalendarUrl:null,createForgeCalendar:!1}}function ts(t,s){const a=s.trim();return a.length>0?a:xa[t].label}function Xu({open:t,onOpenChange:s,initialProvider:a="google",initialStepId:r,microsoftSetup:i,onSubmit:n,pending:o=!1}){const[d,c]=g.useState(()=>ti(a)),[b,p]=g.useState(null),[f,m]=g.useState(null),[x,v]=g.useState(null),w=g.useRef(null),h=()=>{v(null),w.current=null},P=l=>{m(l);const N=l.calendars.filter(M=>M.selectedByDefault).map(M=>M.url),u=l.calendars.find(M=>M.isForgeCandidate);c(M=>({...M,selectedCalendarUrls:M.selectedCalendarUrls.length>0?M.selectedCalendarUrls.filter(A=>l.calendars.some(I=>I.url===A)):N,forgeCalendarUrl:M.provider==="microsoft"?null:(u==null?void 0:u.url)??M.forgeCalendarUrl??null,createForgeCalendar:M.provider==="microsoft"?!1:M.createForgeCalendar&&!u})),p(null)};g.useEffect(()=>{var l;if(!t){(l=w.current)==null||l.close(),w.current=null;return}p(null),m(null),c(ti(a)),h()},[a,t]),g.useEffect(()=>{if(!t||!x||x.status!=="pending")return;const l=u=>{var M,A;u.origin===window.location.origin&&(((M=u.data)==null?void 0:M.type)!=="forge:microsoft-calendar-auth"||((A=u.data)==null?void 0:A.sessionId)!==x.sessionId||O(x.sessionId))},N=window.setInterval(()=>{!w.current||!w.current.closed||(w.current=null,O(x.sessionId,{afterPopupClose:!0}))},400);return window.addEventListener("message",l),()=>{window.removeEventListener("message",l),window.clearInterval(N)}},[x,t]);const T=ue({mutationFn:()=>d.provider==="google"?_a({provider:"google",username:d.username,clientId:d.clientId,clientSecret:d.clientSecret,refreshToken:d.refreshToken}):d.provider==="apple"?_a({provider:"apple",username:d.username,password:d.password}):_a({provider:"caldav",serverUrl:d.serverUrl,username:d.username,password:d.password}),onSuccess:({discovery:l})=>{P(l)},onError:l=>{m(null),p(l instanceof Error?l.message:"Forge could not discover calendars with these credentials.")}}),O=async(l,N)=>{try{const{session:u}=await bc(l);if(v(u),u.status==="authorized"&&u.discovery){P(u.discovery),p(null);return}if(u.status==="error"||u.status==="expired"){p(u.error??"Microsoft sign-in did not complete. Start the guided sign-in again.");return}N!=null&&N.afterPopupClose&&p("The Microsoft sign-in window closed before Forge received permission.")}catch(u){p(u instanceof Error?u.message:"Forge could not confirm the Microsoft sign-in session.")}},y=async()=>{var l;try{if(!i.isReadyForSignIn)throw new Error("Finish the Microsoft setup in Settings -> Calendar before starting sign-in.");p(null),m(null);const{session:N}=await gc({label:ts("microsoft",d.label)});if(!N.authUrl)throw new Error("Forge could not prepare the Microsoft sign-in URL.");if(v(N),(l=w.current)==null||l.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){h(),p(N instanceof Error?N.message:"Forge could not start the Microsoft sign-in flow.")}},C=g.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:(l,N)=>e.jsxs("div",{className:"grid gap-5",children:[e.jsx(B,{label:"Provider",description:"Each setup path is guided. Forge discovers calendars before anything is saved.",children:e.jsx(Ke,{value:l.provider,onChange:u=>{m(null),p(null),h(),N(ti(u))},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(Hl,{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:l.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(Ts,{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:l.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(Qu,{provider:l.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:(l,N)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(B,{label:"Connection label",description:"This is the readable label Forge shows in settings and the calendar health cards.",children:e.jsx(se,{value:l.label,onChange:u=>N({label:u.target.value}),placeholder:xa[l.provider].label})}),l.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(_,{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:i.clientId||"Not configured yet"})]}),e.jsxs("div",{children:["Tenant:"," ",e.jsx("span",{className:"font-medium text-white",children:i.tenantId})]}),e.jsxs("div",{className:"break-all",children:["Redirect URI:"," ",e.jsx("span",{className:"font-medium text-white",children:i.redirectUri})]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-3",children:[e.jsxs(K,{type:"button",onClick:()=>void y(),disabled:!i.isReadyForSignIn,pending:(x==null?void 0:x.status)==="pending",pendingLabel:"Waiting for Microsoft",children:[e.jsx(da,{className:"size-4"}),(x==null?void 0:x.status)==="authorized"?"Sign in again":"Sign in with Microsoft"]}),x!=null&&x.accountLabel?e.jsxs(_,{className:"bg-emerald-500/16 text-emerald-100",children:[e.jsx(Qr,{className:"mr-1 size-3.5"}),x.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."})]}),i.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:i.setupMessage})]})}):e.jsxs(e.Fragment,{children:[l.provider==="caldav"?e.jsx(B,{label:"CalDAV base URL",description:"Use the account-level CalDAV server URL, not an individual calendar collection URL.",children:e.jsx(se,{value:l.serverUrl,onChange:u=>N({serverUrl:u.target.value}),placeholder:"https://caldav.example.com"})}):null,l.provider==="apple"?e.jsx(B,{label:"Apple CalDAV base URL",children:e.jsx(se,{value:"https://caldav.icloud.com",disabled:!0})}):null,e.jsx(B,{label:"Account email or username",children:e.jsx(se,{value:l.username,onChange:u=>N({username:u.target.value}),placeholder:"operator@example.com"})}),l.provider==="google"?e.jsxs(e.Fragment,{children:[e.jsx(B,{label:"Google client ID",children:e.jsx(se,{value:l.clientId,onChange:u=>N({clientId:u.target.value}),placeholder:"1234567890-abcdef.apps.googleusercontent.com"})}),e.jsx(B,{label:"Google client secret",children:e.jsx(se,{type:"password",value:l.clientSecret,onChange:u=>N({clientSecret:u.target.value}),placeholder:"GOCSPX-..."})}),e.jsx(B,{label:"Refresh token",children:e.jsx(se,{type:"password",value:l.refreshToken,onChange:u=>N({refreshToken:u.target.value}),placeholder:"1//0g..."})})]}):e.jsx(B,{label:l.provider==="apple"?"App-specific password":"Password or app password",children:e.jsx(se,{type:"password",value:l.password,onChange:u=>N({password:u.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:(l,N)=>e.jsxs("div",{className:"grid gap-4",children:[l.provider==="microsoft"?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(K,{type:"button",onClick:()=>void y(),pending:(x==null?void 0:x.status)==="pending",pendingLabel:"Waiting for Microsoft",children:[e.jsx(da,{className:"size-4"}),(x==null?void 0:x.status)==="authorized"?"Reconnect Microsoft":"Sign in with Microsoft"]}),f?e.jsxs(_,{className:"bg-white/[0.08] text-white/74",children:[f.calendars.length," discovered"]}):null]}):e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(K,{pending:T.isPending,pendingLabel:"Discovering",onClick:()=>void T.mutateAsync(),children:[e.jsx(ns,{className:"size-4"}),"Discover calendars"]}),f?e.jsxs(_,{className:"bg-white/[0.08] text-white/74",children:[f.calendars.length," discovered"]}):null]}),f?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4 text-sm leading-6 text-white/64",children:["Discovered through"," ",e.jsx("span",{className:"font-medium text-white",children:f.serverUrl}),f.homeUrl?e.jsxs(e.Fragment,{children:[" ","· home set"," ",e.jsx("span",{className:"font-medium text-white",children:f.homeUrl})]}):null]}),e.jsx("div",{className:"grid gap-3",children:f.calendars.map(u=>{const M=l.selectedCalendarUrls.includes(u.url),A=l.forgeCalendarUrl===u.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:u.displayName}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[u.timezone||"No timezone exposed"," ·"," ",u.url]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[u.isForgeCandidate?e.jsx(_,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"Forge match"}):null,u.isPrimary?e.jsx(_,{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:M?l.selectedCalendarUrls.filter(I=>I!==u.url):[...l.selectedCalendarUrls,u.url]}),className:`rounded-full px-3 py-2 text-sm transition ${M?"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:M?"Mirrored":"Mirror into Forge"}),l.provider!=="microsoft"?e.jsx("button",{type:"button",onClick:()=>N({forgeCalendarUrl:u.url,createForgeCalendar:!1}),className:`rounded-full px-3 py-2 text-sm transition ${A?"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:A?"Forge writes here":"Use for Forge writes"}):e.jsx(_,{className:"bg-sky-400/12 text-sky-100",children:"Read only"})]})]},u.url)})}),l.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:!l.createForgeCalendar}),className:`rounded-full px-3 py-2 text-sm transition ${l.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:l.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:l.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:l=>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:ts(l.provider,l.label)}),e.jsx("div",{className:"mt-1 text-sm text-white/58",children:l.provider==="google"?"Google Calendar":l.provider==="apple"?"Apple Calendar":l.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:l.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:l.provider==="microsoft"?"read only":l.forgeCalendarUrl?"existing calendar":l.createForgeCalendar?"new Forge calendar":"not selected"})]})]})]})})}],[f,T.isPending,d.provider,x]);return e.jsx(He,{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:l=>{c(l),f&&l.provider!==f.provider&&m(null)},steps:C,submitLabel:"Connect provider",pending:o,pendingLabel:"Connecting",error:b,initialStepId:r,onSubmit:async()=>{try{if(p(null),!f){p("Discover the available calendars before saving the connection.");return}if(d.selectedCalendarUrls.length===0){p("Select at least one calendar to mirror into Forge.");return}if(d.provider!=="microsoft"&&!d.forgeCalendarUrl&&!d.createForgeCalendar){p("Choose the calendar Forge should write into, or ask Forge to create one.");return}if(d.provider==="google")await n({provider:"google",label:ts("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 n({provider:"apple",label:ts("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(!(x!=null&&x.sessionId)||x.status!=="authorized"){p("Complete the Microsoft sign-in flow before saving this connection.");return}await n({provider:"microsoft",label:ts("microsoft",d.label),authSessionId:x.sessionId,selectedCalendarUrls:d.selectedCalendarUrls})}else await n({provider:"caldav",label:ts("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(l){p(l instanceof Error?l.message:"Forge could not create this calendar connection.")}}})}function ss(t){try{const s=new URL(t);return s.pathname.endsWith("/")||(s.pathname=`${s.pathname}/`),s.toString()}catch{return t}}function Mr(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 Ar="/api/v1/calendar/oauth/microsoft/callback",Gu=/^[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 Dr(t){return{clientId:t.clientId,tenantId:t.tenantId,redirectUri:t.redirectUri}}function Wu(t){const s={};if(t.clientId.trim()?Gu.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 a=new URL(t.redirectUri.trim());a.protocol!=="http:"&&a.protocol!=="https:"?s.redirectUri="Redirect URI must use http or https.":a.pathname!==Ar&&(s.redirectUri=`Redirect URI must end with ${Ar}.`)}catch{s.redirectUri="Redirect URI must be a full URL."}return{issues:s,isValid:Object.keys(s).length===0}}function Hu(t,s){return t.clientId.trim()===s.clientId.trim()&&t.tenantId.trim()===s.tenantId.trim()&&t.redirectUri.trim()===s.redirectUri.trim()}function Yu(){var R,Q,Ce,ie,_e;const t=Qe(),[s,a]=ut(),[r,i]=g.useState(!1),[n,o]=g.useState("google"),[d,c]=g.useState(void 0),[b,p]=g.useState(null),[f,m]=g.useState([]),[x,v]=g.useState(!1),[w,h]=g.useState(null),[P,T]=g.useState(()=>No()),[O,y]=g.useState({clientId:"",tenantId:"common",redirectUri:""}),C=oe({queryKey:["forge-operator-session"],queryFn:cs}),l=C.isSuccess,N=oe({queryKey:["forge-settings"],queryFn:Ta,enabled:l}),u=oe({queryKey:["forge-calendar-connections"],queryFn:xc,enabled:l}),M=oe({queryKey:["forge-calendar-resources"],queryFn:Nc,enabled:l}),A=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"]})])},I=ue({mutationFn:yc,onSuccess:A}),j=ue({mutationFn:J=>wc(J),onSuccess:A}),S=ue({mutationFn:({connectionId:J,patch:H})=>jc(J,H),onSuccess:A}),E=ue({mutationFn:J=>kc(J),onSuccess:A}),X=ue({mutationFn:J=>mo({calendarProviders:{microsoft:J}}),onSuccess:A}),G=ue({mutationFn:J=>fc({clientId:J.clientId.trim(),tenantId:J.tenantId.trim()||"common",redirectUri:J.redirectUri.trim()})});g.useEffect(()=>{if(!l)return;const J=s.get("intent"),H=s.get("provider");if(J!=="connect")return;o(H==="apple"||H==="caldav"||H==="google"||H==="microsoft"?H:"google"),c(H==="microsoft"?"credentials":void 0),i(!0);const pe=new URLSearchParams(s);pe.delete("intent"),pe.delete("provider"),a(pe,{replace:!0})},[l,s,a]),g.useEffect(()=>{var H;const J=(H=N.data)==null?void 0:H.settings.calendarProviders.microsoft;J&&y(Dr(J))},[N.data]);const z=g.useMemo(()=>{var H;const J=new Map;for(const pe of((H=M.data)==null?void 0:H.calendars)??[]){const Ie=J.get(pe.connectionId)??[];Ie.push(pe),J.set(pe.connectionId,Ie)}return J},[M.data]),D=g.useMemo(()=>{var J;return So(((J=M.data)==null?void 0:J.calendars)??[],P.calendarColors)},[(R=M.data)==null?void 0:R.calendars,P.calendarColors]),F=g.useMemo(()=>{var J;return((J=u.data)==null?void 0:J.connections.find(H=>H.id===b))??null},[u.data,b]),q=g.useMemo(()=>{var J;return((J=u.data)==null?void 0:J.connections.find(H=>H.id===w))??null},[u.data,w]),Y=g.useMemo(()=>b?z.get(b)??[]:[],[z,b]),L=((Q=N.data)==null?void 0:Q.settings.calendarProviders.microsoft)??null,V=g.useMemo(()=>Wu(O),[O]),le=L!==null&&!Hu(O,Dr(L)),ce=!(L!=null&&L.isReadyForSignIn)||!V.isValid||le||X.isPending,he=oe({queryKey:["forge-calendar-connection-discovery",b],queryFn:()=>vc(b),enabled:l&&b!==null});g.useEffect(()=>{if(!b){m([]),v(!1);return}const J=Y.filter(H=>H.selectedForSync).map(H=>ss(H.remoteId));m(J),v(!0)},[b,Y]),g.useEffect(()=>{Cm(P)},[P]);const je=g.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:(J,H)=>{var fe,ye;if(he.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(he.isError||!((fe=he.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:he.error instanceof Error?he.error.message:"Forge could not rediscover calendars for this connection."});const pe=he.data.discovery,Ie=(F==null?void 0:F.provider)==="microsoft",Ye=typeof((ye=F==null?void 0:F.config)==null?void 0:ye.forgeCalendarUrl)=="string"?ss(F.config.forgeCalendarUrl):null;return e.jsx("div",{className:"grid gap-3",children:pe.calendars.map($e=>{const ae=ss($e.url),ot=x?J.selectedCalendarUrls.includes(ae):Y.some(Je=>Je.selectedForSync&&ss(Je.remoteId)===ae),st=Ye===ae;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:$e.displayName}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[$e.timezone||"No timezone exposed"," · ",$e.url]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[st&&!Ie?e.jsx(_,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"Forge writes here"}):null,Ie?e.jsx(_,{className:"bg-sky-400/12 text-sky-100",children:"Read only"}):null,$e.isPrimary?e.jsx(_,{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:st&&!Ie,onClick:()=>H({selectedCalendarUrls:ot?J.selectedCalendarUrls.filter(Je=>Je!==ae):[...J.selectedCalendarUrls,ae]}),className:`rounded-full px-3 py-2 text-sm transition ${st&&!Ie?"cursor-not-allowed bg-white/[0.05] text-white/35":ot?"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:st&&!Ie?"Always available for Forge writes":ot?"Mirrored into Forge":"Do not mirror"})})]},$e.url)})})}}],[F,he]);if(C.isLoading||N.isLoading||u.isLoading||M.isLoading)return e.jsx(xt,{eyebrow:"Settings · Calendar",title:"Loading calendar settings",description:"Checking the operator session and loading provider connections.",columns:2,blocks:6});if(C.isError)return e.jsx(Le,{eyebrow:"Settings · Calendar",error:C.error,onRetry:()=>void C.refetch()});if(N.isError||u.isError||M.isError||!((Ce=N.data)!=null&&Ce.settings)||!u.data||!M.data)return e.jsx(Le,{eyebrow:"Settings · Calendar",error:N.error??u.error??M.error??new Error("Calendar settings are unavailable."),onRetry:()=>{N.refetch(),u.refetch(),M.refetch()}});const{providers:W,connections:$}=u.data,k=N.data.settings.calendarProviders.microsoft;return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(Fe,{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(zs,{}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(Z,{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(_,{className:"bg-sky-400/12 text-sky-100",children:"Read only"}),k.isReadyForSignIn&&!le?e.jsxs(_,{className:"bg-emerald-500/16 text-emerald-100",children:[e.jsx(Qr,{className:"mr-1 size-3.5"}),"Ready for sign-in"]}):e.jsxs(_,{className:"bg-white/[0.08] text-white/74",children:[e.jsx(Ts,{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:O.clientId,onChange:J=>y(H=>({...H,clientId:J.target.value})),placeholder:"00000000-0000-0000-0000-000000000000"}),V.issues.clientId?e.jsx("span",{className:"text-sm text-rose-300",children:V.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:O.tenantId,onChange:J=>y(H=>({...H,tenantId:J.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(_,{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:O.redirectUri,onChange:J=>y(H=>({...H,redirectUri:J.target.value})),placeholder:"http://127.0.0.1:4317/api/v1/calendar/oauth/microsoft/callback"}),V.issues.redirectUri?e.jsx("span",{className:"text-sm text-rose-300",children:V.issues.redirectUri}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(K,{onClick:()=>void X.mutateAsync({clientId:O.clientId.trim(),tenantId:O.tenantId.trim()||"common",redirectUri:O.redirectUri.trim()}),disabled:!V.isValid,pending:X.isPending,pendingLabel:"Saving",children:"Save Microsoft settings"}),e.jsx(K,{variant:"secondary",onClick:()=>void G.mutateAsync(O),disabled:!V.isValid,pending:G.isPending,pendingLabel:"Testing",children:"Test Microsoft configuration"}),e.jsxs(K,{variant:"secondary",onClick:()=>{o("microsoft"),c("credentials"),i(!0)},disabled:ce,children:[e.jsx(da,{className:"size-4"}),"Sign in with Microsoft"]})]}),X.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:X.error.message}):null,G.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:G.data.result.message}):null,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]}),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:k.clientId||"Not saved yet"})]}),e.jsxs("div",{children:["Tenant:"," ",e.jsx("span",{className:"font-medium text-white",children:k.tenantId})]}),e.jsxs("div",{className:"break-all",children:["Redirect URI:"," ",e.jsx("span",{className:"font-medium text-white",children:k.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:le?"Save these Microsoft settings before you try to sign in, otherwise the popup will still use the previous saved configuration.":k.setupMessage})]})]})]}),e.jsxs(Z,{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(_,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[e.jsx(Ur,{className:"mr-1 size-3.5"}),"Settings-owned"]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:W.map(J=>e.jsxs("button",{type:"button",onClick:()=>{o(J.provider),c(J.provider==="microsoft"?"credentials":void 0),i(!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:J.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:J.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"})]},J.provider))})]}),e.jsxs(Z,{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:()=>T(J=>({...J,useCalendarColors:!J.useCalendarColors})),className:`rounded-full px-4 py-2 text-sm transition ${P.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:P.useCalendarColors?"Colors on":"Colors off"})]}),(((ie=M.data)==null?void 0:ie.calendars)??[]).length>0?e.jsx("div",{className:"grid gap-3",children:(((_e=M.data)==null?void 0:_e.calendars)??[]).map(J=>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:D[J.id]}}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate font-medium text-white",children:J.title}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[J.canWrite?"Writable":"Read only"," · ",J.timezone]})]})]})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{"aria-label":`Choose display color for ${J.title}`,type:"color",value:D[J.id],onChange:H=>T(pe=>({...pe,calendarColors:{...pe.calendarColors,[J.id]:H.target.value}})),className:"h-10 w-12 cursor-pointer rounded-[14px] border border-white/12 bg-transparent p-1"}),e.jsx(K,{size:"sm",variant:"secondary",onClick:()=>T(H=>{const pe={...H.calendarColors};return delete pe[J.id],{...H,calendarColors:pe}}),children:"Reset palette"})]})]},J.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(Z,{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(J=>{var pe;const H=z.get(J.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:J.label}),e.jsxs("div",{className:"mt-1 text-sm text-white/55",children:[Mr(J.provider)," · ",J.accountLabel||"No account label yet"]}),J.lastSyncedAt?e.jsxs("div",{className:"mt-2 text-sm text-white/48",children:["Last synced ",new Date(J.lastSyncedAt).toLocaleString()]}):null,J.lastSyncError?e.jsx("div",{className:"mt-2 text-sm text-rose-200",children:J.lastSyncError}):null]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_,{className:"bg-white/[0.08] text-white/74",children:J.status}),((pe=J.config)==null?void 0:pe.readOnly)===!0?e.jsx(_,{className:"bg-sky-400/12 text-sky-100",children:"Read only"}):null,e.jsxs(K,{size:"sm",variant:"secondary",pending:j.isPending&&j.variables===J.id,pendingLabel:"Syncing",onClick:()=>void j.mutateAsync(J.id),children:[e.jsx(ns,{className:"size-4"}),"Sync"]}),e.jsxs(K,{size:"sm",variant:"secondary",onClick:()=>{const Ie=(z.get(J.id)??[]).filter(Ye=>Ye.selectedForSync).map(Ye=>ss(Ye.remoteId));m(Ie),v(!0),p(J.id)},children:[e.jsx(Yl,{className:"size-4"}),"Manage mirrored calendars"]}),e.jsxs(K,{size:"sm",variant:"secondary",onClick:()=>h(J.id),children:[e.jsx(bt,{className:"size-4"}),"Remove"]})]})]}),e.jsx("div",{className:"mt-4 grid gap-2",children:H.map(Ie=>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:Ie.title}),e.jsxs("div",{className:"mt-1 text-xs uppercase tracking-[0.16em] text-white/45",children:[Ie.canWrite?"Writable":"Read only"," · ",Ie.timezone]})]}),Ie.forgeManaged?e.jsx(_,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"Forge"}):e.jsxs(_,{className:"bg-white/[0.08] text-white/74",children:[e.jsx(Ct,{className:"mr-1 size-3.5"}),"Mirrored"]})]},Ie.id))})]},J.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(Xu,{open:r,onOpenChange:J=>{i(J),J||c(void 0)},initialProvider:n,initialStepId:d,microsoftSetup:k,pending:I.isPending,onSubmit:async J=>{await I.mutateAsync(J)}}),e.jsx(He,{open:b!==null,onOpenChange:J=>{J||p(null)},eyebrow:"Calendar settings",title:"Manage mirrored calendars",description:"Choose which calendars this connection should mirror into Forge.",value:{selectedCalendarUrls:f},onChange:J=>m(J.selectedCalendarUrls),steps:je,pending:S.isPending,pendingLabel:"Saving",submitLabel:"Save mirror selection",error:S.error instanceof Error?S.error.message:null,onSubmit:async()=>{b&&(await S.mutateAsync({connectionId:b,patch:{selectedCalendarUrls:f.map(ss)}}),v(!1),p(null))}}),e.jsx(He,{open:w!==null,onOpenChange:J=>{J||h(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:q?`Remove ${q.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:q?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"font-medium text-white",children:[Mr(q.provider)," · ",q.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:E.isPending,pendingLabel:"Removing",submitLabel:"Remove connection",error:E.error instanceof Error?E.error.message:null,onSubmit:async()=>{w&&(await E.mutateAsync(w),h(null))}})]})}function Ju(t){return JSON.stringify(t,null,2)}function Er(t){const s=t.trim();if(!s)return{};const a=JSON.parse(s);if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Expected a JSON object.");return a}function Vu(){var M,A,I;const t=Xe(),s=Qe(),[a,r]=g.useState(""),[i,n]=g.useState(null),[o,d]=g.useState(null),c=oe({queryKey:["forge-operator-session"],queryFn:cs}),b=c.isSuccess,p=oe({queryKey:["forge-xp-metrics"],queryFn:co}),f=oe({queryKey:["forge-reward-rules"],queryFn:Xc,enabled:b}),m=oe({queryKey:["forge-reward-ledger"],queryFn:()=>Hc(30),enabled:b}),x=oe({queryKey:["forge-psyche-overview"],queryFn:async()=>(await ka()).overview}),v=la({defaultValues:{title:"",description:"",active:!0,configJson:"{}"}}),w=la({defaultValues:{entityType:"task",entityId:"",deltaXp:15,reasonTitle:"Operator bonus",reasonSummary:"Manual boost for a meaningful action captured with good provenance.",metadataJson:"{}"}}),h=async()=>{await Promise.all([s.invalidateQueries({queryKey:["forge-xp-metrics"]}),s.invalidateQueries({queryKey:["forge-reward-rules"]}),s.invalidateQueries({queryKey:["forge-reward-ledger"]})])},P=ue({mutationFn:j=>Gc(j.ruleId,{title:j.title,description:j.description,active:j.active,config:j.config}),onSuccess:h}),T=ue({mutationFn:Wc,onSuccess:h}),O=((M=f.data)==null?void 0:M.rules)??[],y=g.useMemo(()=>{var j,S,E,X,G,z;return{system:[{id:"operator_manual_reward",label:"Operator reward ledger"}],goal:t.snapshot.goals.map(D=>({id:D.id,label:D.title})),project:t.snapshot.dashboard.projects.map(D=>({id:D.id,label:D.title})),task:t.snapshot.tasks.map(D=>({id:D.id,label:D.title})),habit:t.snapshot.habits.map(D=>({id:D.id,label:D.title})),tag:t.snapshot.tags.map(D=>({id:D.id,label:D.name})),note:[],insight:[],psyche_value:(((j=x.data)==null?void 0:j.values)??[]).map(D=>({id:D.id,label:D.title})),behavior_pattern:(((S=x.data)==null?void 0:S.patterns)??[]).map(D=>({id:D.id,label:D.title})),behavior:(((E=x.data)==null?void 0:E.behaviors)??[]).map(D=>({id:D.id,label:D.title})),belief_entry:(((X=x.data)==null?void 0:X.beliefs)??[]).map(D=>({id:D.id,label:D.statement})),mode_profile:(((G=x.data)==null?void 0:G.modes)??[]).map(D=>({id:D.id,label:D.title})),trigger_report:(((z=x.data)==null?void 0:z.reports)??[]).map(D=>({id:D.id,label:D.title}))}},[x.data,t.snapshot.dashboard.projects,t.snapshot.goals,t.snapshot.habits,t.snapshot.tags,t.snapshot.tasks]);g.useEffect(()=>{var X;const j=w.getValues("entityType"),S=w.getValues("entityId"),E=y[j]??[];S&&E.some(G=>G.id===S)||w.setValue("entityId",((X=E[0])==null?void 0:X.id)??"")},[w,y]),g.useEffect(()=>{O.length&&(!a||!O.some(j=>j.id===a))&&r(O[0].id)},[O,a]);const C=O.find(j=>j.id===a)??O[0]??null;g.useEffect(()=>{C&&(v.reset({title:C.title,description:C.description,active:C.active,configJson:Ju(C.config)}),n(null))},[C,v]);const l=(A=p.data)==null?void 0:A.metrics,u=(((I=m.data)==null?void 0:I.ledger)??[]).filter(j=>j.metadata.manual===!0).slice(0,8);return c.isLoading?e.jsx(xt,{eyebrow:"Settings · Rewards",title:"Loading reward controls",description:"Establishing the operator session and fetching reward configuration.",columns:2,blocks:6}):c.isError?e.jsx(Le,{eyebrow:"Settings · Rewards",error:c.error,onRetry:()=>void c.refetch()}):e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(Fe,{title:"Rewards",description:"XP command deck, reward rule editor, manual bonus grants, and ledger history."}),e.jsx(zs,{}),e.jsx("div",{className:"grid gap-5",children:e.jsxs(Z,{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:[l?e.jsx(zo,{profile:l.profile,achievements:l.achievements,milestoneRewards:l.milestoneRewards,momentumPulse:l.momentumPulse,recentLedger:l.recentLedger}):null,l?e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(Dt,{label:"Total XP",value:l.profile.totalXp,tone:"core"}),e.jsx(Dt,{label:"Daily ambient",value:`${l.dailyAmbientXp} / ${l.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"}),O.length>0?e.jsxs("form",{className:"mt-4 grid gap-4",onSubmit:v.handleSubmit(async j=>{try{n(null);const S=Er(j.configJson);if(!C)return;await P.mutateAsync({ruleId:C.id,title:j.title,description:j.description,active:j.active,config:S})}catch(S){n(S instanceof Error?S.message:"Invalid reward rule config.")}}),children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Rule"}),e.jsx("select",{className:"rounded-[14px] bg-white/[0.06] px-3 py-3 text-white",value:a,onChange:j=>r(j.target.value),children:O.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(se,{...v.register("title")})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Description"}),e.jsx(ve,{className:"min-h-24",...v.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",...v.register("active")})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Config JSON"}),e.jsx(ve,{className:"min-h-28 font-mono text-xs",...v.register("configJson")})]}),i?e.jsx("div",{className:"text-sm text-amber-300",children:i}):null,e.jsx(K,{type:"submit",pending:P.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 S=Er(j.metadataJson);await T.mutateAsync({entityType:j.entityType,entityId:j.entityId,deltaXp:j.deltaXp,reasonTitle:j.reasonTitle,reasonSummary:j.reasonSummary,metadata:S}),w.reset({...j,entityId:"",reasonTitle:"Operator bonus",reasonSummary:"Manual boost for a meaningful action captured with good provenance.",metadataJson:"{}"})}catch(S){d(S instanceof Error?S.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(y).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:(y[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(se,{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(se,{...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(ve,{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(ve,{className:"min-h-24 font-mono text-xs",...w.register("metadataJson")})]}),o?e.jsx("div",{className:"text-sm text-amber-300",children:o}):null,e.jsx(K,{type:"submit",pending:T.isPending,pendingLabel:"Issuing bonus",children:"Issue bonus XP"})]}),T.data?e.jsxs("div",{className:"mt-4 rounded-[18px] bg-[rgba(192,193,255,0.12)] p-4 text-sm text-white",children:["Granted ",T.data.reward.deltaXp>0?"+":"",T.data.reward.deltaXp," XP for ",e.jsx("strong",{children:T.data.reward.reasonTitle}),"."]}):null]})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:"Manual bonus history"}),e.jsx("div",{className:"mt-4 grid gap-3",children:u.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."}):u.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(_,{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))})]})]})]})})]})}function as({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(Oe,{content:s,label:`Explain ${t}`}):null]})}const bs=[{status:"backlog",label:"Backlog",description:"Not started yet.",icon:ds},{status:"focus",label:"Focus",description:"Ready to start soon.",icon:ga},{status:"in_progress",label:"In progress",description:"Work is active now.",icon:Et},{status:"blocked",label:"Blocked",description:"Something is stopping progress.",icon:zr},{status:"done",label:"Done",description:"The task is completed.",icon:ui}];function Zu(){var X,G;const{t,formatDate:s,formatDateTime:a}=qe(),r=Xe(),i=fa(),n=Qe(),[o,d]=g.useState(!1),[c,b]=g.useState(!1),[p,f]=g.useState(!1),[m,x]=g.useState(()=>typeof window<"u"?window.matchMedia("(max-width: 1023px)").matches:!1),[v]=g.useState(()=>{const z=new Date,D=new Date(z);D.setHours(0,0,0,0);const F=new Date(z);return F.setHours(23,59,59,999),{from:D.toISOString(),to:F.toISOString()}});g.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const z=window.matchMedia("(max-width: 1023px)"),D=F=>x(F?F.matches:z.matches);return D(),typeof z.addEventListener=="function"?(z.addEventListener("change",D),()=>z.removeEventListener("change",D)):(z.addListener(D),()=>z.removeListener(D))},[]);const w=oe({queryKey:["task-context",i.taskId],queryFn:()=>sm(i.taskId),enabled:!!i.taskId}),h=oe({queryKey:["task-calendar-overview",i.taskId,v.from,v.to],queryFn:()=>Sa(v),enabled:!!i.taskId}),P=async()=>{await Promise.all([n.invalidateQueries({queryKey:["forge-snapshot"]}),n.invalidateQueries({queryKey:["task-context",i.taskId]}),n.invalidateQueries({queryKey:["activity-archive"]}),n.invalidateQueries({queryKey:["project-board"]}),n.invalidateQueries({queryKey:["forge-xp-metrics"]}),n.invalidateQueries({queryKey:["forge-reward-ledger"]}),n.invalidateQueries({queryKey:["forge-operator-context"]})])},T=ue({mutationFn:({taskId:z,patch:D})=>Os(z,D),onSuccess:P}),O=ue({mutationFn:z=>Si(z),onSuccess:P}),y=ue({mutationFn:z=>go(z),onSuccess:P}),C=ue({mutationFn:({runId:z,actor:D,note:F})=>bo(z,{actor:D,note:F??""}),onSuccess:P}),l=ue({mutationFn:({runId:z,actor:D,note:F})=>fo(z,{actor:D,note:F??""}),onSuccess:P}),N=ue({mutationFn:xo,onSuccess:P}),u=w.data;if(w.isLoading)return e.jsx(xt,{});if(w.isError)return e.jsx(Le,{eyebrow:t("common.taskDetail.errorEyebrow"),error:w.error,onRetry:()=>void w.refetch()});if(!u)return e.jsx(Le,{eyebrow:t("common.taskDetail.errorEyebrow"),error:new Error(t("common.taskDetail.emptyPayload")),onRetry:()=>void w.refetch()});const M=u.activeTaskRun??null,A=bs.find(z=>z.status===u.task.status)??bs[0];bs.filter(z=>z.status!==u.task.status);const I=Ih(u.task,(X=u.project)==null?void 0:X.schedulingRules),j=Uo({rules:I,overview:(G=h.data)==null?void 0:G.calendar}),S=z=>{switch(z){case"active":return"Active";case"completed":return"Completed";case"released":return"Paused";case"timed_out":return"Timed out";default:return z}},E=async z=>{await T.mutateAsync({taskId:u.task.id,patch:{status:z}}),f(!1)};return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Fe,{entityKind:"task",title:e.jsx(Te,{kind:"task",label:u.task.title,variant:"heading",size:"lg",lines:3,className:"max-w-full",labelClassName:"[overflow-wrap:anywhere]"}),titleText:u.task.title,description:u.task.description?e.jsx(mt,{markdown:u.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:`${u.task.points} xp`}),e.jsxs(Z,{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(Te,{kind:"task",label:u.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:u.task.description?e.jsx(mt,{markdown:u.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(K,{pending:w.isFetching,pendingLabel:M?"Opening":"Starting",onClick:async()=>{await r.startTaskNow(u.task.id),await P()},children:[e.jsx(Et,{className:"size-4 fill-current"}),M?"Focus work":"Start work"]}),M?e.jsxs(e.Fragment,{children:[e.jsx(K,{variant:"secondary",pending:C.isPending,pendingLabel:"Pausing",onClick:async()=>{await C.mutateAsync({runId:M.id,actor:M.actor,note:M.note})},children:"Pause"}),e.jsx(K,{variant:"secondary",pending:l.isPending,pendingLabel:"Completing",onClick:async()=>{await l.mutateAsync({runId:M.id,actor:M.actor,note:M.note})},children:"Complete"})]}):null,e.jsxs(K,{variant:"secondary",onClick:()=>b(!0),children:[e.jsx(ds,{className:"size-4"}),"Adjust work"]}),m?e.jsxs(e.Fragment,{children:[e.jsx(K,{variant:"secondary",size:"sm","aria-label":"Change task status",onClick:()=>f(!0),children:e.jsx(A.icon,{className:"size-4"})}),e.jsx(K,{variant:"secondary",size:"sm","aria-label":"Edit task",onClick:()=>d(!0),children:e.jsx(Ss,{className:"size-4"})})]}):e.jsxs(K,{variant:"secondary",onClick:()=>d(!0),children:[e.jsx(Ss,{className:"size-4"}),"Edit task"]}),u.task.status==="done"?e.jsx(K,{variant:"secondary",onClick:async()=>{await O.mutateAsync(u.task.id)},children:"Mark as not done"}):null]})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap gap-2",children:[e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:A.label}),e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:t(`common.enums.priority.${u.task.priority}`)}),e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:t(`common.enums.effort.${u.task.effort}`)}),e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:t(`common.enums.energy.${u.task.energy}`)}),e.jsxs(_,{className:"bg-white/[0.08] text-white/72",children:[u.task.points," xp"]}),u.task.time.totalCreditedSeconds>0?e.jsxs(_,{className:"bg-white/[0.08] text-white/72",children:[Math.floor(u.task.time.totalCreditedSeconds/60)," min tracked"]}):null,M?e.jsx(_,{className:"bg-emerald-500/12 text-emerald-200",children:"Timer active"}):null]}),m?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:bs.map(z=>{const D=z.icon,F=z.status===u.task.status;return e.jsxs("button",{type:"button",disabled:F||T.isPending,className:`rounded-[18px] border px-3.5 py-3 text-left transition ${F?"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 E(z.status),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(D,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"font-medium",children:z.label})]}),e.jsx("div",{className:"mt-2 text-xs leading-5 text-white/54",children:z.description})]},z.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(as,{label:"Project",help:"The project is the main work stream this task belongs to."}),e.jsx("div",{className:"mt-2",children:u.project?e.jsx(Ne,{to:`/projects/${u.project.id}`,className:"inline-flex max-w-full",children:e.jsx(xe,{kind:"project",label:u.project.title,compact:!0,gradient:!1,wrap:!0,className:"max-w-full"})}):e.jsx(_,{className:"bg-white/[0.08] text-white/65",children:"No project linked"})})]}),e.jsxs("div",{children:[e.jsx(as,{label:"Goal",help:"The goal shows the longer-term result this task supports."}),e.jsx("div",{className:"mt-2",children:u.goal?e.jsx(Ne,{to:`/goals/${u.goal.id}`,className:"inline-flex max-w-full",children:e.jsx(xe,{kind:"goal",label:u.goal.title,compact:!0,gradient:!1,wrap:!0,className:"max-w-full"})}):e.jsx(_,{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(as,{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(u.task.dueDate)})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(as,{label:"Owner",help:"The owner is the person or role expected to carry this task."}),e.jsx("div",{className:"mt-2 text-white",children:u.task.owner})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(as,{label:"Created"}),e.jsx("div",{className:"mt-2 text-white",children:a(u.task.createdAt)})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(as,{label:"Updated"}),e.jsx("div",{className:"mt-2 text-white",children:a(u.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(Oe,{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:M?`${M.timerMode==="planned"?"Planned":"Unlimited"} timer active with ${Math.floor(M.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(Ti,{title:"Task scheduling",subtitle:"Set when this task can run. If you leave it empty, the project defaults stay in force.",initialRules:u.task.schedulingRules,initialPlannedDurationSeconds:u.task.plannedDurationSeconds,allowPlannedDuration:!0,saveLabel:"Save task scheduling",onSave:async({schedulingRules:z,plannedDurationSeconds:D})=>{await T.mutateAsync({taskId:u.task.id,patch:{schedulingRules:z,plannedDurationSeconds:D}}),await n.invalidateQueries({queryKey:["task-calendar-overview",i.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(_,{className:j.tone==="blocked"?"bg-rose-500/14 text-rose-100":j.tone==="waiting"?"bg-amber-500/14 text-amber-100":"bg-emerald-500/14 text-emerald-100",children:j.label}),e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:u.task.schedulingRules?"Task override":"Using project defaults"}),u.task.plannedDurationSeconds?e.jsxs(_,{className:"bg-white/[0.08] text-white/72",children:[Math.round(u.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."}),j.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:j.context.map(z=>e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:z},z))})]}):null,j.conflicts.length>0?e.jsx("div",{className:"mt-4 grid gap-2",children:j.conflicts.map(z=>e.jsx("div",{className:"rounded-[16px] bg-rose-500/10 px-3 py-2 text-sm text-rose-100",children:z},z))}):null,e.jsx("div",{className:"mt-4",children:e.jsx(Ne,{to:"/calendar",children:e.jsx(K,{variant:"secondary",children:"Open calendar workspace"})})})]})]}),e.jsx("div",{className:"mt-5",children:e.jsx(Ia,{entityType:"task",entityId:u.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",i.taskId],...u.task.projectId?[["project-board",u.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:[u.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,u.activity.map(z=>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:Pa(z)}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:Ma(z)}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.16em] text-white/35",children:a(z.createdAt)})]}),e.jsx(K,{variant:"ghost",className:"shrink-0",onClick:async()=>{await y.mutateAsync(z.id)},children:"Remove"})]}),Rt(z)&&ha(z)?e.jsx(Ne,{to:Rt(z),className:"mt-3 inline-flex text-[11px] uppercase tracking-[0.16em] text-[var(--primary)]",children:ha(z)}):null]},z.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:[u.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,u.taskRuns.map(z=>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:z.actor}),e.jsx(_,{children:S(z.status)})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:z.note||t("common.labels.noRunNote")}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.16em] text-white/35",children:a(z.updatedAt)})]},z.id))]})]})]}),e.jsx(wa,{open:o,goals:r.snapshot.goals,projects:r.snapshot.dashboard.projects,tags:r.snapshot.tags,editingTask:u.task,onOpenChange:d,onSubmit:async(z,D)=>{D&&await T.mutateAsync({taskId:D,patch:z})}}),e.jsx(qo,{open:c,onOpenChange:b,entityType:"task",entityId:u.task.id,targetLabel:u.task.title,currentCreditedSeconds:u.task.time.totalCreditedSeconds,pending:N.isPending,onSubmit:async z=>{await N.mutateAsync(z)}}),e.jsx(ya,{open:p,onOpenChange:f,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:bs.map(z=>{const D=z.icon,F=z.status===u.task.status;return e.jsx("button",{type:"button",disabled:F||T.isPending,className:`rounded-[22px] border px-4 py-4 text-left transition ${F?"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 E(z.status),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(D,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:z.label}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:z.description})]})]})},z.status)})})})]})}function Lr(t,s,a){var r;return((r=s.find(i=>i.id===t.goalId))==null?void 0:r.title)??a}function ep(t,s){return t.tagIds.map(a=>s.find(r=>r.id===a)).filter(Boolean)}function tp(t,s){(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),s())}function sp(t,s){switch(t.status){case"backlog":return{label:s.backlog,action:"start",icon:Et};case"focus":return{label:s.focus,action:"start",icon:Et};case"in_progress":return{label:s.in_progress,nextStatus:"done",action:"move",icon:ui};case"blocked":return{label:s.blocked,action:"start",icon:Et};default:return null}}function ap({tasks:t,timeline:s,goals:a,tags:r,notesSummaryByEntity:i,selectedTaskId:n,onSelectTask:o,onMove:d,onStartTask:c}){const{t:b,formatDate:p}=qe(),f={backlog:b("common.dailyRunway.actionBacklog"),focus:b("common.dailyRunway.actionFocus"),in_progress:b("common.dailyRunway.actionProgress"),blocked:b("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:b("common.dailyRunway.runwayEyebrow")}),e.jsx(Oe,{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:b("common.dailyRunway.runwayTitle")})]}),e.jsx(_,{className:"shrink-0 text-[var(--primary)]",children:b(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,x)=>{const v=sp(m,f),w=ep(m,r).slice(0,2),h=n===m.id,P=at(i,"task",m.id).count;return e.jsxs("article",{role:"button",tabIndex:0,"aria-pressed":h,className:`grid w-full gap-3 rounded-[22px] px-4 py-4 text-left transition ${h?"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:()=>o(m.id),onKeyDown:T=>tp(T,()=>o(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:b("common.dailyRunway.runwayItem",{index:x+1})}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(xe,{kind:"goal",label:Lr(m,a,b("common.dailyRunway.unassigned")),compact:!0,gradient:!1}),m.time.activeRunCount>0?e.jsx(_,{className:"bg-emerald-500/12 text-emerald-200",children:"Live"}):null]}),e.jsx("div",{className:"mt-2",children:e.jsx(Te,{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||b("common.dailyRunway.noNote")})]}),e.jsx(_,{className:"shrink-0 self-start",children:m.status.replaceAll("_"," ")})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(_,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[m.points," xp"]}),e.jsx(Ze,{entityType:"task",entityId:m.id,count:P}),m.time.totalCreditedSeconds>0?e.jsxs(_,{className:"bg-white/[0.08] text-white/70",children:[Math.floor(m.time.totalCreditedSeconds/60)," min tracked"]}):null,e.jsx(_,{className:"bg-white/[0.08] text-white/70",children:m.effort}),e.jsx(_,{className:"bg-white/[0.08] text-white/70",children:p(m.dueDate)}),w.map(T=>e.jsx(_,{className:"bg-white/[0.08]",style:{color:T.color},children:T.name},T.id))]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:m.owner}),v?e.jsxs(K,{variant:v.action==="start"?"primary":"secondary",className:"px-3 py-2 text-[11px] uppercase tracking-[0.16em]",onClick:async T=>{if(T.stopPropagation(),v.action==="start"){await c(m.id);return}v.nextStatus&&await d(m.id,v.nextStatus)},children:[e.jsx(v.icon,{className:"mr-2 size-3.5"}),v.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:b("common.dailyRunway.timelineEyebrow")}),e.jsx(Oe,{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:b("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(_,{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(x=>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:()=>o(x.id),children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx(Te,{kind:"task",label:x.title,className:"max-w-full",labelClassName:"[overflow-wrap:anywhere]"}),e.jsx("div",{className:"mt-2",children:e.jsx(xe,{kind:"goal",label:Lr(x,a,b("common.dailyRunway.unassigned")),compact:!0,gradient:!1})})]}),e.jsx(Jt,{className:"size-4 shrink-0 text-white/35"})]},x.id)),m.tasks.length===0?e.jsx("div",{className:"text-sm text-white/42",children:b("common.dailyRunway.emptyBucket")}):null]})]},m.id))})]})]})}const si=5;function ip(){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 np(t,s){const a=new Date(t.startAt),r=new Date(t.endAt);return a<s.end&&r>s.start}function rp(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 op(){var T,O;const{t}=qe(),s=Xe(),a=ht(),r=g.useMemo(()=>ip(),[]),i=oe({queryKey:["forge-calendar-overview",r.from,r.to],queryFn:()=>Sa({from:r.from,to:r.to})}),n=s.snapshot.today.directive.task,o=s.snapshot.today.milestoneRewards.find(y=>!y.completed)??s.snapshot.today.milestoneRewards[0]??null,d=s.snapshot.risk.blockedTasks[0]??s.snapshot.risk.overdueTasks[0]??null,c=Math.max(0,s.snapshot.metrics.nextLevelXp-s.snapshot.metrics.currentLevelXp),b=8,p=4,f=10,m=20,x=g.useMemo(()=>{var y;return(((y=i.data)==null?void 0:y.calendar.events)??[]).filter(C=>!C.deletedAt&&C.status!=="cancelled"&&np(C,r)).sort((C,l)=>new Date(C.startAt).getTime()-new Date(l.startAt).getTime())},[(T=i.data)==null?void 0:T.calendar.events,r]),v=x.slice(0,si),w=x.length>0,h=g.useMemo(()=>new Intl.DateTimeFormat(void 0,{weekday:"short",month:"short",day:"numeric"}).format(r.start),[r.start]);return!(n!==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||w)&&!i.isLoading?e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Fe,{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(rt,{eyebrow:t("common.todayPage.heroEyebrow"),title:t("common.todayPage.emptyTitle"),description:t("common.todayPage.emptyDescription"),action:e.jsx(Ne,{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(Fe,{title:"Today",titleText:"Today",description:(n==null?void 0:n.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(Z,{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(Oe,{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(Z,{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(Oe,{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:[c," xp to next level"]}),e.jsx("div",{className:"mt-3",children:e.jsx(_t,{value:s.snapshot.metrics.currentLevelXp/s.snapshot.metrics.nextLevelXp*100,tone:"tertiary"})})]}),e.jsxs(Z,{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(Oe,{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(Z,{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(Oe,{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(_,{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.jsxs("span",{children:["Every ",f," min"]}),e.jsxs(_,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:["+",p," 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(_,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:["+",m," 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(_,{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(ap,{tasks:s.snapshot.overview.topTasks,timeline:s.snapshot.today.timeline,goals:s.snapshot.goals,tags:s.snapshot.tags,notesSummaryByEntity:s.snapshot.dashboard.notesSummaryByEntity,selectedTaskId:(n==null?void 0:n.id)??null,onSelectTask:y=>a(`/tasks/${y}`),onStartTask:async y=>{await s.startTaskNow(y)},onMove:async(y,C)=>{await s.patchTaskStatus(y,C)}})}),e.jsxs("div",{className:"grid min-w-0 gap-5",children:[w?e.jsxs(Z,{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(Oe,{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(Ct,{className:"size-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:h}),e.jsxs("div",{className:"text-sm text-white/58",children:[x.length," event",x.length===1?"":"s"," scheduled"]})]})]}),e.jsxs(Ne,{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(yn,{className:"size-3.5"})]})]}),e.jsxs("div",{className:"mt-4 grid gap-2.5",children:[v.map(y=>e.jsxs("button",{type:"button",className:"grid min-w-0 gap-2 rounded-[18px] bg-white/[0.04] px-3 py-3 text-left transition hover:bg-white/[0.07]",onClick:()=>a("/calendar"),children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white",children:y.title}),e.jsx("div",{className:"mt-1 text-sm text-white/58",children:rp(y)})]}),e.jsx(_,{className:"shrink-0 bg-white/[0.08] text-white/72",children:y.originType==="native"?"Forge":y.originType})]}),y.description?e.jsx("div",{className:"line-clamp-2 text-sm leading-6 text-white/52",children:y.description}):null]},y.id)),x.length>si?e.jsxs(Ne,{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 ",x.length-si," more events in Calendar"]}),e.jsx(yn,{className:"size-4"})]}):null]})]}):null,e.jsxs(Z,{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(Oe,{content:"This is the task Forge currently considers the best anchor for today."})]}),n?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:()=>a(`/tasks/${n.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:n.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:n.description||"No description yet."})]}),e.jsxs(_,{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(_,{className:"bg-white/[0.08] text-white/72",children:s.snapshot.today.directive.goalTitle}):null,e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:s.snapshot.today.directive.sessionLabel}),e.jsx(Ze,{entityType:"task",entityId:n.id,count:((O=s.snapshot.dashboard.notesSummaryByEntity[`task:${n.id}`])==null?void 0:O.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(Z,{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(Oe,{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(y=>{var C;return e.jsxs(Ne,{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:y.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:y.description||"Recurring operating commitment."})]}),e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:y.polarity})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(_,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:["+",y.rewardXp," xp aligned"]}),e.jsxs(_,{className:"bg-white/[0.08] text-white/72",children:["Streak ",y.streakCount]}),e.jsx(Ze,{entityType:"habit",entityId:y.id,count:((C=s.snapshot.dashboard.notesSummaryByEntity[`habit:${y.id}`])==null?void 0:C.count)??0})]})]},y.id)})})]}),e.jsxs(Z,{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(Oe,{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(y=>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:y.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:y.summary})]}),e.jsxs(_,{className:`shrink-0 self-start ${y.completed?"text-emerald-300":"text-[var(--tertiary)]"}`,children:["+",y.rewardXp," xp"]})]}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.16em] text-white/38",children:y.progressLabel})]},y.id))})]}),e.jsxs(Z,{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(Oe,{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(y=>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:y.title}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:y.summary})]}),e.jsx(_,{className:"max-w-[10.5rem] shrink-0 self-start",children:y.rewardLabel})]}),e.jsx("div",{className:"mt-4",children:e.jsx(_t,{value:y.current/y.target*100,tone:"tertiary"})}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.16em] text-white/38",children:y.progressLabel})]},y.id))})]}),e.jsxs(Z,{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(Oe,{content:"This highlights the blocked or overdue task most likely to slow you down if ignored."})]}),d?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:()=>a(`/tasks/${d.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:d.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:d.description||s.snapshot.today.momentum.recoveryHint})]}),e.jsx(_,{className:"bg-white/[0.08] text-white/72",children:d.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}),o?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:o.title}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:o.progressLabel})]}):null]})]})]})]})}function lp(){var b;const{t}=qe(),s=Qe(),a=oe({queryKey:["forge-weekly-review"],queryFn:uc}),r=ue({mutationFn:pc,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"]})])}}),i=(b=a.data)==null?void 0:b.review;if(a.isLoading)return e.jsx(xt,{});if(a.isError)return e.jsx(Le,{eyebrow:t("common.weeklyReview.heroEyebrow"),error:a.error,onRetry:()=>void a.refetch()});if(!i)return e.jsx(Le,{eyebrow:t("common.weeklyReview.heroEyebrow"),error:new Error("Forge returned an empty weekly review payload."),onRetry:()=>void a.refetch()});const n=i.wins[0]??null,o=i.calibration.find(p=>p.mode==="recover")??i.calibration[0]??null,d=i.calibration.find(p=>p.mode==="accelerate")??i.calibration[0]??null,c=[{id:"week",label:"This week",title:`${i.momentumSummary.totalXp} XP with ${i.momentumSummary.focusHours} focus hours`,detail:`Peak window: ${i.momentumSummary.peakWindow}. Efficiency score is holding at ${i.momentumSummary.efficiencyScore}.`,badge:i.windowLabel},{id:"wins",label:"Wins",title:(n==null?void 0:n.title)??t("common.weeklyReview.noWin"),detail:(n==null?void 0:n.summary)??t("common.weeklyReview.noWinDetail"),badge:n?`+${n.rewardXp} xp`:`${i.wins.length} wins`},{id:"recovery",label:"Recovery",title:(o==null?void 0:o.title)??t("common.weeklyReview.noRecovery"),detail:(o==null?void 0:o.note)??t("common.weeklyReview.noRecoveryDetail"),badge:(o==null?void 0:o.mode)??"maintain"},{id:"next-intent",label:"Next intent",title:(d==null?void 0:d.title)??i.reward.title,detail:(d==null?void 0:d.note)??i.reward.summary,badge:`+${i.reward.rewardXp} xp`}];return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Fe,{title:"Weekly Review",description:`${i.windowLabel}. ${t("common.weeklyReview.heroDescription")}`,badge:`${i.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(Z,{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(Xr,{width:"100%",height:"100%",children:e.jsxs(ld,{data:i.chart,children:[e.jsx(Gr,{dataKey:"label",tick:{fill:"rgba(255,255,255,0.42)",fontSize:11}}),e.jsx(Wr,{hide:!0}),e.jsx(dd,{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:i.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:i.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:i.momentumSummary.peakWindow})]})]})]}),e.jsxs(Z,{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:i.calibration.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.jsx("div",{className:"min-w-0 flex-1 font-medium text-white",children:p.title}),e.jsx(_,{className:"max-w-[9rem] shrink-0 self-start",children:p.mode})]}),e.jsx("div",{className:"mt-3 text-sm text-white/58",children:p.note})]},p.id))})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(Z,{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:i.wins.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.jsx("div",{className:"min-w-0 flex-1 font-medium text-white",children:p.title}),e.jsxs(_,{className:"max-w-[8rem] shrink-0 self-start text-emerald-300",children:["+",p.rewardXp," xp"]})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:p.summary})]},p.id))})]}),e.jsxs(Z,{children:[e.jsx("h2",{className:"font-display text-3xl text-white",children:i.reward.title}),e.jsx("p",{className:"mt-3 text-sm leading-7 text-white/60",children:i.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:["+",i.reward.rewardXp," XP"]})]}),e.jsx(K,{className:"mt-4 w-full",disabled:i.completion.finalized,pending:r.isPending,pendingLabel:t("common.weeklyReview.finalizePending"),onClick:async()=>{await r.mutateAsync()},children:i.completion.finalized?t("common.weeklyReview.finalized"):t("common.weeklyReview.finalize")}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:i.completion.finalized?`${t("common.weeklyReview.finalizedDetail")} ${i.completion.finalizedBy?`By ${i.completion.finalizedBy}. `:""}${i.completion.finalizedAt?new Date(i.completion.finalizedAt).toLocaleString():""}`.trim():i.reward.summary})]})]})]}),e.jsx(Bo,{eyebrow:t("common.weeklyReview.summaryEyebrow"),title:t("common.weeklyReview.summaryTitle"),description:t("common.weeklyReview.summaryDescription"),items:c})]})}function dp(){return e.jsxs(Jl,{children:[e.jsxs(Ee,{element:e.jsx(pm,{}),children:[e.jsx(Ee,{index:!0,element:e.jsx(La,{to:"/overview",replace:!0})}),e.jsx(Ee,{path:"overview",element:e.jsx(kh,{})}),e.jsx(Ee,{path:"goals",element:e.jsx(Bm,{})}),e.jsx(Ee,{path:"habits",element:e.jsx(Xm,{})}),e.jsx(Ee,{path:"goals/:goalId",element:e.jsx(_m,{})}),e.jsx(Ee,{path:"projects",element:e.jsx(Fh,{})}),e.jsx(Ee,{path:"projects/:projectId",element:e.jsx(Mh,{})}),e.jsx(Ee,{path:"campaigns",element:e.jsx(La,{to:"/projects",replace:!0})}),e.jsx(Ee,{path:"calendar",element:e.jsx(Mm,{})}),e.jsx(Ee,{path:"psyche",element:e.jsx(Xh,{})}),e.jsx(Ee,{path:"psyche/values",element:e.jsx(Eu,{})}),e.jsx(Ee,{path:"psyche/patterns",element:e.jsx(vu,{})}),e.jsx(Ee,{path:"psyche/behaviors",element:e.jsx(nu,{})}),e.jsx(Ee,{path:"psyche/reports",element:e.jsx(Pu,{})}),e.jsx(Ee,{path:"psyche/reports/:reportId",element:e.jsx(Iu,{})}),e.jsx(Ee,{path:"psyche/goal-map",element:e.jsx(ru,{})}),e.jsx(Ee,{path:"psyche/schemas-beliefs",element:e.jsx(Au,{})}),e.jsx(Ee,{path:"psyche/modes",element:e.jsx(pu,{})}),e.jsx(Ee,{path:"psyche/modes/guide",element:e.jsx(cu,{})}),e.jsx(Ee,{path:"kanban",element:e.jsx(hh,{})}),e.jsx(Ee,{path:"notes",element:e.jsx(yh,{})}),e.jsx(Ee,{path:"today",element:e.jsx(op,{})}),e.jsx(Ee,{path:"activity",element:e.jsx(fm,{})}),e.jsx(Ee,{path:"insights",element:e.jsx(oh,{})}),e.jsx(Ee,{path:"review/weekly",element:e.jsx(lp,{})}),e.jsx(Ee,{path:"settings",element:e.jsx(Lu,{})}),e.jsx(Ee,{path:"settings/calendar",element:e.jsx(Yu,{})}),e.jsx(Ee,{path:"settings/agents",element:e.jsx($u,{})}),e.jsx(Ee,{path:"settings/rewards",element:e.jsx(Vu,{})}),e.jsx(Ee,{path:"settings/bin",element:e.jsx(qu,{})}),e.jsx(Ee,{path:"tasks/:taskId",element:e.jsx(Zu,{})})]}),e.jsx(Ee,{path:"*",element:e.jsx(La,{to:"/overview",replace:!0})})]})}const cp=new Vl({defaultOptions:{queries:{staleTime:2e4,refetchOnWindowFocus:!1}}});Zl.createRoot(document.getElementById("root")).render(e.jsx(ed.StrictMode,{children:e.jsx(td,{client:cp,children:e.jsx(sd,{basename:Wd("/forge/"),children:e.jsx(dp,{})})})}));
36
+ //# sourceMappingURL=index-Cj1IBH_w.js.map