forge-openclaw-plugin 0.2.25 → 0.2.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +59 -3
- package/dist/assets/{board-VmF4FAfr.js → board-C6jCchjI.js} +3 -3
- package/dist/assets/{board-VmF4FAfr.js.map → board-C6jCchjI.js.map} +1 -1
- package/dist/assets/index-DVvS8iiU.css +1 -0
- package/dist/assets/index-zYB-9Dfo.js +85 -0
- package/dist/assets/index-zYB-9Dfo.js.map +1 -0
- package/dist/assets/knowledge-graph-layout.worker-DRvzPxhP.js +2 -0
- package/dist/assets/knowledge-graph-layout.worker-DRvzPxhP.js.map +1 -0
- package/dist/assets/{motion-DvkU14p-.js → motion-DFHrH2rd.js} +2 -2
- package/dist/assets/{motion-DvkU14p-.js.map → motion-DFHrH2rd.js.map} +1 -1
- package/dist/assets/{table-DgiPof9E.js → table-ZL7Di_u3.js} +2 -2
- package/dist/assets/{table-DgiPof9E.js.map → table-ZL7Di_u3.js.map} +1 -1
- package/dist/assets/{ui-nYfoC0Gq.js → ui-CKNPpz7q.js} +2 -2
- package/dist/assets/{ui-nYfoC0Gq.js.map → ui-CKNPpz7q.js.map} +1 -1
- package/dist/assets/vendor-DoNZuFhn.js +1247 -0
- package/dist/assets/vendor-DoNZuFhn.js.map +1 -0
- package/dist/index.html +7 -8
- package/dist/openclaw/local-runtime.d.ts +3 -1
- package/dist/openclaw/local-runtime.js +67 -15
- package/dist/openclaw/plugin-entry-shared.js +24 -2
- package/dist/openclaw/plugin-sdk-types.d.ts +17 -0
- package/dist/openclaw/routes.d.ts +27 -0
- package/dist/openclaw/routes.js +16 -12
- package/dist/openclaw/tools.js +0 -3
- package/dist/server/server/migrations/001_core.sql +411 -0
- package/dist/server/server/migrations/002_psyche.sql +392 -0
- package/dist/server/server/migrations/003_habits.sql +30 -0
- package/dist/server/server/migrations/004_habit_links.sql +8 -0
- package/dist/server/server/migrations/005_habit_psyche_links.sql +24 -0
- package/dist/server/server/migrations/006_work_adjustments.sql +14 -0
- package/dist/server/server/migrations/007_weekly_review_closures.sql +17 -0
- package/dist/server/server/migrations/008_calendar_execution.sql +147 -0
- package/dist/server/server/migrations/009_true_calendar_events.sql +195 -0
- package/dist/server/server/migrations/010_calendar_selection_state.sql +6 -0
- package/dist/server/server/migrations/011_calendar_timezone_backfill.sql +11 -0
- package/dist/server/server/migrations/012_work_block_ranges.sql +7 -0
- package/dist/server/server/migrations/013_microsoft_local_auth_settings.sql +8 -0
- package/dist/server/server/migrations/014_note_tags_and_ephemeral.sql +8 -0
- package/dist/server/server/migrations/015_multi_user_and_strategies.sql +244 -0
- package/dist/server/server/migrations/016_health_companion.sql +158 -0
- package/dist/server/server/migrations/016_strategy_contracts_and_user_graph.sql +22 -0
- package/dist/server/server/migrations/017_preferences.sql +131 -0
- package/dist/server/server/migrations/018_preference_catalogs.sql +31 -0
- package/dist/server/server/migrations/019_wiki_memory.sql +255 -0
- package/dist/server/server/migrations/020_wiki_page_hierarchy.sql +11 -0
- package/dist/server/server/migrations/021_hide_evidence_from_wiki_index.sql +3 -0
- package/dist/server/server/migrations/022_wiki_ingest_background.sql +85 -0
- package/dist/server/server/migrations/023_diagnostic_logs.sql +28 -0
- package/dist/server/server/migrations/024_questionnaires.sql +96 -0
- package/dist/server/server/migrations/025_ai_model_connections.sql +26 -0
- package/dist/server/server/migrations/026_custom_theme_settings.sql +2 -0
- package/dist/server/server/migrations/027_ai_processors.sql +31 -0
- package/dist/server/server/migrations/028_movement_domain.sql +136 -0
- package/dist/server/server/migrations/029_watch_micro_capture.sql +23 -0
- package/dist/server/server/migrations/030_surface_layouts.sql +5 -0
- package/dist/server/server/migrations/031_ai_processor_runtime_upgrades.sql +10 -0
- package/dist/server/server/migrations/032_ai_connectors.sql +44 -0
- package/dist/server/server/migrations/033_movement_trip_point_sync.sql +36 -0
- package/dist/server/server/migrations/034_movement_segment_sync.sql +49 -0
- package/dist/server/server/migrations/035_google_local_auth_settings.sql +2 -0
- package/dist/server/server/migrations/036_google_local_auth_client_secret.sql +2 -0
- package/dist/server/server/migrations/037_workbench_public_inputs_and_run_inputs.sql +5 -0
- package/dist/server/server/migrations/038_data_management_settings.sql +11 -0
- package/dist/server/server/migrations/039_life_force_and_action_points.sql +114 -0
- package/dist/server/server/migrations/040_screen_time_domain.sql +89 -0
- package/dist/server/server/migrations/041_companion_source_states.sql +21 -0
- package/dist/server/server/migrations/042_movement_boxes.sql +47 -0
- package/dist/server/server/migrations/043_movement_box_overlap_overrides.sql +26 -0
- package/dist/server/{app.js → server/src/app.js} +2112 -414
- package/dist/server/server/src/connectors/box-registry.js +223 -0
- package/dist/server/server/src/data-management-types.js +107 -0
- package/dist/server/{db.js → server/src/db.js} +72 -4
- package/dist/server/server/src/debug.js +19 -0
- package/dist/server/{demo-data.js → server/src/demo-data.js} +2 -2
- package/dist/server/{health.js → server/src/health.js} +702 -18
- package/dist/server/{managers → server/src/managers}/platform/llm-manager.js +7 -4
- package/dist/server/server/src/managers/platform/mock-workbench-provider.js +149 -0
- package/dist/server/{managers → server/src/managers}/platform/secrets-manager.js +18 -1
- package/dist/server/{managers → server/src/managers}/runtime.js +9 -0
- package/dist/server/{movement.js → server/src/movement.js} +1971 -112
- package/dist/server/{openapi.js → server/src/openapi.js} +491 -3
- package/dist/server/{psyche-types.js → server/src/psyche-types.js} +9 -1
- package/dist/server/{repositories → server/src/repositories}/activity-events.js +8 -0
- package/dist/server/{repositories → server/src/repositories}/ai-connectors.js +758 -47
- package/dist/server/{repositories → server/src/repositories}/calendar.js +1 -1
- package/dist/server/{repositories → server/src/repositories}/habits.js +37 -1
- package/dist/server/{repositories → server/src/repositories}/model-settings.js +13 -3
- package/dist/server/{repositories → server/src/repositories}/notes.js +3 -0
- package/dist/server/{repositories → server/src/repositories}/settings.js +431 -21
- package/dist/server/{repositories → server/src/repositories}/tasks.js +170 -10
- package/dist/server/server/src/runtime-data-root.js +82 -0
- package/dist/server/server/src/screen-time.js +802 -0
- package/dist/server/{services → server/src/services}/calendar-runtime.js +775 -58
- package/dist/server/server/src/services/data-management.js +788 -0
- package/dist/server/{services → server/src/services}/entity-crud.js +205 -2
- package/dist/server/server/src/services/google-calendar-oauth-config.js +176 -0
- package/dist/server/server/src/services/knowledge-graph.js +1455 -0
- package/dist/server/server/src/services/life-force-model.js +197 -0
- package/dist/server/server/src/services/life-force.js +1270 -0
- package/dist/server/server/src/services/psyche-observation-calendar.js +413 -0
- package/dist/server/{types.js → server/src/types.js} +420 -29
- package/dist/server/server/src/web.js +332 -0
- package/dist/server/src/components/customization/utility-widgets.js +439 -0
- package/dist/server/src/components/ui/info-tooltip.js +25 -0
- package/dist/server/src/components/workbench-boxes/calendar/calendar-boxes.js +78 -0
- package/dist/server/src/components/workbench-boxes/goals/goals-boxes.js +62 -0
- package/dist/server/src/components/workbench-boxes/habits/habits-boxes.js +62 -0
- package/dist/server/src/components/workbench-boxes/health/health-boxes.js +147 -0
- package/dist/server/src/components/workbench-boxes/insights/insights-boxes.js +50 -0
- package/dist/server/src/components/workbench-boxes/kanban/kanban-boxes.js +136 -0
- package/dist/server/src/components/workbench-boxes/movement/movement-boxes.js +47 -0
- package/dist/server/src/components/workbench-boxes/notes/notes-boxes.js +132 -0
- package/dist/server/src/components/workbench-boxes/overview/overview-boxes.js +65 -0
- package/dist/server/src/components/workbench-boxes/preferences/preferences-boxes.js +78 -0
- package/dist/server/src/components/workbench-boxes/projects/projects-boxes.js +62 -0
- package/dist/server/src/components/workbench-boxes/psyche/psyche-boxes.js +88 -0
- package/dist/server/src/components/workbench-boxes/questionnaires/questionnaires-boxes.js +61 -0
- package/dist/server/src/components/workbench-boxes/review/review-boxes.js +53 -0
- package/dist/server/src/components/workbench-boxes/shared/define-workbench-box.js +6 -0
- package/dist/server/src/components/workbench-boxes/shared/generic-node-view.js +49 -0
- package/dist/server/src/components/workbench-boxes/strategies/strategies-boxes.js +62 -0
- package/dist/server/src/components/workbench-boxes/tasks/tasks-boxes.js +76 -0
- package/dist/server/src/components/workbench-boxes/today/today-boxes.js +78 -0
- package/dist/server/src/components/workbench-boxes/wiki/wiki-boxes.js +60 -0
- package/dist/server/src/lib/api-error.js +37 -0
- package/dist/server/src/lib/api.js +2118 -0
- package/dist/server/src/lib/calendar-name-deduper.js +144 -0
- package/dist/server/src/lib/data-management-types.js +1 -0
- package/dist/server/src/lib/diagnostics.js +67 -0
- package/dist/server/src/lib/entity-visuals.js +279 -0
- package/dist/server/src/lib/knowledge-graph-types.js +276 -0
- package/dist/server/src/lib/knowledge-graph.js +470 -0
- package/dist/server/src/lib/psyche-types.js +1 -0
- package/dist/server/src/lib/questionnaire-types.js +1 -0
- package/dist/server/src/lib/runtime-paths.js +24 -0
- package/dist/server/src/lib/schemas.js +238 -0
- package/dist/server/src/lib/snapshot-normalizer.js +416 -0
- package/dist/server/src/lib/theme-system.js +319 -0
- package/dist/server/src/lib/types.js +1 -0
- package/dist/server/src/lib/utils.js +22 -0
- package/dist/server/src/lib/workbench/boxes.js +16 -0
- package/dist/server/src/lib/workbench/contracts.js +229 -0
- package/dist/server/src/lib/workbench/nodes.js +215 -0
- package/dist/server/src/lib/workbench/registry.js +120 -0
- package/dist/server/src/lib/workbench/runtime.js +397 -0
- package/dist/server/src/lib/workbench/tool-catalog.js +68 -0
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/server/index.js +68 -0
- package/server/migrations/035_google_local_auth_settings.sql +2 -0
- package/server/migrations/036_google_local_auth_client_secret.sql +2 -0
- package/server/migrations/037_workbench_public_inputs_and_run_inputs.sql +5 -0
- package/server/migrations/038_data_management_settings.sql +11 -0
- package/server/migrations/039_life_force_and_action_points.sql +114 -0
- package/server/migrations/040_screen_time_domain.sql +89 -0
- package/server/migrations/041_companion_source_states.sql +21 -0
- package/server/migrations/042_movement_boxes.sql +47 -0
- package/server/migrations/043_movement_box_overlap_overrides.sql +26 -0
- package/skills/forge-openclaw/SKILL.md +27 -11
- package/skills/forge-openclaw/entity_conversation_playbooks.md +411 -46
- package/skills/forge-openclaw/psyche_entity_playbooks.md +195 -20
- package/dist/assets/index-CFCKDIMH.js +0 -67
- package/dist/assets/index-CFCKDIMH.js.map +0 -1
- package/dist/assets/index-ZPY6U1TU.css +0 -1
- package/dist/assets/vendor-D9PTEPSB.js +0 -824
- package/dist/assets/vendor-D9PTEPSB.js.map +0 -1
- package/dist/assets/viz-Cqb6s--o.js +0 -34
- package/dist/assets/viz-Cqb6s--o.js.map +0 -1
- package/dist/server/connectors/box-registry.js +0 -257
- package/dist/server/services/psyche-observation-calendar.js +0 -46
- package/dist/server/web.js +0 -98
- /package/dist/server/{discovery-advertiser.js → server/src/discovery-advertiser.js} +0 -0
- /package/dist/server/{e2e-server.js → server/src/e2e-server.js} +0 -0
- /package/dist/server/{errors.js → server/src/errors.js} +0 -0
- /package/dist/server/{index.js → server/src/index.js} +0 -0
- /package/dist/server/{managers → server/src/managers}/base.js +0 -0
- /package/dist/server/{managers → server/src/managers}/contracts.js +0 -0
- /package/dist/server/{managers → server/src/managers}/platform/api-gateway-manager.js +0 -0
- /package/dist/server/{managers → server/src/managers}/platform/audit-manager.js +0 -0
- /package/dist/server/{managers → server/src/managers}/platform/authentication-manager.js +0 -0
- /package/dist/server/{managers → server/src/managers}/platform/authorization-manager.js +0 -0
- /package/dist/server/{managers → server/src/managers}/platform/background-job-manager.js +0 -0
- /package/dist/server/{managers → server/src/managers}/platform/configuration-manager.js +0 -0
- /package/dist/server/{managers → server/src/managers}/platform/database-manager.js +0 -0
- /package/dist/server/{managers → server/src/managers}/platform/event-bus-manager.js +0 -0
- /package/dist/server/{managers → server/src/managers}/platform/external-service-manager.js +0 -0
- /package/dist/server/{managers → server/src/managers}/platform/health-manager.js +0 -0
- /package/dist/server/{managers → server/src/managers}/platform/migration-manager.js +0 -0
- /package/dist/server/{managers → server/src/managers}/platform/openai-responses-provider.js +0 -0
- /package/dist/server/{managers → server/src/managers}/platform/search-index-manager.js +0 -0
- /package/dist/server/{managers → server/src/managers}/platform/session-manager.js +0 -0
- /package/dist/server/{managers → server/src/managers}/platform/storage-manager.js +0 -0
- /package/dist/server/{managers → server/src/managers}/platform/token-manager.js +0 -0
- /package/dist/server/{managers → server/src/managers}/platform/transaction-manager.js +0 -0
- /package/dist/server/{managers → server/src/managers}/platform/trusted-network.js +0 -0
- /package/dist/server/{managers → server/src/managers}/type-guards.js +0 -0
- /package/dist/server/{preferences-seeds.js → server/src/preferences-seeds.js} +0 -0
- /package/dist/server/{preferences-types.js → server/src/preferences-types.js} +0 -0
- /package/dist/server/{questionnaire-flow.js → server/src/questionnaire-flow.js} +0 -0
- /package/dist/server/{questionnaire-seeds.js → server/src/questionnaire-seeds.js} +0 -0
- /package/dist/server/{questionnaire-types.js → server/src/questionnaire-types.js} +0 -0
- /package/dist/server/{repositories → server/src/repositories}/ai-processors.js +0 -0
- /package/dist/server/{repositories → server/src/repositories}/collaboration.js +0 -0
- /package/dist/server/{repositories → server/src/repositories}/deleted-entities.js +0 -0
- /package/dist/server/{repositories → server/src/repositories}/diagnostic-logs.js +0 -0
- /package/dist/server/{repositories → server/src/repositories}/domains.js +0 -0
- /package/dist/server/{repositories → server/src/repositories}/entity-ownership.js +0 -0
- /package/dist/server/{repositories → server/src/repositories}/event-log.js +0 -0
- /package/dist/server/{repositories → server/src/repositories}/goals.js +0 -0
- /package/dist/server/{repositories → server/src/repositories}/preferences.js +0 -0
- /package/dist/server/{repositories → server/src/repositories}/projects.js +0 -0
- /package/dist/server/{repositories → server/src/repositories}/psyche.js +0 -0
- /package/dist/server/{repositories → server/src/repositories}/questionnaires.js +0 -0
- /package/dist/server/{repositories → server/src/repositories}/rewards.js +0 -0
- /package/dist/server/{repositories → server/src/repositories}/strategies.js +0 -0
- /package/dist/server/{repositories → server/src/repositories}/surface-layouts.js +0 -0
- /package/dist/server/{repositories → server/src/repositories}/tags.js +0 -0
- /package/dist/server/{repositories → server/src/repositories}/task-runs.js +0 -0
- /package/dist/server/{repositories → server/src/repositories}/users.js +0 -0
- /package/dist/server/{repositories → server/src/repositories}/weekly-reviews.js +0 -0
- /package/dist/server/{repositories → server/src/repositories}/wiki-memory.js +0 -0
- /package/dist/server/{repositories → server/src/repositories}/work-adjustments.js +0 -0
- /package/dist/server/{seed-demo.js → server/src/seed-demo.js} +0 -0
- /package/dist/server/{services → server/src/services}/context.js +0 -0
- /package/dist/server/{services → server/src/services}/dashboard.js +0 -0
- /package/dist/server/{services → server/src/services}/gamification.js +0 -0
- /package/dist/server/{services → server/src/services}/insights.js +0 -0
- /package/dist/server/{services → server/src/services}/openai-codex-oauth.js +0 -0
- /package/dist/server/{services → server/src/services}/projects.js +0 -0
- /package/dist/server/{services → server/src/services}/psyche.js +0 -0
- /package/dist/server/{services → server/src/services}/relations.js +0 -0
- /package/dist/server/{services → server/src/services}/reviews.js +0 -0
- /package/dist/server/{services → server/src/services}/run-recovery.js +0 -0
- /package/dist/server/{services → server/src/services}/tagging.js +0 -0
- /package/dist/server/{services → server/src/services}/task-run-watchdog.js +0 -0
- /package/dist/server/{services → server/src/services}/work-time.js +0 -0
- /package/dist/server/{watch-mobile.js → server/src/watch-mobile.js} +0 -0
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
var Cu=Object.defineProperty;var Iu=(t,s,i)=>s in t?Cu(t,s,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[s]=i;var ra=(t,s,i)=>Iu(t,typeof s!="symbol"?s+"":s,i);import{K as Tu,g as Pu,j as e,r as d,L as xl,S as Mu,Q as Au,M as On,N as gl,O as Eu,T as Lu,U as fl,V as Du,W as $u,X as Fn,Y as ut,Z as fe,$ as bt,a0 as _n,a1 as Gt,a2 as Xt,a3 as th,a4 as Ki,a5 as Rn,a6 as sh,a7 as gi,a8 as Ca,a9 as bl,aa as ih,ab as Aa,ac as vl,ad as Ou,ae as Fu,af as mt,ag as fn,ah as Vi,ai as vt,aj as je,ak as Ve,al as _e,am as hs,an as dn,ao as wl,ap as _u,aq as Ui,ar as Qr,as as Tt,a as zn,at as Ru,au as zu,av as qu,aw as ah,ax as Bu,ay as Ku,az as Uu,aA as Qu,aB as nh,aC as fi,aD as hi,aE as bn,aF as rh,aG as Cs,aH as Wu,aI as Hu,aJ as Ia,aK as Is,aL as We,aM as lh,aN as oh,aO as yl,aP as Ms,aQ as Gu,aR as Ro,aS as Xu,aT as dh,aU as xe,aV as Vu,aW as ch,aX as Ju,aY as Yu,aZ as Zu,a_ as Ae,a$ as ep,b0 as tp,b1 as qn,b2 as jl,b3 as Pt,b4 as zt,b5 as Nl,b6 as hh,b7 as Ns,b8 as ya,b9 as sp,ba as ct,bb as mh,bc as ip,bd as cn,be as fs,bf as kl,bg as Sl,bh as ap,bi as Cl,bj as np,bk as rp,bl as lp,bm as zo,bn as qo,bo as op,bp as dp,bq as uh,br as cp,bs as ph,bt as es,bu as Bo,bv as mi,bw as xh,bx as gh,by as Ko,bz as Il,bA as hp,bB as mp,bC as up,bD as pp,bE as Bn,bF as Ji,bG as Wr,bH as Qi,bI as Yi,bJ as Uo,bK as fh,bL as xp,bM as gp,bN as fp,bO as bp,bP as bh,bQ as vp,bR as wp,bS as yp,bT as Wi,bU as vh,bV as jp,bW as Np,bX as kp,bY as Hr,bZ as Sp,b_ as Cp,b$ as wh,c0 as yh,c1 as Ip,c2 as Tp,c3 as Pp,c4 as jh,c5 as Mp,c6 as Ap,c7 as Ep,c8 as vn,c9 as Tl,ca as Lp,cb as Dp,cc as $p,cd as Op,ce as Pl,cf as Fp,cg as _p,ch as Rp,ci as Hi,cj as zp,ck as qp,cl as Bp,cm as Kp,cn as Qo,co as Up,cp as Qp,cq as Nh,cr as Wp,cs as lr,ct as Hp,cu as Gp,cv as Wo,cw as Xp,cx as Vp,cy as Jp,cz as Yp,cA as Re,cB as or,cC as Zp,cD as ex,J as tx,cE as sx,cF as ix}from"./vendor-D9PTEPSB.js";import{R as Et,P as Lt,O as Dt,C as $t,T as Ot,D as qt,a as Ft,b as ax}from"./ui-nYfoC0Gq.js";import{m as Kt,A as wn}from"./motion-DvkU14p-.js";import{c as nx,u as rx,f as Ho,g as lx}from"./table-DgiPof9E.js";import{R as Kn,A as kh,X as Un,Y as Qn,c as Gr,C as ox,T as Sh,L as dx,e as cx,B as hx,f as mx}from"./viz-Cqb6s--o.js";import{u as Ml,a as Al,P as El,D as Ll,S as yn,v as jn,b as ux,p as px,c as xx,d as Ch,e as Dl,C as $l,f as Ih,g as Th}from"./board-VmF4FAfr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))a(n);new MutationObserver(n=>{for(const r of n)if(r.type==="childList")for(const l of r.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&a(l)}).observe(document,{childList:!0,subtree:!0});function i(n){const r={};return n.integrity&&(r.integrity=n.integrity),n.referrerPolicy&&(r.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?r.credentials="include":n.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function a(n){if(n.ep)return;n.ep=!0;const r=i(n);fetch(n.href,r)}})();function re(...t){return Tu(Pu(t))}function Ol(t){return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(t))}function Fl({className:t,tone:s="primary"}){return e.jsx("span",{"aria-hidden":"true",className:re("inline-block size-4 rounded-full border border-white/14 border-t-transparent bg-[conic-gradient(from_180deg_at_50%_50%,rgba(255,255,255,0.02),rgba(255,255,255,0.34),rgba(255,255,255,0.02))] align-middle motion-safe:animate-spin",s==="primary"&&"shadow-[0_0_0_1px_rgba(192,193,255,0.22)]",s==="subtle"&&"opacity-80 shadow-[0_0_0_1px_rgba(255,255,255,0.08)]",s==="psyche"&&"shadow-[0_0_0_1px_rgba(110,231,183,0.2)]",t)})}function gx(){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:"Power bar",moreRoutesEyebrow:"More routes",moreRoutesTitle:"Move through Forge",moreRoutesDescription:"Use this sheet for secondary destinations so the bottom bar stays clean and easy to use.",loadingEyebrow:"Forge shell",loadingTitle:"Loading Forge",loadingDescription:"Checking your operator session and loading your latest snapshot.",sessionEyebrow:"Forge operator session",stateEyebrow:"Forge state",settled:"Up to date",savingOne:"Saving {count} change",savingOther:"Saving {count} changes",refreshingOne:"Refreshing {count} view",refreshingOther:"Refreshing {count} views",collapseSidebar:"Collapse sidebar",expandSidebar:"Expand sidebar",rail:{taskBackToKanban:"Back to Kanban",taskOpenToday:"Open Today",projectAll:"All projects",projectGoals:"Goal architecture",goalAll:"All goals",goalProjects:"Active projects",psycheHub:"Psyche hub",psycheReports:"Reports",overview:"Overview",today:"Today"},momentum:{title:"Momentum",streak:"Streak",xp:"XP",momentum:"Momentum",streakBadgeOne:"{count} day streak",streakBadgeOther:"{count} day streak",weeklyXp:"{count} weekly XP",liveMomentum:"{count}% momentum",psycheMode:"Psyche active"}},routeLabels:{overview:"Overview",goals:"Goals",habits:"Habits",projects:"Projects",strategies:"Strategies",preferences:"Preferences",calendar:"Calendar",movement:"Movement",sleep:"Sleep",sports:"Sports",kanban:"Kanban",today:"Today",notes:"Notes",wiki:"Wiki",psyche:"Psyche",activity:"Activity",insights:"Insights",review:"Review",settings:"Settings"},routeDetails:{overview:"See priorities, momentum, and recent evidence in one place.",goals:"Keep long-term direction connected to day-to-day work.",habits:"Track recurring commitments and recurring slips with explicit XP consequences.",projects:"Track the initiatives currently moving your goals forward.",strategies:"Plan the directed path from current work to the end state.",preferences:"Model taste, compare tradeoffs, and inspect preference evidence by context.",calendar:"Sync provider calendars, define work blocks, and plan real timeboxes.",movement:"See stays, trips, landmarks, and movement-linked evidence across time.",sleep:"Inspect sleep timing, recovery, and Psyche-linked context.",sports:"Inspect workout sessions, training volume, and reflection metadata.",kanban:"Move active work across the board without losing context.",today:"Focus today on the clearest next move.",notes:"Search Markdown work notes and reopen the linked work fast.",wiki:"Work in a file-first memory vault with backlinks, entity links, and optional embeddings.",psyche:"Reflect on values, patterns, and reports with structure.",activity:"Review the visible audit trail of what changed and when.",insights:"Store and review coaching, analysis, and recommendations.",review:"Review the week and set the next push.",settings:"Manage collaboration, safety, and operator preferences."},navigation:{openRoute:"Open {label}",create:"Create",createTitle:"Create in Forge",createDescription:"Choose what you want to add next.",closeCreateMenu:"Close create menu",newGoal:"New life goal",newGoalDescription:"Define a long-term direction.",newProject:"New project",newProjectDescription:"Add a concrete initiative under a life goal.",newTask:"New task",newTaskDescription:"Capture the next actionable step in a project.",newStrategy:"New strategy",newStrategyDescription:"Add a directed plan across projects and tasks."},commandPalette:{searchPlaceholder:"Search Forge routes, records, wiki pages, notes, and active work",noResults:"No Forge result matches this search yet.",categoryRoute:"Route",categoryGoal:"Goal",categoryProject:"Project",categoryTask:"Task",routeOverview:"Open the overview.",routeToday:"Open today.",routeKanban:"Open the board.",routeNotes:"Search notes.",routeWiki:"Open the wiki memory workspace.",routePsyche:"Open Psyche.",routeGoals:"Open your life goals.",routeHabits:"Open your habits.",routeProjects:"Open your projects.",routeStrategies:"Open your strategies.",routePreferences:"Open the preferences workspace.",routeCalendar:"Open the calendar workspace.",routeReview:"Open weekly review.",routeSettings:"Open settings.",openLifeGoal:"Open life goal",openFocusTask:"Open focus task"},pageState:{loadingTitle:"Getting things ready",loadingDescription:"Loading the latest Forge data for this view."},settings:{localeLabel:"Language",localeDescription:"Choose the language used throughout Forge.",localeEnglish:"English",localeFrench:"French",localeSaved:"Language saved"},overview:{heroEyebrow:"Strategic overview",heroEmptyTitle:"Ready to get started",heroDescription:"See your goals, active projects, current tasks, and recent evidence in one place.",emptyTitle:"No overview yet",emptyDescription:"Create a life goal, project, or task to give Forge something real to organize.",emptyAction:"Open life goals",commandEyebrow:"Command surface",commandTitle:"Now, next, risks, and recent proof",commandDescription:"See what needs attention now, what comes next, where drift is appearing, and what progress is already visible.",sectionGoals:"Active life goals",sectionProjects:"Active projects",sectionFocus:"Today's focus",sectionEvidence:"Recent evidence",sectionMomentum:"Momentum core",sectionAttention:"Needs attention",noGoals:"No life goals are active yet. Start by defining the direction you want Forge to support.",noProjects:"No active projects yet. Add a project to turn a goal into practical work.",noFocus:"No focus tasks yet. Promote a task when you know what deserves attention next.",noEvidence:"No evidence has been recorded yet. Completed work and logged activity will appear here.",noProjectYet:"No project yet",noAttention:"No major drift signal right now. Forge will raise neglected goals here when they start slipping.",metricsLevel:"Level",metricsWeeklyXp:"Weekly XP",metricsFocusTasks:"Focus tasks",metricsOverdue:"Overdue"},todayPage:{heroEyebrow:"Today",heroEmptyTitle:"No daily direction yet",heroDescription:"Start a task, earn XP, and keep today's work clear.",emptyTitle:"No daily runway yet",emptyDescription:"Add goals, tasks, or reward targets so Forge can shape a useful day plan.",emptyAction:"Open life goals",commandEyebrow:"Today command",commandTitle:"Directive, daily quests, recovery, and finish line",commandDescription:"See the next useful move clearly and keep the day grounded in real work.",questsTitle:"Daily quests",questsEmpty:"No daily quests yet. They will appear once Forge has enough live work and reward context.",rewardsTitle:"Milestone rewards",rewardsEmpty:"No milestone rewards are active yet. Long-term rewards will appear here as progress structure grows.",signalDirective:"Directive",signalQuest:"Quest chain",signalComeback:"Recovery",signalFinish:"Finish line",noDirective:"Choose one clear task to anchor the day.",noQuest:"No active daily quest chain",noQuestDetail:"Daily quests should reinforce real work, not distract from it.",noComeback:"Recovery window is clear",noFinish:"Keep the day clean",noDirectiveDetail:"Promote a real task and Today will become sharper immediately.",noFinishDetail:"A good finish today should make tomorrow lighter, not noisier."},kanban:{heroEyebrow:"Task board",heroTitle:"Task board",heroDescription:"Use the board to move active work, review blocked items, and open task details when you need more context.",emptyTitle:"No board yet",emptyDescription:"Create your first task inside a project to start using the board.",emptyAction:"Open life goals",healthEyebrow:"Board status",healthTitle:"Visible work, focus, blockers, and completed work",healthDescription:"See what is active, what needs attention, and what has already been completed.",visibleWork:"Visible work",focusWork:"Current focus",blockedWork:"Blocked work",completedWork:"Completed work",visibleDetail:"{hidden} tasks are outside the current filters.",focusDetailReady:"These are the tasks most ready to be picked up next.",focusDetailEmpty:"Move one backlog task into focus to make the board more useful.",blockedDetail:"These tasks need a decision, an unblock, or a reset before they can move again.",blockedDetailEmpty:"No blocked tasks right now.",doneDetail:"Completed work stays here until you review it or reopen it.",doneDetailEmpty:"Nothing has been completed on this board yet.",boardFilters:"Board filters",filterGoal:"Goal",filterOwner:"Owner",allGoals:"All goals",allOwners:"All owners",noTasksMatch:"No tasks match these filters",noTasksMatchDescription:"These filters hide every task. Reset them to see the full board again.",taskContext:"Task details",evidence:"Recent activity",runHistory:"Run history",noTaskEvidence:"No activity has been recorded for this task yet.",noRunHistory:"No runs have been recorded for this task yet.",taskPlacement:"Task placement",projectLabel:"Project: {value}",goalLabel:"Life goal: {value}",ownerLabel:"Owner: {value}",dueLabel:"Due: {value}",openTask:"Open task",openProject:"Open project",openGoal:"Open life goal",noProjectLinked:"No project linked",noGoalLinked:"No life goal linked"},dailyRunway:{runwayEyebrow:"Today",runwayTitle:"Tasks for today",prioritiesOne:"{count} task",prioritiesOther:"{count} tasks",unassigned:"Unassigned",runwayItem:"Task {index}",noNote:"No note yet.",inspect:"Open task",actionBacklog:"Start",actionFocus:"Start",actionProgress:"Done",actionBlocked:"Start",timelineEyebrow:"By status",timelineTitle:"Tasks by status",emptyBucket:"Nothing here right now."},executionBoard:{laneBacklogTitle:"Backlog",laneBacklogDetail:"Not started yet",laneFocusTitle:"Focus",laneFocusDetail:"Ready to work on",laneProgressTitle:"In progress",laneProgressDetail:"Currently moving",laneBlockedTitle:"Blocked",laneBlockedDetail:"Needs attention",laneDoneTitle:"Done",laneDoneDetail:"Completed",noExecutionNote:"No note yet.",reopen:"Reopen",emptyLane:"No tasks in this lane.",deleteDropTitle:"Drop here to delete",deleteDropDetail:"Move this task into the Bin.",deleteConfirmTitle:"Delete task?",deleteConfirmDescription:'Move "{title}" to the Bin? You can restore it later from Settings.',deleteConfirmCheckbox:"Do not ask again",deleteConfirmCancel:"No",deleteConfirmSubmit:"Yes, delete",deletingTask:"Deleting…"},weeklyReview:{heroEyebrow:"Weekly review",heroDescription:"Review the week, note what moved, and decide what needs attention next.",summaryEyebrow:"Weekly summary",summaryTitle:"This week, wins, recovery, and next steps",summaryDescription:"Use this review to understand what happened this week and choose the most useful next move.",sectionMomentum:"Momentum summary",sectionGoals:"Goal check-in",sectionWins:"Wins",completionBonus:"Completion bonus",finalize:"Finish review",finalized:"Review finalized",finalizedDetail:"This cycle is already locked into evidence.",finalizePending:"Finalizing review",noWin:"No win recorded yet",noWinDetail:"If this week was quiet, use the review to capture one useful takeaway anyway.",noRecovery:"No recovery suggestion yet",noRecoveryDetail:"If the week felt steady, keep a light recovery option available for next week."},dialogs:{closeDialog:"Close dialog",task:{eyebrow:"Task",createTitle:"Create task",editTitle:"Edit task",description:"Use tasks for the next concrete step inside a project. Pick the project first so Forge can keep the larger context aligned.",project:"Project",selectProject:"Select a project",goal:"Life goal",title:"Title",descriptionLabel:"Description",owner:"Owner",xp:"XP",priority:"Priority",status:"Status",effort:"Effort",energy:"Energy",dueDate:"Due date",tags:"Tags",save:"Save task",create:"Create task"},project:{eyebrow:"Project",createTitle:"Create project",editTitle:"Edit project",description:"Use projects to turn a life goal into a concrete stream of work with tasks, evidence, and momentum.",goal:"Life goal",selectGoal:"Select a life goal",title:"Title",descriptionLabel:"Description",status:"Status",targetXp:"Target XP",themeColor:"Theme color",save:"Save project",create:"Create project",submitError:"Project update failed."},goal:{eyebrow:"Life goal",createTitle:"Create life goal",editTitle:"Edit life goal",description:"Use life goals to define what matters over the coming months or years before you break the path into projects.",title:"Title",descriptionLabel:"Description",horizon:"Horizon",status:"Status",targetXp:"Target XP",themeColor:"Theme color",tags:"Life domains and context",save:"Save life goal",create:"Create life goal",submitError:"Goal update failed."}},taskDetail:{eyebrow:"Task",errorEyebrow:"Task",emptyPayload:"Forge returned an empty task payload.",heroFallback:"Use this task page to update the work, move it forward, and keep its context clear.",commandEyebrow:"Task overview",commandTitle:"What this task is, what to do next, and where it fits",commandDescription:"Use this page to update the task itself and understand its surrounding context clearly.",signalState:"State",signalNext:"Next move",signalEvidence:"Recent activity",signalAnchor:"Connected project",noStateChange:"No state change needed",terminalStateDetail:"This task is already in a completed state unless you decide to reopen it.",noEvidence:"No recent activity yet",noEvidenceDetail:"Completed work, corrections, and logged sessions will appear here as the task moves.",noAnchor:"No connected project yet",linkAnchorDetail:"Connect this task to a project or life goal so Forge can show why it matters.",edit:"Edit task",deleteTask:"Delete",deleting:"Deleting…",deleteTaskConfirm:'Move "{title}" to the Bin? You can restore it later unless you permanently delete it from Settings.',openProject:"Open project",openGoal:"Open life goal",markNotCompleted:"Mark not completed",sectionStatus:"Task status",fieldProject:"Project",fieldGoal:"Life goal",fieldDueDate:"Due date",pendingMove:"Moving",actionBacklog:"Move to backlog",actionFocus:"Move to focus",actionProgress:"Start now",actionBlocked:"Mark blocked",actionDone:"Mark completed",sectionEvidence:"Recent activity",noVisibleEvidence:"No activity has been recorded for this task yet.",removeLog:"Remove log",openRelatedItem:"Open related item",sectionRuns:"Work sessions",noRuns:"No work sessions have been recorded for this task yet.",sectionMetadata:"More task details",metaOwner:"Owner: {value}",metaEffort:"Effort: {value}",metaEnergy:"Energy: {value}",metaCreated:"Created: {value}",metaUpdated:"Last updated: {value}",metaCompleted:"Completed at: {value}",metaNotCompleted:"Not completed"},projectDetail:{errorEyebrow:"Project",heroEyebrow:"Project",commandEyebrow:"Project status",commandTitle:"Momentum, next task, risk, and evidence",commandDescription:"Use this page to see what is moving, what needs attention next, and what evidence already supports the project.",signalMomentum:"Momentum",signalNext:"Next task",signalRisk:"Risk",signalEvidence:"Evidence",trackedTasksOne:"{count} tracked task",trackedTasksOther:"{count} tracked tasks",noNextTask:"No next task selected yet",noNextTaskDetail:"Pick or create a task so the project has a clear next move.",needsFocus:"Needs focus",noRisk:"No immediate risk signal",noRiskDetail:"Blocked or neglected work will appear here when the project starts drifting.",noEvidence:"No recent evidence yet",noEvidenceDetail:"Completed work and logged activity will appear here as the project moves.",compatibility:"Compatibility mode",compatibilityDescription:"This project comes from an older snapshot format. You can review it here, but editing the project itself needs the updated backend.",addTask:"Add task",editProject:"Edit project",suspendProject:"Suspend",suspending:"Suspending…",finishProject:"Finish",finishing:"Finishing…",restartProject:"Restart",restarting:"Restarting…",deleteProject:"Delete",deleting:"Deleting…",deleteProjectConfirm:'Move "{title}" to the Bin? You can restore it later unless you permanently delete it from Settings.',openGoal:"Open life goal",sectionHealth:"Project health",fieldStatus:"Status",fieldProgress:"Progress",fieldMomentum:"Momentum",sectionEvidence:"Recent evidence"},goalDetail:{eyebrow:"Life goal",missingTitle:"This life goal is not available",missingDescription:"Forge cannot find this life goal in the current snapshot. Return to the goals view and choose an active one.",backToGoals:"Back to goals",heroBadgeOne:"{count} project",heroBadgeOther:"{count} projects",commandEyebrow:"Goal status",commandTitle:"Progress, next push, risk, and evidence",commandDescription:"Use this page to see what is advancing the goal, what should move next, and where support is needed.",signalProgress:"Progress",signalNext:"Next push",signalRisk:"Risk",signalEvidence:"Evidence",progressTitle:"{progress}% with {count} completed tasks",progressDetail:"{xp} XP is already banked on this goal.",noProject:"No active project yet",noProjectDetail:"Add a project so this goal has a concrete execution path.",needsProject:"Needs project",nextMove:"Next move: {value}",noRisk:"No drift signal right now",noRiskDetail:"If this goal starts slipping, Forge will surface that pressure here.",noEvidence:"No recent evidence yet",noEvidenceDetail:"Completed tasks, project motion, and agent actions will appear here as proof of progress.",edit:"Edit life goal",addProject:"Add project",deleteGoal:"Delete",deleting:"Deleting…",deleteGoalConfirm:'Move "{title}" to the Bin? You can restore it later unless you permanently delete it from Settings.',sectionProjects:"Projects advancing this goal",noProjects:"This goal does not have an active project yet. Add one to turn the goal into practical motion.",addNextTask:"Add the next task",sectionHealth:"Goal health",fieldProgress:"Progress",fieldCompletedTasks:"Completed tasks",fieldXpBanked:"XP banked",sectionEvidence:"Recent evidence",noEvidenceLogged:"No evidence has been logged for this goal yet. Task completions, project updates, and agent actions will appear here."}}}}const fx=gx(),bx={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:"Barre de puissance",moreRoutesEyebrow:"Autres vues",moreRoutesTitle:"Parcourir Forge",moreRoutesDescription:"Utilisez ce panneau pour accéder aux vues secondaires sans surcharger la barre inférieure.",loadingEyebrow:"Forge",loadingTitle:"Chargement de Forge",loadingDescription:"Vérification de votre session opérateur et chargement du dernier instantané.",sessionEyebrow:"Session opérateur Forge",stateEyebrow:"État de Forge",settled:"À jour",savingOne:"Enregistrement de {count} modification",savingOther:"Enregistrement de {count} modifications",refreshingOne:"Actualisation de {count} vue",refreshingOther:"Actualisation de {count} vues",collapseSidebar:"Réduire la barre latérale",expandSidebar:"Déployer la barre latérale",rail:{taskBackToKanban:"Retour au Kanban",taskOpenToday:"Ouvrir Aujourd'hui",projectAll:"Tous les projets",projectGoals:"Architecture des objectifs",goalAll:"Tous les objectifs",goalProjects:"Projets actifs",psycheHub:"Hub Psyche",psycheReports:"Rapports",overview:"Vue d'ensemble",today:"Aujourd'hui"},momentum:{title:"Momentum",streak:"Série",xp:"XP",momentum:"Momentum",streakBadgeOne:"{count} jour de série",streakBadgeOther:"{count} jours de série",weeklyXp:"{count} XP cette semaine",liveMomentum:"{count}% de momentum",psycheMode:"Psyche active"}},routeLabels:{overview:"Vue d'ensemble",goals:"Objectifs",habits:"Habitudes",projects:"Projets",strategies:"Stratégies",preferences:"Préférences",calendar:"Calendrier",movement:"Mouvement",sleep:"Sommeil",sports:"Sport",kanban:"Kanban",today:"Aujourd'hui",notes:"Notes",wiki:"Wiki",psyche:"Psyche",activity:"Activité",insights:"Insights",review:"Revue",settings:"Réglages"},routeDetails:{overview:"Voyez les priorités, le momentum et les preuves récentes au même endroit.",goals:"Reliez la direction long terme au travail du quotidien.",habits:"Suivez les engagements récurrents et les rechutes avec des conséquences XP explicites.",projects:"Suivez les initiatives qui font avancer vos objectifs.",strategies:"Planifiez le chemin dirigé entre le travail actuel et l'état final.",preferences:"Modélisez les goûts, comparez les arbitrages et inspectez les preuves par contexte.",calendar:"Synchronisez les calendriers, définissez les blocs de travail et planifiez des timeboxes réelles.",movement:"Inspectez séjours, trajets, lieux clés et preuves liées au mouvement.",sleep:"Inspectez le sommeil, la régularité et le contexte lié à Psyche.",sports:"Inspectez les entraînements, le volume et les métadonnées de réflexion.",kanban:"Faites progresser le travail actif sans perdre le contexte.",today:"Concentrez aujourd'hui sur le prochain mouvement le plus net.",notes:"Recherchez les notes Markdown et rouvrez vite le travail lié.",wiki:"Travaillez dans une mémoire explicite basée sur des fichiers avec backlinks, liens Forge et embeddings optionnels.",psyche:"Réfléchissez avec structure sur vos valeurs, vos schémas et vos rapports.",activity:"Relisez la trace visible de ce qui a changé et quand.",insights:"Stockez et relisez coaching, analyses et recommandations.",review:"Relisez la semaine et préparez la prochaine poussée.",settings:"Gérez la collaboration, la sécurité et vos préférences."},navigation:{openRoute:"Ouvrir {label}",create:"Créer",createTitle:"Créer dans Forge",createDescription:"Choisissez ce que vous voulez ajouter ensuite.",closeCreateMenu:"Fermer le menu de création",newGoal:"Nouvel objectif de vie",newGoalDescription:"Définir une direction à long terme.",newProject:"Nouveau projet",newProjectDescription:"Ajouter une initiative concrète sous un objectif de vie.",newTask:"Nouvelle tâche",newTaskDescription:"Capturer la prochaine étape actionnable dans un projet.",newStrategy:"Nouvelle stratégie",newStrategyDescription:"Ajouter un plan dirigé à travers projets et tâches."},commandPalette:{searchPlaceholder:"Rechercher les vues Forge, les fiches, les pages wiki, les notes et le travail actif",noResults:"Aucun résultat Forge ne correspond à cette recherche.",categoryRoute:"Vue",categoryGoal:"Objectif",categoryProject:"Projet",categoryTask:"Tâche",routeOverview:"Ouvrir la vue d'ensemble.",routeToday:"Ouvrir aujourd'hui.",routeKanban:"Ouvrir le tableau.",routeNotes:"Rechercher les notes.",routeWiki:"Ouvrir l'espace mémoire wiki.",routePsyche:"Ouvrir Psyche.",routeGoals:"Ouvrir vos objectifs de vie.",routeHabits:"Ouvrir vos habitudes.",routeProjects:"Ouvrir vos projets.",routeStrategies:"Ouvrir vos stratégies.",routePreferences:"Ouvrir l'espace préférences.",routeCalendar:"Ouvrir l'espace calendrier.",routeReview:"Ouvrir la revue hebdomadaire.",routeSettings:"Ouvrir les réglages.",openLifeGoal:"Ouvrir l'objectif de vie",openFocusTask:"Ouvrir la tâche prioritaire"},pageState:{loadingTitle:"Préparation en cours",loadingDescription:"Chargement des dernières données Forge pour cette vue."},settings:{localeLabel:"Langue",localeDescription:"Choisissez la langue utilisée dans Forge.",localeEnglish:"Anglais",localeFrench:"Français",localeSaved:"Langue enregistrée"},overview:{heroEyebrow:"Vue stratégique",heroEmptyTitle:"Prêt à démarrer",heroDescription:"Voyez vos objectifs, projets actifs, tâches en cours et preuves récentes au même endroit.",emptyTitle:"Pas encore de vue d'ensemble",emptyDescription:"Créez un objectif de vie, un projet ou une tâche pour donner à Forge une base réelle.",emptyAction:"Ouvrir les objectifs de vie",commandEyebrow:"Vue de commande",commandTitle:"Maintenant, ensuite, risques et preuves récentes",commandDescription:"Cette vue doit montrer ce qui mérite votre attention maintenant, ce qui vient ensuite, où la dérive apparaît et les progrès déjà visibles.",sectionGoals:"Objectifs de vie actifs",sectionProjects:"Projets actifs",sectionFocus:"Priorité du jour",sectionEvidence:"Preuves récentes",sectionMomentum:"Noyau de momentum",sectionAttention:"À surveiller",noGoals:"Aucun objectif de vie actif pour le moment. Commencez par définir la direction que Forge doit soutenir.",noProjects:"Aucun projet actif. Ajoutez un projet pour transformer un objectif en travail concret.",noFocus:"Aucune tâche prioritaire pour le moment. Faites passer une tâche en priorité quand vous savez quoi faire ensuite.",noEvidence:"Aucune preuve enregistrée pour le moment. Le travail accompli et l'activité journalisée apparaîtront ici.",noProjectYet:"Pas encore de projet",noAttention:"Aucun signal majeur de dérive pour le moment. Forge affichera ici les objectifs négligés.",metricsLevel:"Niveau",metricsWeeklyXp:"XP hebdo",metricsFocusTasks:"Tâches prioritaires",metricsOverdue:"En retard"},todayPage:{heroEyebrow:"Aujourd'hui",heroEmptyTitle:"Pas encore de direction du jour",heroDescription:"Commencez une tâche, gagnez de l'XP et gardez la journée claire.",emptyTitle:"Pas encore de piste du jour",emptyDescription:"Ajoutez des objectifs, des tâches ou des cibles de récompense pour que Forge puisse construire une journée utile.",emptyAction:"Ouvrir les objectifs de vie",commandEyebrow:"Commande du jour",commandTitle:"Directive, quêtes du jour, reprise et ligne d'arrivée",commandDescription:"Aujourd'hui doit rendre le prochain mouvement utile évident et garder la journée ancrée dans un vrai travail.",questsTitle:"Quêtes du jour",questsEmpty:"Pas encore de quêtes du jour. Elles apparaîtront quand Forge aura assez de travail réel et de contexte de récompense.",rewardsTitle:"Récompenses jalons",rewardsEmpty:"Aucune récompense jalon active pour le moment. Elles apparaîtront à mesure que la structure de progression se précise.",signalDirective:"Directive",signalQuest:"Chaîne de quêtes",signalComeback:"Reprise",signalFinish:"Ligne d'arrivée",noDirective:"Choisissez une tâche claire pour ancrer la journée.",noQuest:"Aucune chaîne de quêtes active",noQuestDetail:"Les quêtes du jour doivent renforcer le vrai travail, pas le détourner.",noComeback:"La fenêtre de reprise est claire",noFinish:"Gardez la journée nette",noDirectiveDetail:"Faites passer une vraie tâche en priorité et la vue Aujourd'hui deviendra plus nette.",noFinishDetail:"Une bonne fin de journée doit alléger demain, pas l'encombrer."},kanban:{heroEyebrow:"Tableau des tâches",heroTitle:"Tableau des tâches",heroDescription:"Utilisez le tableau pour faire avancer le travail actif, revoir les blocages et ouvrir les détails quand nécessaire.",emptyTitle:"Pas encore de tableau",emptyDescription:"Créez votre première tâche dans un projet pour commencer à utiliser le tableau.",emptyAction:"Ouvrir les objectifs de vie",healthEyebrow:"État du tableau",healthTitle:"Travail visible, priorité, blocages et travail terminé",healthDescription:"Le tableau doit montrer ce qui est actif, ce qui demande de l'attention et ce qui est déjà terminé.",visibleWork:"Travail visible",focusWork:"Priorité actuelle",blockedWork:"Travail bloqué",completedWork:"Travail terminé",visibleDetail:"{hidden} tâches sont hors des filtres actuels.",focusDetailReady:"Ce sont les tâches les plus prêtes à être reprises maintenant.",focusDetailEmpty:"Faites passer une tâche du backlog en priorité pour rendre le tableau plus utile.",blockedDetail:"Ces tâches ont besoin d'une décision, d'un déblocage ou d'une remise à plat avant d'avancer.",blockedDetailEmpty:"Aucune tâche bloquée pour le moment.",doneDetail:"Le travail terminé reste ici jusqu'à sa revue ou sa réouverture.",doneDetailEmpty:"Rien n'a encore été terminé sur ce tableau.",boardFilters:"Filtres du tableau",filterGoal:"Objectif",filterOwner:"Responsable",allGoals:"Tous les objectifs",allOwners:"Tous les responsables",noTasksMatch:"Aucune tâche ne correspond à ces filtres",noTasksMatchDescription:"Ces filtres masquent toutes les tâches. Réinitialisez-les pour revoir l'ensemble du tableau.",taskContext:"Détails de la tâche",evidence:"Activité récente",runHistory:"Historique d'exécution",noTaskEvidence:"Aucune activité n'a encore été enregistrée pour cette tâche.",noRunHistory:"Aucune exécution n'a encore été enregistrée pour cette tâche.",taskPlacement:"Placement de la tâche",projectLabel:"Projet : {value}",goalLabel:"Objectif de vie : {value}",ownerLabel:"Responsable : {value}",dueLabel:"Échéance : {value}",openTask:"Ouvrir la tâche",openProject:"Ouvrir le projet",openGoal:"Ouvrir l'objectif de vie",noProjectLinked:"Aucun projet lié",noGoalLinked:"Aucun objectif de vie lié"},dailyRunway:{runwayEyebrow:"Aujourd'hui",runwayTitle:"Tâches du jour",prioritiesOne:"{count} tâche",prioritiesOther:"{count} tâches",unassigned:"Non attribué",runwayItem:"Tâche {index}",noNote:"Aucune note pour le moment.",inspect:"Ouvrir la tâche",actionBacklog:"Commencer",actionFocus:"Commencer",actionProgress:"Terminer",actionBlocked:"Commencer",timelineEyebrow:"Par statut",timelineTitle:"Tâches par statut",emptyBucket:"Rien ici pour le moment."},executionBoard:{laneBacklogTitle:"Backlog",laneBacklogDetail:"Pas encore commencé",laneFocusTitle:"Priorité",laneFocusDetail:"Prêt à être traité",laneProgressTitle:"En cours",laneProgressDetail:"En mouvement",laneBlockedTitle:"Bloqué",laneBlockedDetail:"Demande de l'attention",laneDoneTitle:"Terminé",laneDoneDetail:"Achevé",noExecutionNote:"Aucune note pour le moment.",reopen:"Rouvrir",emptyLane:"Aucune tâche dans cette colonne.",deleteDropTitle:"Déposer ici pour supprimer",deleteDropDetail:"Déplacez cette tâche dans la corbeille.",deleteConfirmTitle:"Supprimer la tâche ?",deleteConfirmDescription:'Déplacer "{title}" vers la corbeille ? Vous pourrez la restaurer plus tard dans Réglages.',deleteConfirmCheckbox:"Ne plus demander",deleteConfirmCancel:"Non",deleteConfirmSubmit:"Oui, supprimer",deletingTask:"Suppression…"},weeklyReview:{heroEyebrow:"Revue hebdomadaire",heroDescription:"Relisez la semaine, notez ce qui a avancé et décidez de ce qui demande de l'attention ensuite.",summaryEyebrow:"Résumé hebdomadaire",summaryTitle:"Cette semaine, les progrès, la récupération et la suite",summaryDescription:"Utilisez cette revue pour comprendre la semaine et choisir le prochain mouvement utile.",sectionMomentum:"Résumé du momentum",sectionGoals:"Point sur les objectifs",sectionWins:"Progrès",completionBonus:"Bonus de complétion",finalize:"Terminer la revue",finalized:"Revue terminée",finalizedDetail:"Ce cycle est déjà consigné comme preuve.",finalizePending:"Finalisation de la revue",noWin:"Aucun progrès enregistré",noWinDetail:"Même si la semaine a été calme, notez au moins un apprentissage utile.",noRecovery:"Aucune suggestion de récupération",noRecoveryDetail:"Si la semaine a été stable, gardez malgré tout une option légère de récupération."},dialogs:{closeDialog:"Fermer la fenêtre",task:{eyebrow:"Tâche",createTitle:"Créer une tâche",editTitle:"Modifier la tâche",description:"Utilisez les tâches pour représenter la prochaine étape concrète dans un projet. Choisissez d'abord le projet pour garder le bon contexte.",project:"Projet",selectProject:"Sélectionner un projet",goal:"Objectif de vie",title:"Titre",descriptionLabel:"Description",owner:"Responsable",xp:"XP",priority:"Priorité",status:"Statut",effort:"Effort",energy:"Énergie",dueDate:"Date d'échéance",tags:"Tags",save:"Enregistrer la tâche",create:"Créer la tâche"},project:{eyebrow:"Projet",createTitle:"Créer un projet",editTitle:"Modifier le projet",description:"Utilisez les projets pour transformer un objectif de vie en flux de travail concret avec tâches, preuves et momentum.",goal:"Objectif de vie",selectGoal:"Sélectionner un objectif de vie",title:"Titre",descriptionLabel:"Description",status:"Statut",targetXp:"XP cible",themeColor:"Couleur du thème",save:"Enregistrer le projet",create:"Créer le projet",submitError:"La mise à jour du projet a échoué."},goal:{eyebrow:"Objectif de vie",createTitle:"Créer un objectif de vie",editTitle:"Modifier l'objectif de vie",description:"Utilisez les objectifs de vie pour définir ce qui compte sur les mois ou les années à venir avant de le décliner en projets.",title:"Titre",descriptionLabel:"Description",horizon:"Horizon",status:"Statut",targetXp:"XP cible",themeColor:"Couleur du thème",tags:"Domaines de vie et contexte",save:"Enregistrer l'objectif de vie",create:"Créer l'objectif de vie",submitError:"La mise à jour de l'objectif a échoué."}},taskDetail:{eyebrow:"Tâche",errorEyebrow:"Tâche",emptyPayload:"Forge a renvoyé une charge utile de tâche vide.",heroFallback:"Utilisez cette page pour mettre à jour la tâche, la faire avancer et garder son contexte clair.",commandEyebrow:"Commande de tâche",commandTitle:"Statut, prochaine action, preuves et contexte",commandDescription:"Cette page doit aider à modifier directement la tâche et à comprendre clairement son contexte.",signalState:"Statut",signalNext:"Prochaine action",signalEvidence:"Activité récente",signalAnchor:"Projet lié",noStateChange:"Aucun changement d'état nécessaire",terminalStateDetail:"Cette tâche est déjà dans un état terminé, sauf si vous décidez de la rouvrir.",noEvidence:"Aucune activité récente pour le moment",noEvidenceDetail:"Le travail terminé, les corrections et les sessions apparaîtront ici à mesure que la tâche avance.",noAnchor:"Aucun projet lié",linkAnchorDetail:"Reliez cette tâche à un projet ou à un objectif de vie pour que Forge puisse montrer pourquoi elle compte.",edit:"Modifier la tâche",deleteTask:"Supprimer",deleting:"Suppression…",deleteTaskConfirm:`Déplacer "{title}" vers la corbeille ? Vous pourrez la restaurer plus tard tant qu'elle n'est pas supprimée définitivement dans Réglages.`,openProject:"Ouvrir le projet",openGoal:"Ouvrir l'objectif de vie",markNotCompleted:"Marquer comme non terminée",sectionStatus:"Statut de la tâche",fieldProject:"Projet",fieldGoal:"Objectif de vie",fieldDueDate:"Date d'échéance",pendingMove:"Déplacement",actionBacklog:"Passer au backlog",actionFocus:"Passer en priorité",actionProgress:"Commencer maintenant",actionBlocked:"Marquer bloquée",actionDone:"Marquer terminée",sectionEvidence:"Activité récente",noVisibleEvidence:"Aucune activité n'a encore été enregistrée pour cette tâche.",removeLog:"Supprimer l'entrée",openRelatedItem:"Ouvrir l'élément lié",sectionRuns:"Sessions de travail",noRuns:"Aucune session de travail n'a encore été enregistrée pour cette tâche.",sectionMetadata:"Autres détails de la tâche",metaOwner:"Responsable : {value}",metaEffort:"Effort : {value}",metaEnergy:"Énergie : {value}",metaCreated:"Créée : {value}",metaUpdated:"Dernière mise à jour : {value}",metaCompleted:"Terminée le : {value}",metaNotCompleted:"Non terminée"},projectDetail:{errorEyebrow:"Projet",heroEyebrow:"Projet",commandEyebrow:"État du projet",commandTitle:"Momentum, prochaine tâche, risque et preuves",commandDescription:"Utilisez cette page pour voir ce qui avance, ce qui demande votre attention ensuite, et quelles preuves soutiennent déjà le projet.",signalMomentum:"Momentum",signalNext:"Prochaine tâche",signalRisk:"Risque",signalEvidence:"Preuves",trackedTasksOne:"{count} tâche suivie",trackedTasksOther:"{count} tâches suivies",noNextTask:"Aucune prochaine tâche choisie",noNextTaskDetail:"Choisissez ou créez une tâche pour donner au projet un prochain mouvement clair.",needsFocus:"Besoin de priorité",noRisk:"Aucun risque immédiat",noRiskDetail:"Le travail bloqué ou négligé apparaîtra ici si le projet commence à dériver.",noEvidence:"Aucune preuve récente",noEvidenceDetail:"Le travail terminé et l'activité enregistrée apparaîtront ici à mesure que le projet avance.",compatibility:"Mode de compatibilité",compatibilityDescription:"Ce projet provient d'un ancien format d'instantané. Vous pouvez le consulter ici, mais sa modification demande le backend mis à jour.",addTask:"Ajouter une tâche",editProject:"Modifier le projet",suspendProject:"Suspendre",suspending:"Suspension…",finishProject:"Terminer",finishing:"Finalisation…",restartProject:"Relancer",restarting:"Relance…",deleteProject:"Supprimer",deleting:"Suppression…",deleteProjectConfirm:`Déplacer "{title}" vers la corbeille ? Vous pourrez le restaurer plus tard tant qu'il n'est pas supprimé définitivement dans Réglages.`,openGoal:"Ouvrir l'objectif de vie",sectionHealth:"Santé du projet",fieldStatus:"Statut",fieldProgress:"Progression",fieldMomentum:"Momentum",sectionEvidence:"Preuves récentes"},goalDetail:{eyebrow:"Objectif de vie",missingTitle:"Cet objectif de vie n'est pas disponible",missingDescription:"Forge ne trouve pas cet objectif de vie dans l'instantané actuel. Revenez à la vue des objectifs et choisissez-en un actif.",backToGoals:"Retour aux objectifs",heroBadgeOne:"{count} projet",heroBadgeOther:"{count} projets",commandEyebrow:"État de l'objectif",commandTitle:"Progression, prochain élan, risque et preuves",commandDescription:"Utilisez cette page pour voir ce qui fait avancer l'objectif, ce qui doit bouger ensuite, et où du soutien est nécessaire.",signalProgress:"Progression",signalNext:"Prochain élan",signalRisk:"Risque",signalEvidence:"Preuves",progressTitle:"{progress}% avec {count} tâches terminées",progressDetail:"{xp} XP sont déjà cumulés sur cet objectif.",noProject:"Aucun projet actif pour le moment",noProjectDetail:"Ajoutez un projet pour donner à cet objectif un chemin d'exécution concret.",needsProject:"Projet nécessaire",nextMove:"Prochaine action : {value}",noRisk:"Aucun signal de dérive pour le moment",noRiskDetail:"Si cet objectif commence à glisser, Forge affichera cette pression ici.",noEvidence:"Aucune preuve récente",noEvidenceDetail:"Les tâches terminées, le mouvement des projets et les actions d'agents apparaîtront ici comme preuve de progression.",edit:"Modifier l'objectif de vie",addProject:"Ajouter un projet",deleteGoal:"Supprimer",deleting:"Suppression…",deleteGoalConfirm:`Déplacer "{title}" vers la corbeille ? Vous pourrez le restaurer plus tard tant qu'il n'est pas supprimé définitivement dans Réglages.`,sectionProjects:"Projets qui font avancer cet objectif",noProjects:"Cet objectif n'a pas encore de projet actif. Ajoutez-en un pour le transformer en mouvement concret.",addNextTask:"Ajouter la prochaine tâche",sectionHealth:"Santé de l'objectif",fieldProgress:"Progression",fieldCompletedTasks:"Tâches terminées",fieldXpBanked:"XP cumulés",sectionEvidence:"Preuves récentes",noEvidenceLogged:"Aucune preuve n'a encore été enregistrée pour cet objectif. Les tâches terminées, les mises à jour de projet et les actions d'agents apparaîtront ici."}}},Go={en:fx,fr:bx};function Xo(t,s){const i=s.split(".");let a=t;for(const n of i){if(!a||typeof a=="string")return;a=a[n]}return typeof a=="string"?a:void 0}function vx(t,s){return s?t.replace(/\{(\w+)\}/g,(i,a)=>{const n=s[a];return n==null?"":String(n)}):t}function Nn(t,s,i){const a=Xo(Go[t],s),n=Xo(Go.en,s);return vx(a??n??s,i)}const wx={locale:"en",t:(t,s)=>Nn("en",t,s),formatDate:t=>t?new Intl.DateTimeFormat("en",{month:"short",day:"numeric"}).format(new Date(`${t}T00:00:00.000Z`)):Nn("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)},Ph=d.createContext(null);function yx({children:t,locale:s}){const i=d.useMemo(()=>({locale:s,t:(a,n)=>Nn(s,a,n),formatDate:a=>a?new Intl.DateTimeFormat(s,{month:"short",day:"numeric"}).format(new Date(`${a}T00:00:00.000Z`)):Nn(s,"common.labels.noDate"),formatDateTime:a=>new Intl.DateTimeFormat(s,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(a)),formatNumber:a=>new Intl.NumberFormat(s).format(a)}),[s]);return e.jsx(Ph.Provider,{value:i,children:t})}function lt(){return d.useContext(Ph)??wx}function Vo({active:t,label:s,className:i,onClick:a}){const{t:n}=lt();return e.jsxs(Kt.button,{type:"button",initial:!1,animate:{opacity:t?1:.55,y:0,scale:t?1:.98},transition:{duration:.24,ease:"easeOut"},onClick:a,className:re("surface-pulse ambient-glow inline-flex min-h-11 shrink-0 items-center gap-2.5 rounded-full border border-white/8 px-4 py-2 text-left shadow-[0_18px_40px_rgba(3,8,18,0.22)] backdrop-blur-xl transition hover:border-white/14 hover:bg-white/[0.03]",a?"cursor-pointer":"cursor-default",i),"aria-live":"polite","aria-label":`${n("common.labels.backgroundActivity")}: ${s}`,children:[e.jsx(Fl,{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:n("common.labels.backgroundActivity")}),e.jsx("span",{className:"text-white/30",children:"•"}),e.jsx("span",{className:"truncate text-sm text-white/80",children:s})]})]})}function L({className:t,tone:s="default",size:i="md",wrap:a=!1,...n}){return e.jsx("span",{className:re("inline-flex max-w-full items-center rounded-full border border-white/8 bg-white/6 font-medium text-white/78",a?"whitespace-normal break-words [overflow-wrap:anywhere]":"overflow-hidden text-ellipsis whitespace-nowrap",i==="sm"?"min-h-7 px-2.5 py-1 text-[12px]":"min-h-8 px-3 py-1.5 text-[12px]",s==="meta"&&"bg-white/[0.04] text-white/58",s==="signal"&&"bg-[rgba(192,193,255,0.12)] text-white/86",t),...n})}const jx=["goal","project","task","strategy","habit","value","pattern","behavior","belief","mode","report"],Nx={goal:{kind:"goal",label:"Goal",icon:Fn,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:$u,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:Du,iconClassName:"text-indigo-100",nameClassName:"text-indigo-100",badgeClassName:"border-indigo-300/24 bg-[linear-gradient(135deg,rgba(129,140,248,0.22),rgba(129,140,248,0.08))] text-indigo-50",subtleBadgeClassName:"border-indigo-300/18 bg-[rgba(129,140,248,0.08)] text-indigo-100",buttonClassName:"border-indigo-300/20 bg-[rgba(129,140,248,0.12)] text-indigo-50 hover:bg-[rgba(129,140,248,0.18)]"},strategy:{kind:"strategy",label:"Strategy",icon:fl,iconClassName:"text-cyan-100",nameClassName:"text-cyan-100",badgeClassName:"border-cyan-300/24 bg-[linear-gradient(135deg,rgba(34,211,238,0.22),rgba(34,211,238,0.08))] text-cyan-50",subtleBadgeClassName:"border-cyan-300/18 bg-[rgba(34,211,238,0.08)] text-cyan-100",buttonClassName:"border-cyan-300/20 bg-[rgba(34,211,238,0.12)] text-cyan-50 hover:bg-[rgba(34,211,238,0.18)]"},habit:{kind:"habit",label:"Habit",icon:Lu,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:Eu,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:gl,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:On,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:Au,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:Mu,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:xl,iconClassName:"text-blue-100",nameClassName:"text-blue-100",badgeClassName:"border-blue-300/24 bg-[linear-gradient(135deg,rgba(96,165,250,0.24),rgba(96,165,250,0.08))] text-blue-50",subtleBadgeClassName:"border-blue-300/18 bg-[rgba(96,165,250,0.08)] text-blue-100",buttonClassName:"border-blue-300/20 bg-[rgba(96,165,250,0.12)] text-blue-50 hover:bg-[rgba(96,165,250,0.18)]"}};function Ts(t){return Nx[t]}function kx(t){return jx.includes(t)}function ja(t,s){const i=Ts(t);return s?`border ${i.buttonClassName}`:"border border-white/8 bg-white/[0.05] text-white/62 hover:bg-white/[0.08] hover:text-white"}function Te({kind:t,label:s,compact:i=!1,showIcon:a=!0,iconOnly:n=!1,gradient:r=!0,wrap:l=!1,className:o,...c}){const x=Ts(t),v=x.icon;return e.jsxs(L,{size:i?"sm":"md",wrap:l,className:re("max-w-full min-w-0 gap-1.5 border font-medium",r?x.badgeClassName:x.subtleBadgeClassName,i&&!n&&"px-2.5",n&&"px-2.5",o),...c,children:[a?e.jsx(v,{className:re("size-3.5 shrink-0",x.iconClassName)}):null,n?null:e.jsx("span",{className:re("min-w-0 max-w-full",l?"whitespace-normal break-words [overflow-wrap:anywhere]":"truncate"),children:s??x.label})]})}const Sx={sm:"text-base",md:"text-lg",lg:"text-2xl",xl:"text-3xl"},dr={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 Xe({kind:t,label:s,variant:i="inline",size:a="md",showKind:n=!1,showIcon:r=!0,showBadge:l=!1,badgeLabel:o,badgeCompact:c=!0,badgeGradient:x=!1,lines:v=1,labelClassName:u,className:f,...h}){const m=Ts(t),b=m.icon;return i==="pill"?e.jsxs("span",{className:re("inline-flex max-w-full items-center gap-2 rounded-full border px-4 py-2 font-medium shadow-[0_10px_28px_rgba(3,8,18,0.18)]",m.badgeClassName,f),...h,children:[r?e.jsx(b,{className:re("size-4 shrink-0",m.iconClassName)}):null,e.jsx("span",{className:re("min-w-0 max-w-full",dr[v],u),children:s})]}):i==="heading"?e.jsxs("span",{className:re("inline-flex max-w-full min-w-0 items-center gap-3",f),...h,children:[l?e.jsx(Te,{kind:t,label:o??m.label,compact:c,gradient:x,className:"shrink-0"}):null,n&&!l?e.jsx(Te,{kind:t,label:o??m.label,compact:!0,gradient:!1,className:"shrink-0"}):null,e.jsx("span",{className:re("min-w-0 max-w-full font-display leading-tight",Sx[a],dr[v],m.nameClassName,u),children:s})]}):e.jsxs("span",{className:re("inline-flex max-w-full min-w-0 items-center gap-2",f),...h,children:[r?e.jsx(b,{className:re("size-4 shrink-0",m.iconClassName)}):null,l?e.jsx(Te,{kind:t,label:o??m.label,compact:c,gradient:x,className:"shrink-0"}):null,n?e.jsx("span",{className:re("text-sm font-medium",m.nameClassName),children:m.label}):null,e.jsx("span",{className:re("min-w-0 max-w-full",dr[v],m.nameClassName,u),children:s})]})}function le({className:t,size:s,...i}){return e.jsx("input",{...i,className:re("interactive-tap w-full rounded-[22px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none ring-0 placeholder:text-white/35 focus:border-[rgba(192,193,255,0.35)]",t)})}class Ea extends Error{constructor(i){super(i.message);ra(this,"status");ra(this,"code");ra(this,"details");ra(this,"requestPath");this.name="ForgeApiError",this.status=i.status,this.code=i.code,this.details=i.details??[],this.requestPath=i.requestPath}}function Cx(t){return t instanceof Ea?{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 Mh(t){const s=t.startsWith("/")?t:`/${t}`;return s.endsWith("/")?s:`${s}/`}function Ix(t){const s=Mh(t);return s==="/"?"/":s.endsWith("/")?s.slice(0,-1):s}function Tx(){return new URL(Mh("/forge/"),window.location.origin)}function ui(t){if(t.startsWith("/api/"))return t;const s=t.startsWith("/")?t.slice(1):t;return new URL(s,Tx()).pathname}function Xr(t,s=0){return t===null||typeof t=="boolean"||typeof t=="number"||typeof t=="string"?t:typeof t=="bigint"?t.toString():t instanceof Error?{name:t.name,message:t.message,stack:t.stack??null}:Array.isArray(t)?s>=3?`[Array(${t.length})]`:t.slice(0,20).map(i=>Xr(i,s+1)):t&&typeof t=="object"?s>=3?"[Object]":Object.fromEntries(Object.entries(t).slice(0,30).map(([i,a])=>[i,Xr(a,s+1)])):String(t)}function Px(t){return t?Object.fromEntries(Object.entries(t).map(([s,i])=>[s,Xr(i)])):{}}async function kn(t){try{await fetch(ui("/api/v1/diagnostics/logs"),{method:"POST",credentials:"same-origin",keepalive:!0,headers:{"content-type":"application/json","x-forge-source":"ui"},body:JSON.stringify({...t,source:t.source??"ui",details:Px(t.details)})})}catch{}}function Mx(t){return s=>kn({...t,...s})}const Ax={allowWorkBlockKinds:[],blockWorkBlockKinds:[],allowCalendarIds:[],blockCalendarIds:[],allowEventTypes:[],blockEventTypes:[],allowEventKeywords:[],blockEventKeywords:[],allowAvailability:[],blockAvailability:[]};function $s(t){return{id:(t==null?void 0:t.id)??"",title:(t==null?void 0:t.title)??"",description:(t==null?void 0:t.description)??"",status:(t==null?void 0:t.status)??"backlog",priority:(t==null?void 0:t.priority)??"medium",owner:(t==null?void 0:t.owner)??"Albert",goalId:(t==null?void 0:t.goalId)??null,projectId:(t==null?void 0:t.projectId)??null,dueDate:(t==null?void 0:t.dueDate)??null,effort:(t==null?void 0:t.effort)??"deep",energy:(t==null?void 0:t.energy)??"steady",points:(t==null?void 0:t.points)??0,plannedDurationSeconds:(t==null?void 0:t.plannedDurationSeconds)??null,schedulingRules:(t==null?void 0:t.schedulingRules)??null,sortOrder:(t==null?void 0:t.sortOrder)??0,completedAt:(t==null?void 0:t.completedAt)??null,createdAt:(t==null?void 0:t.createdAt)??new Date(0).toISOString(),updatedAt:(t==null?void 0:t.updatedAt)??new Date(0).toISOString(),tagIds:(t==null?void 0:t.tagIds)??[],userId:(t==null?void 0:t.userId)??null,user:(t==null?void 0:t.user)??null,time:(t==null?void 0:t.time)??{totalTrackedSeconds:0,totalCreditedSeconds:0,liveTrackedSeconds:0,liveCreditedSeconds:0,manualAdjustedSeconds:0,activeRunCount:0,hasCurrentRun:!1,currentRunId:null}}}function cr(t){return{id:(t==null?void 0:t.id)??"",title:(t==null?void 0:t.title)??"",description:(t==null?void 0:t.description)??"",horizon:(t==null?void 0:t.horizon)==="quarter"||(t==null?void 0:t.horizon)==="lifetime"?t.horizon:"year",status:(t==null?void 0:t.status)==="paused"||(t==null?void 0:t.status)==="completed"?t.status:"active",targetPoints:(t==null?void 0:t.targetPoints)??0,themeColor:(t==null?void 0:t.themeColor)??"#c8a46b",createdAt:(t==null?void 0:t.createdAt)??new Date(0).toISOString(),updatedAt:(t==null?void 0:t.updatedAt)??new Date(0).toISOString(),tagIds:(t==null?void 0:t.tagIds)??[],userId:(t==null?void 0:t.userId)??null,user:(t==null?void 0:t.user)??null}}function hr(t){return{id:(t==null?void 0:t.id)??"",name:(t==null?void 0:t.name)??"",kind:(t==null?void 0:t.kind)==="value"||(t==null?void 0:t.kind)==="execution"?t.kind:"category",color:(t==null?void 0:t.color)??"#71717a",description:(t==null?void 0:t.description)??"",userId:(t==null?void 0:t.userId)??null,user:(t==null?void 0:t.user)??null}}function mr(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)??Ax,createdAt:(t==null?void 0:t.createdAt)??new Date(0).toISOString(),updatedAt:(t==null?void 0:t.updatedAt)??new Date(0).toISOString(),goalTitle:(t==null?void 0:t.goalTitle)??"",activeTaskCount:(t==null?void 0:t.activeTaskCount)??0,completedTaskCount:(t==null?void 0:t.completedTaskCount)??0,totalTasks:(t==null?void 0:t.totalTasks)??0,earnedPoints:(t==null?void 0:t.earnedPoints)??(t==null?void 0:t.totalPoints)??0,progress:(t==null?void 0:t.progress)??0,nextTaskId:(t==null?void 0:t.nextTaskId)??null,nextTaskTitle:(t==null?void 0:t.nextTaskTitle)??null,momentumLabel:(t==null?void 0:t.momentumLabel)??"No momentum yet",userId:(t==null?void 0:t.userId)??null,user:(t==null?void 0:t.user)??null,time:(t==null?void 0:t.time)??{totalTrackedSeconds:0,totalCreditedSeconds:0,liveTrackedSeconds:0,liveCreditedSeconds:0,manualAdjustedSeconds:0,activeRunCount:0,hasCurrentRun:!1,currentRunId:null}}}function qa(t){return{id:(t==null?void 0:t.id)??"",title:(t==null?void 0:t.title)??"",description:(t==null?void 0:t.description)??"",status:(t==null?void 0:t.status)??"active",polarity:(t==null?void 0:t.polarity)??"positive",frequency:(t==null?void 0:t.frequency)??"daily",targetCount:(t==null?void 0:t.targetCount)??1,weekDays:(t==null?void 0:t.weekDays)??[],linkedGoalIds:(t==null?void 0:t.linkedGoalIds)??[],linkedProjectIds:(t==null?void 0:t.linkedProjectIds)??[],linkedTaskIds:(t==null?void 0:t.linkedTaskIds)??[],linkedValueIds:(t==null?void 0:t.linkedValueIds)??[],linkedPatternIds:(t==null?void 0:t.linkedPatternIds)??[],linkedBehaviorIds:(t==null?void 0:t.linkedBehaviorIds)??[],linkedBeliefIds:(t==null?void 0:t.linkedBeliefIds)??[],linkedModeIds:(t==null?void 0:t.linkedModeIds)??[],linkedReportIds:(t==null?void 0:t.linkedReportIds)??[],linkedBehaviorId:(t==null?void 0:t.linkedBehaviorId)??null,linkedBehaviorTitle:(t==null?void 0:t.linkedBehaviorTitle)??null,linkedBehaviorTitles:(t==null?void 0:t.linkedBehaviorTitles)??[],rewardXp:(t==null?void 0:t.rewardXp)??12,penaltyXp:(t==null?void 0:t.penaltyXp)??8,generatedHealthEventTemplate:(t==null?void 0:t.generatedHealthEventTemplate)??{enabled:!1,workoutType:"",title:"",durationMinutes:60,xpReward:0,tags:[],links:[],notesTemplate:""},createdAt:(t==null?void 0:t.createdAt)??new Date(0).toISOString(),updatedAt:(t==null?void 0:t.updatedAt)??new Date(0).toISOString(),lastCheckInAt:(t==null?void 0:t.lastCheckInAt)??null,lastCheckInStatus:(t==null?void 0:t.lastCheckInStatus)??null,streakCount:(t==null?void 0:t.streakCount)??0,completionRate:(t==null?void 0:t.completionRate)??0,dueToday:(t==null?void 0:t.dueToday)??!1,userId:(t==null?void 0:t.userId)??null,user:(t==null?void 0:t.user)??null,checkIns:(t==null?void 0:t.checkIns)??[]}}function Jo(t){return{id:(t==null?void 0:t.id)??"",kind:(t==null?void 0:t.kind)??"human",handle:(t==null?void 0:t.handle)??"",displayName:(t==null?void 0:t.displayName)??"",description:(t==null?void 0:t.description)??"",accentColor:(t==null?void 0:t.accentColor)??"#c0c1ff",createdAt:(t==null?void 0:t.createdAt)??new Date(0).toISOString(),updatedAt:(t==null?void 0:t.updatedAt)??new Date(0).toISOString()}}function Ex(t){return{id:(t==null?void 0:t.id)??"",title:(t==null?void 0:t.title)??"",overview:(t==null?void 0:t.overview)??"",endStateDescription:(t==null?void 0:t.endStateDescription)??"",status:(t==null?void 0:t.status)==="paused"||(t==null?void 0:t.status)==="completed"?t.status:"active",targetGoalIds:(t==null?void 0:t.targetGoalIds)??[],targetProjectIds:(t==null?void 0:t.targetProjectIds)??[],linkedEntities:(t==null?void 0:t.linkedEntities)??[],graph:(t==null?void 0:t.graph)??{nodes:[],edges:[]},metrics:(t==null?void 0:t.metrics)??{alignmentScore:0,planCoverageScore:0,sequencingScore:100,scopeDisciplineScore:100,qualityScore:0,targetProgressScore:0,completedNodeCount:0,startedNodeCount:0,readyNodeCount:0,totalNodeCount:1,completedTargetCount:0,totalTargetCount:0,offPlanEntityCount:0,offPlanActiveEntityCount:0,offPlanCompletedEntityCount:0,activeNodeIds:[],nextNodeIds:[],blockedNodeIds:[],outOfOrderNodeIds:[]},isLocked:(t==null?void 0:t.isLocked)??!1,lockedAt:(t==null?void 0:t.lockedAt)??null,lockedByUserId:(t==null?void 0:t.lockedByUserId)??null,lockedByUser:(t==null?void 0:t.lockedByUser)??null,createdAt:(t==null?void 0:t.createdAt)??new Date(0).toISOString(),updatedAt:(t==null?void 0:t.updatedAt)??new Date(0).toISOString(),userId:(t==null?void 0:t.userId)??null,user:(t==null?void 0:t.user)??null}}function Lx(t){var r,l,o,c,x,v,u,f,h,m,b,w,M,E,D,j,S,p,A,T,k,$,g,C,F,z,J,O,_,B,K,Z,U,I,G,W,ne,de,we,Ne,H,me,y,P,q,pe,ee,Y,R,X,be,Ie,te,ce,Se,he,Ge,De,ue,Fe,dt,yt,wt,kt,Qt,oe,ke,$e,Ye,Pe,ve,Ee,Oe,tt,Qe,St,Le,pt,_t,Jt,ws,Js,Ys,Zs,N,V,ge,ye,Ce,xt,Ds,ys,ia,aa,na,vo,wo,yo,jo,No,ko,So,Co,Io,To,Po,Mo,Ao,Eo,Lo,Do,$o,Oo,Fo,_o;const s=t,i=(s.projects??s.campaigns??[]).map(mr),a=(((r=s.dashboard)==null?void 0:r.projects)??((l=s.dashboard)==null?void 0:l.campaigns)??i).map(mr),n=(((o=s.overview)==null?void 0:o.projects)??((c=s.overview)==null?void 0:c.campaigns)??a).map(mr);return{...t,meta:{apiVersion:"v1",transport:"rest+sse",generatedAt:((x=t.meta)==null?void 0:x.generatedAt)??new Date().toISOString(),backend:((v=t.meta)==null?void 0:v.backend)??"forge-node-runtime",mode:((u=t.meta)==null?void 0:u.mode)??"transitional-node"},metrics:{totalXp:((f=t.metrics)==null?void 0:f.totalXp)??0,level:((h=t.metrics)==null?void 0:h.level)??1,currentLevelXp:((m=t.metrics)==null?void 0:m.currentLevelXp)??0,nextLevelXp:((b=t.metrics)==null?void 0:b.nextLevelXp)??120,weeklyXp:((w=t.metrics)==null?void 0:w.weeklyXp)??0,streakDays:((M=t.metrics)==null?void 0:M.streakDays)??0,comboMultiplier:((E=t.metrics)==null?void 0:E.comboMultiplier)??1,momentumScore:((D=t.metrics)==null?void 0:D.momentumScore)??0,topGoalId:((j=t.metrics)==null?void 0:j.topGoalId)??null,topGoalTitle:((S=t.metrics)==null?void 0:S.topGoalTitle)??null},users:(t.users??[]).map(Jo),strategies:(t.strategies??[]).map(Ex),userScope:{selectedUserIds:((p=t.userScope)==null?void 0:p.selectedUserIds)??[],selectedUsers:(((A=t.userScope)==null?void 0:A.selectedUsers)??[]).map(Jo)},dashboard:{stats:{totalPoints:((k=(T=t.dashboard)==null?void 0:T.stats)==null?void 0:k.totalPoints)??0,completedThisWeek:((g=($=t.dashboard)==null?void 0:$.stats)==null?void 0:g.completedThisWeek)??0,activeGoals:((F=(C=t.dashboard)==null?void 0:C.stats)==null?void 0:F.activeGoals)??0,alignmentScore:((J=(z=t.dashboard)==null?void 0:z.stats)==null?void 0:J.alignmentScore)??0,focusTasks:((_=(O=t.dashboard)==null?void 0:O.stats)==null?void 0:_.focusTasks)??0,overdueTasks:((K=(B=t.dashboard)==null?void 0:B.stats)==null?void 0:K.overdueTasks)??0,dueThisWeek:((U=(Z=t.dashboard)==null?void 0:Z.stats)==null?void 0:U.dueThisWeek)??0},goals:(((I=t.dashboard)==null?void 0:I.goals)??[]).map(as=>({...as,...cr(as)})),projects:a,tasks:(((G=t.dashboard)==null?void 0:G.tasks)??[]).map($s),habits:(((W=t.dashboard)==null?void 0:W.habits)??t.habits??[]).map(qa),tags:(((ne=t.dashboard)==null?void 0:ne.tags)??[]).map(hr),suggestedTags:(((de=t.dashboard)==null?void 0:de.suggestedTags)??[]).map(hr),owners:((we=t.dashboard)==null?void 0:we.owners)??[],executionBuckets:(((Ne=t.dashboard)==null?void 0:Ne.executionBuckets)??[]).map(as=>({...as,tasks:(as.tasks??[]).map($s)})),gamification:((H=t.dashboard)==null?void 0:H.gamification)??{totalXp:((me=t.metrics)==null?void 0:me.totalXp)??0,level:((y=t.metrics)==null?void 0:y.level)??1,currentLevelXp:((P=t.metrics)==null?void 0:P.currentLevelXp)??0,nextLevelXp:((q=t.metrics)==null?void 0:q.nextLevelXp)??120,weeklyXp:((pe=t.metrics)==null?void 0:pe.weeklyXp)??0,streakDays:((ee=t.metrics)==null?void 0:ee.streakDays)??0,comboMultiplier:((Y=t.metrics)==null?void 0:Y.comboMultiplier)??1,momentumScore:((R=t.metrics)==null?void 0:R.momentumScore)??0,topGoalId:((X=t.metrics)==null?void 0:X.topGoalId)??null,topGoalTitle:((be=t.metrics)==null?void 0:be.topGoalTitle)??null},achievements:((Ie=t.dashboard)==null?void 0:Ie.achievements)??[],milestoneRewards:((te=t.dashboard)==null?void 0:te.milestoneRewards)??[],recentActivity:((ce=t.dashboard)==null?void 0:ce.recentActivity)??[],notesSummaryByEntity:((Se=t.dashboard)==null?void 0:Se.notesSummaryByEntity)??{}},overview:{generatedAt:((he=t.overview)==null?void 0:he.generatedAt)??new Date().toISOString(),strategicHeader:{streakDays:((De=(Ge=t.overview)==null?void 0:Ge.strategicHeader)==null?void 0:De.streakDays)??((ue=t.metrics)==null?void 0:ue.streakDays)??0,level:((dt=(Fe=t.overview)==null?void 0:Fe.strategicHeader)==null?void 0:dt.level)??((yt=t.metrics)==null?void 0:yt.level)??1,totalXp:((kt=(wt=t.overview)==null?void 0:wt.strategicHeader)==null?void 0:kt.totalXp)??((Qt=t.metrics)==null?void 0:Qt.totalXp)??0,currentLevelXp:((ke=(oe=t.overview)==null?void 0:oe.strategicHeader)==null?void 0:ke.currentLevelXp)??(($e=t.metrics)==null?void 0:$e.currentLevelXp)??0,nextLevelXp:((Pe=(Ye=t.overview)==null?void 0:Ye.strategicHeader)==null?void 0:Pe.nextLevelXp)??((ve=t.metrics)==null?void 0:ve.nextLevelXp)??120,momentumScore:((Oe=(Ee=t.overview)==null?void 0:Ee.strategicHeader)==null?void 0:Oe.momentumScore)??((tt=t.metrics)==null?void 0:tt.momentumScore)??0,focusTasks:((St=(Qe=t.overview)==null?void 0:Qe.strategicHeader)==null?void 0:St.focusTasks)??0,overdueTasks:((pt=(Le=t.overview)==null?void 0:Le.strategicHeader)==null?void 0:pt.overdueTasks)??0},projects:n,activeGoals:(((_t=t.overview)==null?void 0:_t.activeGoals)??[]).map(as=>({...as,...cr(as)})),topTasks:(((Jt=t.overview)==null?void 0:Jt.topTasks)??[]).map($s),dueHabits:(((ws=t.overview)==null?void 0:ws.dueHabits)??((Js=t.today)==null?void 0:Js.dueHabits)??((Ys=t.dashboard)==null?void 0:Ys.habits)??[]).map(qa),recentEvidence:((Zs=t.overview)==null?void 0:Zs.recentEvidence)??[],achievements:((N=t.overview)==null?void 0:N.achievements)??[],domainBalance:((V=t.overview)==null?void 0:V.domainBalance)??[],neglectedGoals:((ge=t.overview)==null?void 0:ge.neglectedGoals)??[]},today:{generatedAt:((ye=t.today)==null?void 0:ye.generatedAt)??new Date().toISOString(),directive:{task:(xt=(Ce=t.today)==null?void 0:Ce.directive)!=null&&xt.task?$s(t.today.directive.task):null,goalTitle:((ys=(Ds=t.today)==null?void 0:Ds.directive)==null?void 0:ys.goalTitle)??null,rewardXp:((aa=(ia=t.today)==null?void 0:ia.directive)==null?void 0:aa.rewardXp)??0,sessionLabel:((vo=(na=t.today)==null?void 0:na.directive)==null?void 0:vo.sessionLabel)??"No active session"},timeline:(((wo=t.today)==null?void 0:wo.timeline)??[]).map(as=>({...as,tasks:(as.tasks??[]).map($s)})),dueHabits:(((yo=t.today)==null?void 0:yo.dueHabits)??((jo=t.overview)==null?void 0:jo.dueHabits)??((No=t.dashboard)==null?void 0:No.habits)??[]).map(qa),dailyQuests:((ko=t.today)==null?void 0:ko.dailyQuests)??[],milestoneRewards:((So=t.today)==null?void 0:So.milestoneRewards)??[],recentHabitRewards:((Co=t.today)==null?void 0:Co.recentHabitRewards)??[],momentum:{streakDays:((To=(Io=t.today)==null?void 0:Io.momentum)==null?void 0:To.streakDays)??0,momentumScore:((Mo=(Po=t.today)==null?void 0:Po.momentum)==null?void 0:Mo.momentumScore)??0,recoveryHint:((Eo=(Ao=t.today)==null?void 0:Ao.momentum)==null?void 0:Eo.recoveryHint)??""}},risk:{generatedAt:((Lo=t.risk)==null?void 0:Lo.generatedAt)??new Date().toISOString(),overdueTasks:(((Do=t.risk)==null?void 0:Do.overdueTasks)??[]).map($s),blockedTasks:((($o=t.risk)==null?void 0:$o.blockedTasks)??[]).map($s),neglectedGoals:((Oo=t.risk)==null?void 0:Oo.neglectedGoals)??[],summary:((Fo=t.risk)==null?void 0:Fo.summary)??""},goals:(t.goals??[]).map(cr),projects:i,tags:(t.tags??[]).map(hr),tasks:(t.tasks??[]).map($s),habits:(t.habits??((_o=t.dashboard)==null?void 0:_o.habits)??[]).map(qa),activity:t.activity??[],activeTaskRuns:t.activeTaskRuns??[]}}function _l(t){const s=typeof t.location=="string"?t.location:"",i=t.place??{label:s,address:"",timezone:"",latitude:null,longitude:null,source:"",externalPlaceId:""};return{...t,place:{label:i.label||s,address:i.address??"",timezone:i.timezone??"",latitude:i.latitude??null,longitude:i.longitude??null,source:i.source??"",externalPlaceId:i.externalPlaceId??""}}}function Dx(t){return{...t,events:t.events.map(_l)}}async function $x(t){const s=await t.text();if(!s)return null;try{return JSON.parse(s)}catch{return s}}async function ie(t,s){const i=new Headers(s==null?void 0:s.headers);i.set("x-forge-source","ui"),(s==null?void 0:s.body)!==void 0&&!(typeof FormData<"u"&&s.body instanceof FormData)&&!i.has("content-type")&&i.set("content-type","application/json");let a;try{a=await fetch(ui(t),{credentials:"same-origin",headers:i,...s})}catch(r){throw t!=="/api/v1/diagnostics/logs"&&kn({level:"error",scope:"frontend_api",eventKey:"request_network_failure",message:`API request failed before reaching Forge: ${t}`,route:t,functionName:"request",details:{error:r instanceof Error?{name:r.name,message:r.message,stack:r.stack??null}:String(r)}}),r}const n=await $x(a);if(!a.ok){const r=typeof n=="object"&&n!==null?n:null,l=Array.isArray(r==null?void 0:r.details)?r.details:[];throw t!=="/api/v1/diagnostics/logs"&&kn({level:a.status>=500?"error":"warning",scope:"frontend_api",eventKey:"request_failed",message:`API request failed: ${t}`,route:t,functionName:"request",details:{statusCode:a.status,code:typeof(r==null?void 0:r.code)=="string"?r.code:typeof(r==null?void 0:r.error)=="string"?r.error:"request_failed",response:typeof n=="string"||n&&typeof n=="object"?n:null,validationIssues:l}}),new Ea({status:a.status,code:typeof(r==null?void 0:r.code)=="string"?r.code:typeof(r==null?void 0:r.error)=="string"?r.error:"request_failed",message:typeof(r==null?void 0:r.error)=="string"?r.error:typeof(r==null?void 0:r.message)=="string"?r.message:typeof n=="string"?n:`Request failed: ${a.status}`,requestPath:t,details:l})}return n}function Rl(t){return t.map(s=>({contentMarkdown:s.contentMarkdown.trim(),author:s.author.trim()||null})).filter(s=>s.contentMarkdown.length>0)}const Ox="forge.selected-user-ids";function Fx(){if(typeof window>"u")return[];try{const t=window.localStorage.getItem(Ox);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean):[]}catch{return[]}}function _x(t){return t??Fx()}function ot(t){return Array.isArray(t)?t.filter(s=>typeof s=="string"):void 0}function at(t,s){for(const i of _x(s))i.trim()&&t.append("userIds",i.trim())}function Zi(){return ie("/api/v1/auth/operator-session")}function Rx(){return ie("/api/v1/auth/operator-session",{method:"DELETE"})}function zx(t){const s=new URLSearchParams;at(s,ot(t));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/context${i}`).then(Lx)}function Yo(t){const s=new URLSearchParams;t.userId&&s.set("userId",t.userId),t.domain&&s.set("domain",t.domain),t.contextId&&s.set("contextId",t.contextId);const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/preferences/workspace${i}`)}function qx(t){return ie("/api/v1/preferences/game/start",{method:"POST",body:JSON.stringify(t)})}function Bx(t){return ie("/api/v1/preferences/catalogs",{method:"POST",body:JSON.stringify(t)})}function Kx(t,s){return ie(`/api/v1/preferences/catalogs/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Ux(t){return ie(`/api/v1/preferences/catalogs/${t}`,{method:"DELETE"})}function Qx(t){return ie("/api/v1/preferences/catalog-items",{method:"POST",body:JSON.stringify(t)})}function Wx(t,s){return ie(`/api/v1/preferences/catalog-items/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Hx(t){return ie(`/api/v1/preferences/catalog-items/${t}`,{method:"DELETE"})}function Gx(t){return ie("/api/v1/preferences/contexts",{method:"POST",body:JSON.stringify(t)})}function Xx(t,s){return ie(`/api/v1/preferences/contexts/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Vx(t){return ie("/api/v1/preferences/contexts/merge",{method:"POST",body:JSON.stringify(t)})}function Jx(t){return ie("/api/v1/preferences/items",{method:"POST",body:JSON.stringify(t)})}function Yx(t,s){return ie(`/api/v1/preferences/items/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Vr(t){return ie("/api/v1/preferences/items/from-entity",{method:"POST",body:JSON.stringify(t)})}function Zx(t){return ie("/api/v1/preferences/judgments",{method:"POST",body:JSON.stringify(t)})}function eg(t){return ie("/api/v1/preferences/signals",{method:"POST",body:JSON.stringify(t)})}function tg(t,s){return ie(`/api/v1/preferences/items/${t}/score`,{method:"PATCH",body:JSON.stringify(s)})}function sg(t){const s=new URLSearchParams;at(s,ot(t));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/insights${i}`)}function Wn(t){const s=new URLSearchParams;at(s,ot(t));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/psyche/overview${i}`)}function Ah(t){const s=new URLSearchParams;at(s,ot(t));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/psyche/questionnaires${i}`)}function Eh(t,s){const i=new URLSearchParams;at(i,ot(s));const a=i.size>0?`?${i.toString()}`:"";return ie(`/api/v1/psyche/questionnaires/${t}${a}`)}function ig(t){return ie("/api/v1/psyche/questionnaires",{method:"POST",body:JSON.stringify(t)})}function ag(t,s={}){return ie(`/api/v1/psyche/questionnaires/${t}/clone`,{method:"POST",body:JSON.stringify(s)})}function ng(t){return ie(`/api/v1/psyche/questionnaires/${t}/draft`,{method:"POST",body:JSON.stringify({})})}function rg(t,s){return ie(`/api/v1/psyche/questionnaires/${t}/draft`,{method:"PATCH",body:JSON.stringify(s)})}function lg(t,s={}){return ie(`/api/v1/psyche/questionnaires/${t}/publish`,{method:"POST",body:JSON.stringify(s)})}function og(t,s={}){return ie(`/api/v1/psyche/questionnaires/${t}/runs`,{method:"POST",body:JSON.stringify(s)})}function dg(t,s){const i=new URLSearchParams;at(i,ot(s));const a=i.size>0?`?${i.toString()}`:"";return ie(`/api/v1/psyche/questionnaire-runs/${t}${a}`)}function cg(t,s){return ie(`/api/v1/psyche/questionnaire-runs/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function hg(t){return ie(`/api/v1/psyche/questionnaire-runs/${t}/complete`,{method:"POST",body:JSON.stringify({})})}function ps(t){const s=new URLSearchParams;at(s,ot(t));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/psyche/values${i}`)}function ea(t){return ie("/api/v1/psyche/values",{method:"POST",body:JSON.stringify(t)})}function mg(t,s){return ie(`/api/v1/psyche/values/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Vs(t){const s=new URLSearchParams;at(s,ot(t));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/psyche/patterns${i}`)}function zl(t){return ie("/api/v1/psyche/patterns",{method:"POST",body:JSON.stringify(t)})}function ug(t,s){return ie(`/api/v1/psyche/patterns/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function xs(t){const s=new URLSearchParams;at(s,ot(t));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/psyche/behaviors${i}`)}function Hn(t){return ie("/api/v1/psyche/behaviors",{method:"POST",body:JSON.stringify(t)})}function pg(t,s){return ie(`/api/v1/psyche/behaviors/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function La(){return ie("/api/v1/psyche/schema-catalog")}function As(t){const s=new URLSearchParams;at(s,ot(t));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/psyche/beliefs${i}`)}function ql(t){return ie("/api/v1/psyche/beliefs",{method:"POST",body:JSON.stringify(t)})}function xg(t,s){return ie(`/api/v1/psyche/beliefs/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Es(t){const s=new URLSearchParams;at(s,ot(t));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/psyche/modes${i}`)}function Da(t){return ie("/api/v1/psyche/modes",{method:"POST",body:JSON.stringify(t)})}function gg(t,s){return ie(`/api/v1/psyche/modes/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function fg(){return ie("/api/v1/psyche/mode-guides")}function bg(t){return ie("/api/v1/psyche/mode-guides",{method:"POST",body:JSON.stringify(t)})}function Lh(){return ie("/api/v1/psyche/event-types")}function Dh(){return ie("/api/v1/psyche/emotions")}function bi(t){const s=new URLSearchParams;at(s,ot(t));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/psyche/reports${i}`)}function $h(t){return ie("/api/v1/psyche/reports",{method:"POST",body:JSON.stringify(t)})}function vg(t){return ie(`/api/v1/psyche/reports/${t}`)}function wg(t,s){return ie(`/api/v1/psyche/reports/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Oh(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 a of t.linkedTo??[])s.append("linkedTo",`${a.entityType}:${a.entityId}`);for(const a of t.tags??[])a.trim()&&s.append("tags",a.trim());for(const a of t.textTerms??[])a.trim()&&s.append("textTerms",a.trim());t.author&&s.set("author",t.author),t.query&&s.set("query",t.query),at(s,t.userIds),t.updatedFrom&&s.set("updatedFrom",t.updatedFrom),t.updatedTo&&s.set("updatedTo",t.updatedTo),t.limit&&s.set("limit",String(t.limit));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/notes${i}`)}function $a(t){return ie("/api/v1/notes",{method:"POST",body:JSON.stringify(t)})}function Zo(t){return ie(`/api/v1/notes/${t}`)}function Ta(t,s){return ie(`/api/v1/notes/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Bl(t,s="soft"){const i=s==="soft"?"":`?mode=${s}`;return ie(`/api/v1/notes/${t}${i}`,{method:"DELETE"})}function Gn(){return ie("/api/v1/wiki/settings")}function yg(t){return ie("/api/v1/wiki/spaces",{method:"POST",body:JSON.stringify(t)})}function jg(t={}){const s=new URLSearchParams;t.spaceId&&s.set("spaceId",t.spaceId),t.kind&&s.set("kind",t.kind),t.limit&&s.set("limit",String(t.limit));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/wiki/pages${i}`)}function Ng(t){return ie(`/api/v1/wiki/pages/${t}`)}function kg(t={}){var i;const s=new URLSearchParams;return(i=t.spaceId)!=null&&i.trim()&&s.set("spaceId",t.spaceId.trim()),ie(`/api/v1/wiki/home${s.size>0?`?${s.toString()}`:""}`)}function Sg(t){var i;const s=new URLSearchParams;return(i=t.spaceId)!=null&&i.trim()&&s.set("spaceId",t.spaceId.trim()),ie(`/api/v1/wiki/by-slug/${encodeURIComponent(t.slug)}${s.size>0?`?${s.toString()}`:""}`)}function Cg(t={}){var i;const s=new URLSearchParams;return(i=t.spaceId)!=null&&i.trim()&&s.set("spaceId",t.spaceId.trim()),t.kind&&s.set("kind",t.kind),ie(`/api/v1/wiki/tree${s.size>0?`?${s.toString()}`:""}`)}function Fh(t){return ie("/api/v1/wiki/pages",{method:"POST",body:JSON.stringify({kind:t.kind??"wiki",title:t.title,slug:t.slug??"",parentSlug:t.parentSlug??null,indexOrder:t.indexOrder??0,showInIndex:t.showInIndex??!0,aliases:t.aliases??[],summary:t.summary??"",contentMarkdown:t.contentMarkdown,author:t.author??null,tags:t.tags??[],spaceId:t.spaceId??"",frontmatter:t.frontmatter??{},links:t.links??[]})})}function Ig(t,s){return ie(`/api/v1/wiki/pages/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Tg(t,s="soft"){const i=new URLSearchParams;return i.set("mode",s),ie(`/api/v1/wiki/pages/${t}?${i.toString()}`,{method:"DELETE"})}function Pg(t){return ie("/api/v1/wiki/search",{method:"POST",body:JSON.stringify(t)})}function Mg(t={}){return ie("/api/v1/wiki/sync",{method:"POST",body:JSON.stringify(t)})}function Ag(t={}){return ie("/api/v1/wiki/reindex",{method:"POST",body:JSON.stringify(t)})}function Eg(t){return ie("/api/v1/wiki/settings/embedding-profiles",{method:"POST",body:JSON.stringify(t)})}function Lg(t,s){return ie(`/api/v1/wiki/settings/${t}-profiles/${s}`,{method:"DELETE"})}function ed(t){return ie("/api/v1/wiki/ingest-jobs",{method:"POST",body:JSON.stringify(t)})}function Dg(t){var i,a,n;const s=new FormData;return(i=t.spaceId)!=null&&i.trim()&&s.set("spaceId",t.spaceId.trim()),(a=t.titleHint)!=null&&a.trim()&&s.set("titleHint",t.titleHint.trim()),(n=t.llmProfileId)!=null&&n.trim()&&s.set("llmProfileId",t.llmProfileId.trim()),s.set("parseStrategy",t.parseStrategy??"auto"),s.set("entityProposalMode",t.entityProposalMode??"suggest"),s.set("createAsKind",t.createAsKind??"wiki"),s.set("linkedEntityHints",JSON.stringify(t.linkedEntityHints??[])),t.files.forEach(r=>{s.append("files",r)}),ie("/api/v1/wiki/ingest-jobs/uploads",{method:"POST",body:s})}function _h(t={}){var i;const s=new URLSearchParams;return(i=t.spaceId)!=null&&i.trim()&&s.set("spaceId",t.spaceId.trim()),typeof t.limit=="number"&&s.set("limit",String(t.limit)),ie(`/api/v1/wiki/ingest-jobs${s.size>0?`?${s.toString()}`:""}`)}function $g(t){return ie(`/api/v1/wiki/ingest-jobs/${t}`)}function Og(t){return ie("/api/v1/wiki/search",{method:"POST",body:JSON.stringify({spaceId:t.spaceId,kind:t.kind,mode:t.mode??"text",query:t.query??"",profileId:t.profileId,limit:t.limit??8})})}function Rh(t){return ie(`/api/v1/wiki/ingest-jobs/${t}`,{method:"DELETE"})}function Fg(t){return ie(`/api/v1/wiki/ingest-jobs/${t}/rerun`,{method:"POST"})}function _g(t){return ie(`/api/v1/wiki/ingest-jobs/${t}/resume`,{method:"POST"})}function Rg(t){return ie(`/api/v1/wiki/ingest-jobs/${t.jobId}/review`,{method:"POST",body:JSON.stringify({decisions:t.decisions})})}function zh(t){return ie("/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 zg(t){return ie(`/api/v1/insights/${t}`,{method:"DELETE"})}function td(t,s,i=""){return ie(`/api/v1/insights/${t}/feedback`,{method:"POST",body:JSON.stringify({feedbackType:s,note:i})})}function qg(){return ie("/api/v1/reviews/weekly")}function Bg(){return ie("/api/v1/reviews/weekly/finalize",{method:"POST"})}function Xn(t={}){const s=new URLSearchParams;t.from&&s.set("from",t.from),t.to&&s.set("to",t.to),at(s,ot(t.userIds));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/calendar/overview${i}`).then(a=>({...a,calendar:Dx(a.calendar)}))}function Kg(t={}){const s=new URLSearchParams;t.from&&s.set("from",t.from),t.to&&s.set("to",t.to),at(s,ot(t.userIds));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/psyche/self-observation/calendar${i}`)}function Ug(){return ie("/api/v1/calendar/connections")}function ur(t){return ie("/api/v1/calendar/discovery",{method:"POST",body:JSON.stringify(t)})}function Qg(t){return ie("/api/v1/calendar/oauth/microsoft/start",{method:"POST",body:JSON.stringify(t)})}function Wg(t){return ie("/api/v1/calendar/oauth/microsoft/test-config",{method:"POST",body:JSON.stringify(t)})}function Hg(t){return ie(`/api/v1/calendar/oauth/microsoft/session/${t}`)}function Gg(t){return ie(`/api/v1/calendar/connections/${t}/discovery`)}function Xg(t){return ie("/api/v1/calendar/connections",{method:"POST",body:JSON.stringify(t)})}function Vg(t){return ie(`/api/v1/calendar/connections/${t}/sync`,{method:"POST"})}function Jg(t,s){return ie(`/api/v1/calendar/connections/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Yg(t){return ie(`/api/v1/calendar/connections/${t}`,{method:"DELETE"})}function Zg(){return ie("/api/v1/calendar/calendars")}function ef(t){return ie("/api/v1/calendar/work-block-templates",{method:"POST",body:JSON.stringify(t)})}function tf(t,s){return ie(`/api/v1/calendar/work-block-templates/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function sf(t){return ie(`/api/v1/calendar/work-block-templates/${t}`,{method:"DELETE"})}function af(t){return ie("/api/v1/calendar/events",{method:"POST",body:JSON.stringify(t)}).then(s=>({...s,event:_l(s.event)}))}function nf(t,s){return ie(`/api/v1/calendar/events/${t}`,{method:"PATCH",body:JSON.stringify(s)}).then(i=>({...i,event:_l(i.event)}))}function rf(t){return ie(`/api/v1/calendar/events/${t}`,{method:"DELETE"})}function lf(t){return ie("/api/v1/calendar/timeboxes",{method:"POST",body:JSON.stringify(t)})}function of(t,s){return ie(`/api/v1/calendar/timeboxes/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function df(t){return ie("/api/v1/calendar/timeboxes/recommend",{method:"POST",body:JSON.stringify(t)})}function cf(t={}){const s=new URLSearchParams;at(s,t.userIds),t.status&&s.set("status",t.status),t.polarity&&s.set("polarity",t.polarity),t.dueToday&&s.set("dueToday","true"),t.limit&&s.set("limit",String(t.limit));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/habits${i}`)}function hf(t){return ie("/api/v1/habits",{method:"POST",body:JSON.stringify({...t,linkedBehaviorId:t.linkedBehaviorId||null})})}function mf(t,s){return ie(`/api/v1/habits/${t}`,{method:"PATCH",body:JSON.stringify({...s,linkedBehaviorId:s.linkedBehaviorId===""?null:s.linkedBehaviorId})})}function uf(t){return ie(`/api/v1/habits/${t}`,{method:"DELETE"})}function pf(t,s){return ie(`/api/v1/habits/${t}/check-ins`,{method:"POST",body:JSON.stringify(s)})}function xf(t,s){return ie(`/api/v1/habits/${t}/check-ins/${encodeURIComponent(s)}`,{method:"DELETE"})}function gf(t){return ie(`/api/v1/projects/${t}/board`)}function ff(){return ie("/api/v1/operator/context")}function vi(){return ie("/api/v1/settings")}function bf(t){return ie("/api/v1/settings/models/connections",{method:"POST",body:JSON.stringify(t)})}function vf(t){return ie(`/api/v1/settings/models/connections/${t}`,{method:"DELETE"})}function wf(t){return ie("/api/v1/settings/models/connections/test",{method:"POST",body:JSON.stringify(t)})}function yf(){return ie("/api/v1/settings/models/oauth/openai-codex/start",{method:"POST"})}function jf(t){return ie(`/api/v1/settings/models/oauth/openai-codex/session/${t}`)}function Nf(t,s){return ie(`/api/v1/settings/models/oauth/openai-codex/session/${t}/manual`,{method:"POST",body:JSON.stringify({codeOrUrl:s})})}function kf(t){return ie(`/api/v1/surfaces/${t}/layout`)}function Sf(t,s){return ie(`/api/v1/surfaces/${t}/layout`,{method:"PUT",body:JSON.stringify(s)})}function Cf(t){return ie(`/api/v1/surfaces/${t}/layout/reset`,{method:"POST"})}function If(){return ie("/api/v1/ai-connectors/catalog/boxes")}function Tf(){return ie("/api/v1/ai-connectors")}function Pf(t){return ie("/api/v1/ai-connectors",{method:"POST",body:JSON.stringify(t)})}function Mf(t){return ie(`/api/v1/ai-connectors/${t}`)}function Af(t,s){return ie(`/api/v1/ai-connectors/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Ef(t){return ie(`/api/v1/ai-connectors/${t}`,{method:"DELETE"})}function Lf(t,s){return ie(`/api/v1/ai-connectors/${t}/run`,{method:"POST",body:JSON.stringify(s)})}function Df(t,s){return ie(`/api/v1/ai-connectors/${t}/chat`,{method:"POST",body:JSON.stringify(s)})}function $f(t){const s=new URLSearchParams;at(s,ot(t));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/health/overview${i}`)}function Of(t){const s=new URLSearchParams;at(s,ot(t));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/health/sleep${i}`)}function Ff(t){const s=new URLSearchParams;at(s,ot(t));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/health/fitness${i}`)}function _f(t){const s=new URLSearchParams;t!=null&&t.date&&s.set("date",t.date),at(s,ot(t==null?void 0:t.userIds));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/movement/day${i}`)}function Rf(t){const s=new URLSearchParams;t!=null&&t.month&&s.set("month",t.month),at(s,ot(t==null?void 0:t.userIds));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/movement/month${i}`)}function zf(t){const s=new URLSearchParams;at(s,ot(t));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/movement/all-time${i}`)}function qf(t){const s=new URLSearchParams;at(s,ot(t));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/movement/settings${i}`)}function Bf(t,s){const i=new URLSearchParams;at(i,ot(s));const a=i.size>0?`?${i.toString()}`:"";return ie(`/api/v1/movement/settings${a}`,{method:"PATCH",body:JSON.stringify(t)})}function Kf(t){const s=new URLSearchParams;at(s,ot(t));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/movement/places${i}`)}function qh(t,s){const i=new URLSearchParams;at(i,ot(s));const a=i.size>0?`?${i.toString()}`:"";return ie(`/api/v1/movement/places${a}`,{method:"POST",body:JSON.stringify(t)})}function Uf(t,s){return ie(`/api/v1/movement/places/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Qf(t){return ie(`/api/v1/movement/trips/${t}`)}function sd(t){const s=new URLSearchParams;t!=null&&t.before&&s.set("before",t.before),typeof(t==null?void 0:t.limit)=="number"&&s.set("limit",String(t.limit)),t!=null&&t.includeInvalid&&s.set("includeInvalid","true"),at(s,ot(t==null?void 0:t.userIds));const i=s.size>0?`?${s.toString()}`:"";return ie(`/api/v1/movement/timeline${i}`)}function Wf(t,s){return ie(`/api/v1/movement/stays/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Hf(t){return ie(`/api/v1/movement/stays/${t}`,{method:"DELETE"})}function Gf(t,s){return ie(`/api/v1/movement/trips/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Xf(t){return ie(`/api/v1/movement/trips/${t}`,{method:"DELETE"})}function Vf(t,s,i){return ie(`/api/v1/movement/trips/${t}/points/${s}`,{method:"PATCH",body:JSON.stringify(i)})}function Jf(t,s){return ie(`/api/v1/movement/trips/${t}/points/${s}`,{method:"DELETE"})}function Yf(t){return ie("/api/v1/movement/selection",{method:"POST",body:JSON.stringify(t)})}function Zf(t){return ie("/api/v1/health/pairing-sessions",{method:"POST",body:JSON.stringify(t??{})})}function eb(t){return ie(`/api/v1/health/pairing-sessions/${t}`,{method:"DELETE"})}function tb(t){return ie("/api/v1/health/pairing-sessions/revoke-all",{method:"POST",body:JSON.stringify(t??{})})}function sb(t,s){return ie(`/api/v1/health/workouts/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function ib(t,s){return ie(`/api/v1/health/sleep/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function ab(){return ie("/api/v1/users/directory")}function nb(t,s){return ie(`/api/v1/users/access-grants/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function rb(t){return ie("/api/v1/users",{method:"POST",body:JSON.stringify(t)})}function lb(t,s){return ie(`/api/v1/users/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function ob(t){return ie("/api/v1/strategies",{method:"POST",body:JSON.stringify(t)})}function db(t){return ie(`/api/v1/strategies/${t}`)}function Jr(t,s){return ie(`/api/v1/strategies/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Bh(t){return ie(`/api/v1/strategies/${t}`,{method:"DELETE"})}function cb(){return ie("/api/v1/settings/bin")}function hb(){return ie("/api/v1/agents/onboarding")}function mb(){return ie("/api/v1/approval-requests")}function ub(t,s=""){return ie(`/api/v1/approval-requests/${t}/approve`,{method:"POST",body:JSON.stringify({note:s})})}function pb(t,s=""){return ie(`/api/v1/approval-requests/${t}/reject`,{method:"POST",body:JSON.stringify({note:s})})}function xb(){return ie("/api/v1/rewards/rules")}function gb(t,s){return ie(`/api/v1/rewards/rules/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function fb(t){return ie("/api/v1/rewards/bonus",{method:"POST",body:JSON.stringify(t)})}function bb(t=50){return ie(`/api/v1/rewards/ledger?limit=${t}`)}function Kh(){return ie("/api/v1/metrics/xp")}function Kl(t){return ie("/api/v1/settings",{method:"PATCH",body:JSON.stringify(t)})}function id(t){return ie("/api/v1/entities/delete",{method:"POST",body:JSON.stringify(t)})}function ad(t){return ie("/api/v1/entities/restore",{method:"POST",body:JSON.stringify(t)})}function Uh(t){return ie("/api/v1/entities/search",{method:"POST",body:JSON.stringify(t)})}function vb(t){return ie("/api/v1/settings/tokens",{method:"POST",body:JSON.stringify(t)})}function wb(t){return ie(`/api/v1/settings/tokens/${t}/rotate`,{method:"POST"})}function yb(t){return ie(`/api/v1/settings/tokens/${t}/revoke`,{method:"POST"})}function jb(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"),at(s,ot(t.userIds)),ie(`/api/v1/activity?${s.toString()}`)}function Nb(t={}){const s=new URLSearchParams;return s.set("limit",String(t.limit??200)),t.level&&s.set("level",t.level),t.source&&s.set("source",t.source),t.scope&&s.set("scope",t.scope),t.route&&s.set("route",t.route),t.entityType&&s.set("entityType",t.entityType),t.entityId&&s.set("entityId",t.entityId),t.jobId&&s.set("jobId",t.jobId),t.search&&s.set("search",t.search),t.beforeCreatedAt&&s.set("beforeCreatedAt",t.beforeCreatedAt),t.beforeId&&s.set("beforeId",t.beforeId),ie(`/api/v1/diagnostics/logs?${s.toString()}`)}function Qh(t){return ie("/api/v1/goals",{method:"POST",body:JSON.stringify({...t,notes:Rl(t.notes)})})}function Wh(t){return ie("/api/v1/projects",{method:"POST",body:JSON.stringify({...t,notes:Rl(t.notes)})})}function Hh(t,s){return ie(`/api/v1/projects/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function kb(t,s="soft"){return ie(`/api/v1/projects/${t}${s==="hard"?"?mode=hard":""}`,{method:"DELETE"})}function Sb(t,s){return ie(`/api/v1/goals/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Cb(t){return ie(`/api/v1/goals/${t}`,{method:"DELETE"})}function Sn(t){const s={...t,goalId:t.goalId||null,projectId:t.projectId||null,dueDate:t.dueDate||null,notes:Rl(t.notes)};return ie("/api/v1/tasks",{method:"POST",body:JSON.stringify(s)})}function Oa(t,s){return ie(`/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 Ul(t){return ie(`/api/v1/tasks/${t}`,{method:"DELETE"})}function Ql(t){return ie(`/api/v1/tasks/${t}/uncomplete`,{method:"POST",body:JSON.stringify({})})}function Ib(t){return ie(`/api/v1/tasks/${t}/context`)}function Tb(t){return ie("/api/v1/operator/log-work",{method:"POST",body:JSON.stringify(t)})}function Gh(t){return ie("/api/v1/work-adjustments",{method:"POST",body:JSON.stringify(t)})}function Xh(t,s="Removed from the visible archive."){return ie(`/api/v1/activity/${t}/remove`,{method:"POST",body:JSON.stringify({reason:s})})}function Pb(t){return ie("/api/v1/session-events",{method:"POST",body:JSON.stringify(t)})}function Mb(t,s){return ie(`/api/v1/tasks/${t}/runs`,{method:"POST",body:JSON.stringify(s)})}function Ab(t,s){return ie(`/api/v1/task-runs/${t}/heartbeat`,{method:"POST",body:JSON.stringify(s)})}function Eb(t,s={}){return ie(`/api/v1/task-runs/${t}/focus`,{method:"POST",body:JSON.stringify(s)})}function Vh(t,s){return ie(`/api/v1/task-runs/${t}/complete`,{method:"POST",body:JSON.stringify(s)})}function Jh(t,s){return ie(`/api/v1/task-runs/${t}/release`,{method:"POST",body:JSON.stringify(s)})}function Yh(t){return t.map(s=>(s==null?void 0:s.trim())??"").filter(Boolean)}function Zh(t){return Array.isArray(t)?t:[]}function Mt(t){const s=Zh(t);return s.length===1?s[0]:null}function Nt(t){return t?`${t.displayName} · ${t.kind}${t.handle?` · @${t.handle}`:""}`:""}function ts(t,s="Default Forge owner"){return t?`Suggested owner: ${t.displayName} · ${t.kind}`:s}function st(t,s){const i=Nt(s);return i?`${t} · ${i}`:t}function Ke(t,s,i="No description yet."){return Yh([t,Nt(s)]).join(" · ")||i}function Be(t,s){const i=s&&"user"in s?s.user:s;return Yh([...t,i==null?void 0:i.displayName,i==null?void 0:i.handle,i==null?void 0:i.kind,i==null?void 0:i.description]).join(" ").toLowerCase()}const em=["goal","project","task","strategy","habit","note","insight","calendar_event","work_block_template","task_timebox","psyche_value","behavior_pattern","behavior","belief_entry","mode_profile","trigger_report"];function Yr(t){return t.map(s=>(s==null?void 0:s.trim())??"").filter(Boolean)}function Rt(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}function Lb(t){if(!t||typeof t!="object")return null;const s=t,i=Rt(s.id),a=Rt(s.kind),n=Rt(s.displayName);return!i||!n||a!=="human"&&a!=="bot"?null:{id:i,kind:a,displayName:n,handle:Rt(s.handle)??"",description:Rt(s.description)??"",accentColor:Rt(s.accentColor)??"",createdAt:Rt(s.createdAt)??"",updatedAt:Rt(s.updatedAt)??""}}function hn(t){return t.trim().toLowerCase()}function Db(t){switch(t){case"goal":case"project":case"task":case"strategy":case"habit":return t;case"psyche_value":return"value";case"behavior_pattern":return"pattern";case"behavior":return"behavior";case"belief_entry":return"belief";case"mode_profile":return"mode";case"trigger_report":return"report";default:return null}}function Vn(t,s){switch(t){case"goal":return"Goal";case"project":return"Project";case"task":return"Task";case"strategy":return"Strategy";case"habit":return"Habit";case"note":return Rt(s==null?void 0:s.kind)==="wiki"?"Wiki page":"Note";case"insight":return"Insight";case"calendar_event":return"Calendar event";case"work_block_template":return"Work block";case"task_timebox":return"Timebox";case"psyche_value":return"Value";case"behavior_pattern":return"Pattern";case"behavior":return"Behavior";case"belief_entry":return"Belief";case"mode_profile":return"Mode";case"trigger_report":return"Report";default:return t.replaceAll("_"," ")}}function tm(t,s){return(t==="belief_entry"?[s.statement,s.title,s.name]:t==="note"?[s.title,s.slug]:[s.title,s.displayName,s.statement,s.name,s.label,s.slug]).map(Rt).find(Boolean)??`${Vn(t,s)} ${String(s.id??"")}`}function sm(t,s){const i=[s.summary,s.description,s.overview,s.flexibleAlternative,s.originNote,s.endState,s.whyItMatters,s.valuedDirection,s.contentPlain].map(Rt).find(Boolean),a=[s.goalTitle,s.projectTitle,s.status,s.kind].map(Rt).find(Boolean),n=Nt(Lb(s.user)),r=Yr([t==="note"?Vn(t,s):null,n||null]).join(" · ");return Yr([i,a,n||null]).join(" · ")||r}function $b(t,s){return Yr([tm(t,s),sm(t,s),Vn(t,s),Rt(s.slug),Rt(s.handle)]).join(" ").toLowerCase()}function Ob(t,s,i){switch(t){case"goal":return`/goals/${encodeURIComponent(s)}`;case"project":return`/projects/${encodeURIComponent(s)}`;case"task":return`/tasks/${encodeURIComponent(s)}`;case"strategy":return`/strategies/${encodeURIComponent(s)}`;case"habit":return`/habits?focus=${encodeURIComponent(s)}`;case"note":{const a=Rt(i.kind),n=Rt(i.slug);return a==="wiki"&&n?`/wiki/page/${encodeURIComponent(n)}`:"/notes"}case"insight":return"/insights";case"calendar_event":case"work_block_template":case"task_timebox":return"/calendar";case"psyche_value":return`/psyche/values?focus=${encodeURIComponent(s)}`;case"behavior_pattern":return`/psyche/patterns?focus=${encodeURIComponent(s)}`;case"behavior":return`/psyche/behaviors?focus=${encodeURIComponent(s)}`;case"belief_entry":return`/psyche/schemas-beliefs?focus=${encodeURIComponent(s)}`;case"mode_profile":return`/psyche/modes?focus=${encodeURIComponent(s)}`;case"trigger_report":return`/psyche/reports/${encodeURIComponent(s)}`;default:return null}}function nd(t,s,i){const a=hn(t);if(!a)return 0;const n=hn(s),r=hn(i),l=a.split(/\s+/).filter(Boolean);let o=0;n===a&&(o+=400),n.startsWith(a)&&(o+=240),n.includes(a)&&(o+=180),r.startsWith(a)&&(o+=32),r.includes(a)&&(o+=20);for(const c of l)n.startsWith(c)?o+=36:n.includes(c)&&(o+=24),r.includes(c)&&(o+=12);return o}const Fb=new Set(em);function _b(t){return typeof t=="string"&&Fb.has(t)}function Ct(t,s){const i=s??bt;switch(t){case"wiki":return{icon:Rn,tileClassName:"border-blue-300/18 bg-blue-300/12 text-blue-100 shadow-[0_18px_36px_rgba(96,165,250,0.12)]",badgeClassName:"border-blue-300/18 bg-blue-300/10 text-blue-100"};case"note":return{icon:Ki,tileClassName:"border-amber-300/18 bg-amber-300/12 text-amber-100 shadow-[0_18px_36px_rgba(251,191,36,0.12)]",badgeClassName:"border-amber-300/18 bg-amber-300/10 text-amber-100"};case"insight":return{icon:th,tileClassName:"border-emerald-300/18 bg-emerald-300/12 text-emerald-100 shadow-[0_18px_36px_rgba(52,211,153,0.12)]",badgeClassName:"border-emerald-300/18 bg-emerald-300/10 text-emerald-100"};case"calendar":return{icon:Xt,tileClassName:"border-cyan-300/18 bg-cyan-300/12 text-cyan-100 shadow-[0_18px_36px_rgba(34,211,238,0.12)]",badgeClassName:"border-cyan-300/18 bg-cyan-300/10 text-cyan-100"};case"route":return{icon:i,tileClassName:"border-white/12 bg-white/[0.05] text-white/72 shadow-[0_18px_36px_rgba(3,8,18,0.18)]",badgeClassName:"border-white/10 bg-white/[0.05] text-white/62"};default:return{icon:i,tileClassName:"border-white/12 bg-white/[0.05] text-white/72 shadow-[0_18px_36px_rgba(3,8,18,0.18)]",badgeClassName:"border-white/10 bg-white/[0.05] text-white/62"}}}function Rb({item:t}){if(t.kind){const a=Ts(t.kind),n=a.icon;return e.jsx("span",{className:re("mt-0.5 inline-flex size-11 shrink-0 items-center justify-center rounded-[17px] border",a.subtleBadgeClassName),children:e.jsx(n,{className:re("size-5",a.iconClassName)})})}const s=Ct("search",t.icon),i=t.icon??s.icon;return e.jsx("span",{className:re("mt-0.5 inline-flex size-11 shrink-0 items-center justify-center rounded-[17px] border",t.tileClassName??s.tileClassName),children:e.jsx(i,{className:"size-5"})})}function zb({item:t}){if(t.kind)return e.jsx(Te,{kind:t.kind,label:t.category,compact:!0,gradient:!1});const s=Ct("search",t.icon),i=t.icon??s.icon;return e.jsxs("span",{className:re("inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] font-medium",t.badgeClassName??s.badgeClassName),children:[e.jsx(i,{className:"size-3.5"}),t.category]})}function Ht(t,s,i){return`${t} ${s} ${i}`.trim().toLowerCase()}function qb({open:t,onOpenChange:s,snapshot:i,selectedUserIds:a}){var A;const n=ut(),{t:r}=lt(),l=d.useRef([]),[o,c]=d.useState(""),[x,v]=d.useState(0),u=d.useDeferredValue(o),f=hn(u);d.useEffect(()=>{t||(c(""),v(0))},[t]);const h=d.useMemo(()=>[{id:"route-overview",title:r("common.routeLabels.overview"),detail:r("common.commandPalette.routeOverview"),href:"/overview",category:r("common.commandPalette.categoryRoute"),section:"Routes",searchText:Ht(r("common.routeLabels.overview"),r("common.commandPalette.routeOverview"),r("common.commandPalette.categoryRoute")),score:0,...Ct("route",sh)},{id:"route-today",title:r("common.routeLabels.today"),detail:r("common.commandPalette.routeToday"),href:"/today",category:r("common.commandPalette.categoryRoute"),section:"Routes",searchText:Ht(r("common.routeLabels.today"),r("common.commandPalette.routeToday"),r("common.commandPalette.categoryRoute")),score:0,...Ct("route",gi)},{id:"route-kanban",title:r("common.routeLabels.kanban"),detail:r("common.commandPalette.routeKanban"),href:"/kanban",category:r("common.commandPalette.categoryRoute"),section:"Routes",searchText:Ht(r("common.routeLabels.kanban"),r("common.commandPalette.routeKanban"),r("common.commandPalette.categoryRoute")),score:0,...Ct("route",Ca)},{id:"route-psyche",title:r("common.routeLabels.psyche"),detail:r("common.commandPalette.routePsyche"),href:"/psyche",category:r("common.commandPalette.categoryRoute"),section:"Routes",searchText:Ht(r("common.routeLabels.psyche"),r("common.commandPalette.routePsyche"),r("common.commandPalette.categoryRoute")),score:0,...Ct("route",bl)},{id:"route-notes",title:r("common.routeLabels.notes"),detail:r("common.commandPalette.routeNotes"),href:"/notes",category:r("common.commandPalette.categoryRoute"),section:"Routes",searchText:Ht(r("common.routeLabels.notes"),r("common.commandPalette.routeNotes"),r("common.commandPalette.categoryRoute")),score:0,...Ct("route",Ki)},{id:"route-wiki",title:r("common.routeLabels.wiki"),detail:r("common.commandPalette.routeWiki"),href:"/wiki",category:r("common.commandPalette.categoryRoute"),section:"Routes",searchText:Ht(r("common.routeLabels.wiki"),r("common.commandPalette.routeWiki"),r("common.commandPalette.categoryRoute")),score:0,...Ct("route",Rn)},{id:"route-goals",title:r("common.routeLabels.goals"),detail:r("common.commandPalette.routeGoals"),href:"/goals",category:r("common.commandPalette.categoryRoute"),section:"Routes",searchText:Ht(r("common.routeLabels.goals"),r("common.commandPalette.routeGoals"),r("common.commandPalette.categoryRoute")),score:0,...Ct("route",Fn)},{id:"route-habits",title:r("common.routeLabels.habits"),detail:r("common.commandPalette.routeHabits"),href:"/habits",category:r("common.commandPalette.categoryRoute"),section:"Routes",searchText:Ht(r("common.routeLabels.habits"),r("common.commandPalette.routeHabits"),r("common.commandPalette.categoryRoute")),score:0,...Ct("route",gl)},{id:"route-projects",title:r("common.routeLabels.projects"),detail:r("common.commandPalette.routeProjects"),href:"/projects",category:r("common.commandPalette.categoryRoute"),section:"Routes",searchText:Ht(r("common.routeLabels.projects"),r("common.commandPalette.routeProjects"),r("common.commandPalette.categoryRoute")),score:0,...Ct("route",ih)},{id:"route-strategies",title:r("common.routeLabels.strategies"),detail:r("common.commandPalette.routeStrategies"),href:"/strategies",category:r("common.commandPalette.categoryRoute"),section:"Routes",searchText:Ht(r("common.routeLabels.strategies"),r("common.commandPalette.routeStrategies"),r("common.commandPalette.categoryRoute")),score:0,...Ct("route",fl)},{id:"route-preferences",title:r("common.routeLabels.preferences"),detail:r("common.commandPalette.routePreferences"),href:"/preferences",category:r("common.commandPalette.categoryRoute"),section:"Routes",searchText:Ht(r("common.routeLabels.preferences"),r("common.commandPalette.routePreferences"),r("common.commandPalette.categoryRoute")),score:0,...Ct("route",Aa)},{id:"route-calendar",title:r("common.routeLabels.calendar"),detail:r("common.commandPalette.routeCalendar"),href:"/calendar",category:r("common.commandPalette.categoryRoute"),section:"Routes",searchText:Ht(r("common.routeLabels.calendar"),r("common.commandPalette.routeCalendar"),r("common.commandPalette.categoryRoute")),score:0,...Ct("route",Xt)},{id:"route-settings",title:r("common.routeLabels.settings"),detail:r("common.commandPalette.routeSettings"),href:"/settings",category:r("common.commandPalette.categoryRoute"),section:"Routes",searchText:Ht(r("common.routeLabels.settings"),r("common.commandPalette.routeSettings"),r("common.commandPalette.categoryRoute")),score:0,...Ct("route",vl)}],[r]),m=d.useMemo(()=>{const T=[...i.overview.topTasks.slice(0,4).map(k=>({id:`task-${k.id}`,title:k.title,detail:Nt(k.user)||r("common.commandPalette.openFocusTask"),href:`/tasks/${k.id}`,category:r("common.commandPalette.categoryTask"),section:"Recent",searchText:`${k.title} ${Nt(k.user)}`.toLowerCase(),score:0,kind:"task"})),...i.dashboard.projects.slice(0,3).map(k=>({id:`project-${k.id}`,title:k.title,detail:[k.goalTitle,Nt(k.user)].filter(Boolean).join(" · "),href:`/projects/${k.id}`,category:r("common.commandPalette.categoryProject"),section:"Recent",searchText:`${k.title} ${k.goalTitle??""} ${Nt(k.user)}`.toLowerCase(),score:0,kind:"project"})),...i.overview.activeGoals.slice(0,2).map(k=>({id:`goal-${k.id}`,title:k.title,detail:Nt(k.user)||r("common.commandPalette.openLifeGoal"),href:`/goals/${k.id}`,category:r("common.commandPalette.categoryGoal"),section:"Recent",searchText:`${k.title} ${Nt(k.user)}`.toLowerCase(),score:0,kind:"goal"})),...i.dashboard.habits.slice(0,2).map(k=>({id:`habit-${k.id}`,title:k.title,detail:[k.frequency==="daily"?"Daily habit":"Weekly habit",Nt(k.user)].filter(Boolean).join(" · "),href:`/habits?focus=${k.id}`,category:r("common.routeLabels.habits"),section:"Recent",searchText:`${k.title} ${k.frequency} ${Nt(k.user)}`.toLowerCase(),score:0,kind:"habit"}))].slice(0,8);return[...h.slice(0,6),...T]},[h,i,r]),b=fe({queryKey:["forge-power-bar-search",f,[...a].sort().join("|")],enabled:t&&f.length>0,queryFn:async()=>{const T=await Uh({searches:em.map($=>({entityTypes:[$],query:u.trim(),userIds:a.length>0?a:void 0,limit:$==="note"?6:4,clientRef:$}))}),k=new Map;for(const $ of T.results){const g=Array.isArray($.matches)?$.matches??[]:[];for(const C of g){if(!C||typeof C!="object")continue;const F=C;if(!_b(F.entityType)||typeof F.id!="string"||!F.entity||typeof F.entity!="object")continue;const z=F.entity,J=Ob(F.entityType,F.id,z);if(!J)continue;const O=tm(F.entityType,z),_=sm(F.entityType,z),B=Vn(F.entityType,z),K=$b(F.entityType,z),Z=Db(F.entityType)??void 0,U=nd(u,O,K);let I=Ct("search");F.entityType==="note"?I=Ct(z.kind==="wiki"?"wiki":"note"):F.entityType==="insight"?I=Ct("insight"):(F.entityType==="calendar_event"||F.entityType==="task_timebox"||F.entityType==="work_block_template")&&(I=Ct("calendar"));const G={id:`${F.entityType}-${F.id}`,title:O,detail:_,href:J,category:B,section:"Results",searchText:K,score:U,kind:Z,icon:I.icon,tileClassName:I.tileClassName,badgeClassName:I.badgeClassName},W=k.get(G.id);(!W||G.score>W.score)&&k.set(G.id,G)}}return Array.from(k.values()).sort(($,g)=>g.score-$.score||$.title.localeCompare(g.title)).slice(0,12)}}),w=d.useMemo(()=>f?h.map(T=>({...T,score:nd(u,T.title,T.searchText)})).filter(T=>T.score>0).sort((T,k)=>k.score-T.score||T.title.localeCompare(k.title)).slice(0,4):[],[u,f,h]),M=d.useMemo(()=>{if(!f)return m;const T=[...w],k=new Set(T.map($=>$.id));for(const $ of b.data??[])k.has($.id)||(k.add($.id),T.push($));return T.slice(0,16)},[m,b.data,f,w]);d.useEffect(()=>{v(0)},[f,t]),d.useEffect(()=>{M.length!==0&&v(T=>Math.min(Math.max(T,0),M.length-1))},[M]),d.useEffect(()=>{const T=l.current[x];T==null||T.scrollIntoView({block:"nearest"})},[x]);const E=M[x]??null,D=i.users.filter(T=>a.includes(T.id)),j=a.length===0?"All humans and bots":D.length===1?((A=D[0])==null?void 0:A.displayName)??"1 selected owner":`${D.length||a.length} selected owners`,S=f.length>0&&b.isFetching,p=T=>{s(!1),n(T.href)};return e.jsx(Et,{open:t,onOpenChange:s,children:e.jsxs(Lt,{children:[e.jsx(Dt,{className:"fixed inset-0 z-40 bg-[rgba(5,10,18,0.72)] backdrop-blur-xl"}),e.jsxs($t,{className:"fixed inset-x-3 bottom-3 top-3 z-50 flex flex-col overflow-hidden rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top,rgba(71,85,105,0.24),transparent_36%),linear-gradient(180deg,rgba(18,27,42,0.98),rgba(8,12,24,0.98))] shadow-[0_40px_120px_rgba(3,8,18,0.56)] sm:inset-x-6 sm:bottom-6 sm:top-6 md:left-1/2 md:right-auto md:top-[9vh] md:h-[min(78vh,44rem)] md:w-[min(60rem,calc(100vw-2rem))] md:-translate-x-1/2 md:bottom-auto",children:[e.jsx(Ot,{className:"sr-only",children:"Forge power bar"}),e.jsx(qt,{className:"sr-only",children:"Search routes and Forge records, then open the selected result."}),e.jsxs("div",{className:"border-b border-white/8 px-4 py-4 sm:px-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-3 py-1.5 text-[12px] text-white/68",children:[e.jsx("span",{className:"rounded-full bg-white/[0.08] px-2 py-0.5 text-[11px] uppercase tracking-[0.16em] text-white/50",children:"Scope"}),e.jsx("span",{children:j})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] uppercase tracking-[0.16em] text-white/40",children:[e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1",children:"Shift Shift"}),e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1",children:"Cmd/Ctrl K"})]})]}),e.jsxs("div",{className:"mt-4 rounded-[24px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.08),rgba(255,255,255,0.03))] px-4 py-3 shadow-[inset_0_1px_0_rgba(255,255,255,0.05)]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(bt,{className:"size-5 text-white/36"}),e.jsx(le,{autoFocus:!0,value:o,onChange:T=>c(T.target.value),onKeyDown:T=>{if(T.key==="ArrowDown"){T.preventDefault(),v(k=>M.length===0?0:Math.min(k+1,M.length-1));return}if(T.key==="ArrowUp"){T.preventDefault(),v(k=>Math.max(k-1,0));return}if(T.key==="Enter"&&E){T.preventDefault(),p(E);return}T.key==="Escape"&&(T.preventDefault(),s(!1))},placeholder:r("common.commandPalette.searchPlaceholder"),className:"border-0 bg-transparent px-0 py-0 text-[1rem] focus:border-0"}),S?e.jsx(_n,{className:"size-4 shrink-0 animate-spin text-white/42"}):null]}),e.jsx("div",{className:"mt-2 pl-8 text-[13px] leading-6 text-white/46",children:f?"Search spans routes plus Forge records in the current owner scope.":"Jump between Forge surfaces or start typing to search records across the current scope."})]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-3 py-3 sm:px-4",children:M.length===0?e.jsx("div",{className:"rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] px-4 py-8 text-center text-sm text-white/56",children:b.isFetching?"Searching Forge...":r("common.commandPalette.noResults")}):e.jsx("div",{className:"grid gap-2",children:M.map((T,k)=>{var C;const g=(((C=M[k-1])==null?void 0:C.section)??null)!==T.section;return e.jsxs("div",{children:[g?e.jsx("div",{className:"px-2 pb-1 pt-2 text-[11px] uppercase tracking-[0.18em] text-white/34 first:pt-0",children:T.section}):null,e.jsxs("button",{ref:F=>{l.current[k]=F},type:"button",className:re("group flex w-full items-start gap-3 rounded-[24px] border px-4 py-3.5 text-left transition",k===x?"border-white/18 bg-[linear-gradient(180deg,rgba(255,255,255,0.11),rgba(255,255,255,0.05))] shadow-[0_24px_60px_rgba(3,8,18,0.24)]":"border-transparent bg-white/[0.04] hover:bg-white/[0.07]"),onMouseEnter:()=>v(k),onClick:()=>p(T),children:[e.jsx(Rb,{item:T}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(zb,{item:T})}),e.jsx("div",{className:"mt-2 text-[15px] font-medium text-white",children:T.kind?e.jsx(Xe,{kind:T.kind,label:T.title,showIcon:!1,labelClassName:"text-white"}):T.title}),e.jsx("div",{className:"mt-1 text-sm leading-6 text-white/56",children:T.detail})]}),e.jsx(Gt,{className:re("mt-1 size-4 shrink-0 transition",k===x?"text-white/72":"text-white/26 group-hover:text-white/48")})]})]},T.id)})})}),e.jsx("div",{className:"border-t border-white/8 px-4 py-3 sm:px-5",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[12px] text-white/44",children:[e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1",children:"Up/Down navigate"}),e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1",children:"Enter open"}),e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1",children:"Esc close"})]})})]})]})})}function rd({routeKey:t,tone:s="core",children:i}){return e.jsx(Kt.div,{"data-route-key":t,"data-route-tone":s,className:"w-full max-w-full min-w-0",initial:!1,animate:{opacity:1,y:0},transition:{duration:.12,ease:"easeOut"},children:i})}const Bb=Ou("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 Q({className:t,variant:s,size:i,pending:a=!1,pendingLabel:n,children:r,disabled:l,...o}){return e.jsxs("button",{className:re(Bb({variant:s,size:i}),t),disabled:l||a,"aria-busy":a,...o,children:[a?e.jsx(Fl,{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:a&&n?n:r})]})}function bs({open:t,onOpenChange:s,eyebrow:i,title:a,description:n,children:r}){const{t:l}=lt();return e.jsx(Et,{open:t,onOpenChange:s,children:e.jsxs(Lt,{children:[e.jsx(Dt,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.72)] backdrop-blur-xl"}),e.jsxs($t,{className:"fixed inset-x-4 bottom-4 top-4 z-50 mx-auto flex max-w-xl flex-col overflow-hidden rounded-[32px] border border-white/8 bg-[linear-gradient(180deg,rgba(20,28,42,0.98),rgba(12,17,30,0.98))] shadow-[0_32px_90px_rgba(3,8,18,0.45)]",children:[e.jsx("div",{className:"border-b border-white/8 px-5 py-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"type-label text-white/46",children:i}),e.jsx(Ot,{className:"mt-2 type-display-section text-white",children:a}),n?e.jsx(qt,{className:"mt-3 type-body text-white/64",children:n}):null]}),e.jsx(Q,{variant:"secondary",onClick:()=>s(!1),children:l("common.actions.close")})]})}),e.jsx("div",{className:"min-h-0 flex-1 overflow-x-hidden overflow-y-auto p-4",children:r})]})]})})}function Hs({children:t,className:s}){return e.jsx("div",{className:re("text-sm leading-6 text-white/50",s),children:t})}function it({content:t,label:s="Explain this field",className:i}){const[a,n]=d.useState(!1),r=d.useRef(null),l=d.useId();return d.useEffect(()=>{if(!a)return;const o=c=>{var x;(x=r.current)!=null&&x.contains(c.target)||n(!1)};return document.addEventListener("pointerdown",o),()=>document.removeEventListener("pointerdown",o)},[a]),e.jsxs("span",{ref:r,className:re("relative inline-flex items-center",i),onMouseEnter:()=>n(!0),onMouseLeave:()=>n(!1),children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":a?l:void 0,"aria-expanded":a,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:()=>n(!0),onBlur:()=>n(!1),onClick:()=>n(o=>!o),children:e.jsx(Fu,{className:"size-3.5"})}),e.jsx("span",{id:l,role:"tooltip",className:re("pointer-events-none absolute right-0 top-[calc(100%+0.55rem)] z-40 w-[min(16rem,calc(100vw-2.5rem))] max-w-[calc(100vw-2.5rem)] rounded-[18px] border border-white/8 bg-[rgba(12,17,30,0.96)] px-3 py-2.5 text-sm leading-6 text-white/74 shadow-[0_18px_48px_rgba(3,8,18,0.42)] transition",a?"translate-y-0 opacity-100":"translate-y-1 opacity-0"),children:t})]})}const ld="(max-width: 1023px)";function Kb(){const[t,s]=d.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(ld).matches);return d.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const i=window.matchMedia(ld),a=n=>{s(n.matches)};return s(i.matches),typeof i.addEventListener=="function"?(i.addEventListener("change",a),()=>i.removeEventListener("change",a)):(i.addListener(a),()=>i.removeListener(a))},[]),t}function se({label:t,description:s,labelHelp:i,hint:a,error:n,children:r}){return e.jsxs("label",{className:"grid gap-2",children:[e.jsxs("span",{className:"flex items-center gap-2 text-sm font-medium text-white",children:[e.jsx("span",{children:t}),i?e.jsx(it,{content:i,label:`Explain ${t}`}):null]}),s?e.jsx("span",{className:"text-sm leading-6 text-white/54",children:s}):null,r,a?e.jsx(Hs,{children:a}):null,n?e.jsx("span",{className:"text-sm text-rose-300",children:n}):null]})}function Ze({options:t,value:s,onChange:i,columns:a=2}){return e.jsx("div",{className:re("grid gap-3",a===3?"md:grid-cols-3":"md:grid-cols-2"),children:t.map(n=>{const r=n.value===s;return e.jsxs("button",{type:"button",className:re("rounded-[22px] border px-4 py-4 text-left transition",r?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.14)] text-white shadow-[0_18px_36px_rgba(5,12,24,0.24)]":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"),onClick:()=>i(n.value),children:[e.jsx("div",{className:"font-medium",children:n.label}),n.description?e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:n.description}):null]},n.value)})})}function rt({open:t,onOpenChange:s,eyebrow:i,title:a,description:n,value:r,onChange:l,steps:o,onSubmit:c,submitLabel:x,pending:v=!1,pendingLabel:u,error:f,resolveError:h,initialStepId:m,contentClassName:b}){const{t:w}=lt(),M=Kb(),[E,D]=d.useState(0),j=d.useRef(t),S=d.useRef(m),p=o[E];d.useEffect(()=>{const C=j.current,F=S.current!==m;if(j.current=t,S.current=m,!t){D(0);return}if(!C||F){if(m){const z=o.findIndex(J=>J.id===m);D(z>=0?z:0);return}D(0);return}if(E>=o.length){D(Math.max(0,o.length-1));return}if(!p&&m){const z=o.findIndex(J=>J.id===m);D(z>=0?z:0)}},[m,t,p,E,o]);const A=C=>{l({...r,...C})},T=o.length,k=T===0?0:(E+1)/T*100,$=p?h==null?void 0:h(p.id):void 0,g=$===void 0?f:$;return e.jsx(Et,{open:t,onOpenChange:s,children:e.jsxs(Lt,{children:[e.jsx(Dt,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.72)] backdrop-blur-xl"}),e.jsxs($t,{"data-testid":"question-flow-dialog",className:re("fixed z-50 flex flex-col overflow-hidden border border-white/8 bg-[linear-gradient(180deg,rgba(21,28,44,0.985),rgba(12,17,30,0.985))] shadow-[0_30px_90px_rgba(3,8,18,0.45)]",M?"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]",b),children:[e.jsx(Ot,{className:"sr-only",children:a}),e.jsx(qt,{className:"sr-only",children:n}),e.jsx("div",{className:"sticky top-0 z-10 border-b border-white/8 bg-[rgba(12,17,30,0.9)] px-4 py-2.5 backdrop-blur-xl md:px-6",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-[11px] uppercase tracking-[0.18em] text-white/42",children:[e.jsx("span",{className:"truncate",children:i}),e.jsxs("span",{className:"whitespace-nowrap",children:["Step ",E+1," of ",T]})]}),e.jsx("div",{className:"mt-2 h-1.5 rounded-full bg-white/[0.06]",children:e.jsx(Kt.div,{className:"h-full rounded-full bg-[linear-gradient(90deg,rgba(192,193,255,0.9),rgba(125,211,252,0.82))]",animate:{width:`${k}%`},transition:{duration:.35,ease:"easeOut"}})})]}),e.jsx(Ft,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":w("common.dialogs.closeDialog"),className:"rounded-full bg-white/6 p-2 text-white/65 transition hover:bg-white/10 hover:text-white",children:e.jsx(mt,{className:"size-4"})})})]})}),e.jsx("div",{"data-testid":"question-flow-canvas",className:"min-h-0 flex-1 overflow-y-auto overscroll-contain px-4 py-4 md:px-6 md:py-5",children:e.jsx(wn,{mode:"wait",children:e.jsxs(Kt.div,{initial:{opacity:0,y:18},animate:{opacity:1,y:0},exit:{opacity:0,y:-18},transition:{duration:.28,ease:"easeOut"},className:"flex min-h-full min-w-0 flex-col gap-5",children:[e.jsxs("div",{className:"flex min-h-full min-w-0 flex-col justify-start",children:[p.eyebrow?e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-[var(--secondary)]",children:p.eyebrow}):null,e.jsx("h3",{className:"mt-1.5 font-display text-[clamp(1.45rem,2.15vw,2rem)] leading-tight text-white",children:p.title}),p.description?e.jsx("p",{className:"mt-1.5 max-w-3xl text-sm leading-6 text-white/58",children:p.description}):null,e.jsx("div",{className:"mt-5 grid flex-1 content-start gap-5",children:p.render(r,A)})]}),g?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:g}):null]},p.id)})}),e.jsx("div",{className:"sticky bottom-0 border-t border-white/8 bg-[rgba(12,17,30,0.92)] px-4 pt-2.5 pb-[calc(env(safe-area-inset-bottom)+0.75rem)] backdrop-blur-xl md:px-6 md:pb-3",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2 sm:justify-between",children:[e.jsx("div",{className:"hidden min-w-0 shrink text-[12px] text-white/45 sm:block",children:e.jsxs("span",{className:"truncate whitespace-nowrap",children:["Step ",E+1,"/",T]})}),e.jsxs("div",{className:"flex min-w-0 shrink-0 flex-wrap items-center justify-end gap-1.5 sm:gap-2",children:[E>0?e.jsxs(Q,{type:"button",variant:"secondary",className:"min-w-max px-3 text-[12px]",onClick:()=>D(C=>Math.max(0,C-1)),children:[e.jsx(fn,{className:"size-4"}),"Back"]}):e.jsx(Ft,{asChild:!0,children:e.jsx(Q,{type:"button",variant:"secondary",className:"min-w-max px-3 text-[12px]",children:w("common.actions.cancel")})}),E<T-1?e.jsxs(Q,{type:"button",className:"min-w-max px-3 text-[12px]",onClick:()=>D(C=>Math.min(T-1,C+1)),children:["Continue",e.jsx(Gt,{className:"size-4"})]}):e.jsxs(Q,{type:"button",className:"min-w-max px-3 text-[12px]",pending:v,pendingLabel:u,onClick:()=>void c(),children:[e.jsx(Vi,{className:"size-4"}),x]})]})]})})]})]})})}const Me=d.forwardRef(function({className:s,...i},a){return e.jsx("textarea",{ref:a,...i,className:re("min-h-28 w-full rounded-[22px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none placeholder:text-white/35 focus:border-[rgba(192,193,255,0.35)]",s)})}),Ub={contentMarkdown:"",author:""};function Qb(){return{...Ub}}function Wl({notes:t,onChange:s,entityLabel:i}){return e.jsxs("div",{className:"grid gap-3",children:[t.length===0?e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4 text-sm leading-6 text-white/58",children:["Add an optional Markdown note if this ",i," should start with context, evidence, or a clear handoff summary."]}):null,t.map((a,n)=>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 ",n+1]}),e.jsx(Q,{type:"button",variant:"ghost",size:"sm",onClick:()=>s(t.filter((r,l)=>l!==n)),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(le,{value:a.author,placeholder:"Albert",onChange:r=>s(t.map((l,o)=>o===n?{...l,author:r.target.value}:l))})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Markdown note"}),e.jsx(Me,{className:"min-h-28",value:a.contentMarkdown,placeholder:"Capture why this was created now, what changed, or what the next person should know.",onChange:r=>s(t.map((l,o)=>o===n?{...l,contentMarkdown:r.target.value}:l))})]})]})]},n)),e.jsx("div",{children:e.jsx(Q,{type:"button",variant:"secondary",onClick:()=>s([...t,Qb()]),children:"Add creation note"})})]})}function ss({value:t,users:s,onChange:i,label:a="Owner",defaultLabel:n="Default Forge owner",help:r}){return e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-white",children:a}),r?e.jsx("span",{className:"text-xs leading-5 text-white/52",children:r}):null,e.jsxs("select",{value:t??"",onChange:l=>i(l.target.value||null),className:"min-h-10 rounded-[var(--radius-control)] border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.3)]",children:[e.jsx("option",{value:"",children:n}),s.map(l=>e.jsxs("option",{value:l.id,children:[l.displayName," · ",l.kind]},l.id))]})]})}const Wb=["obsidian","solar","aurora","ember","custom","system"],Hb=vt(Wb),Os=je().trim().regex(/^#[0-9a-fA-F]{6}$/,"Use a 6-digit hex color"),Zr=Ve({label:je().trim().min(1,"Theme name is required").max(40),primary:Os,secondary:Os,tertiary:Os,canvas:Os,panel:Os,panelHigh:Os,panelLow:Os,ink:Os}),Gb=["--primary","--secondary","--tertiary","--surface","--surface-low","--surface-panel","--surface-high","--surface-glass","--surface-psyche","--surface-psyche-high","--hero-gradient","--card-gradient","--card-shadow","--card-shadow-hover","--forge-body-ambient-primary","--forge-body-ambient-secondary","--forge-body-gradient-start","--forge-body-gradient-end","--forge-body-text"],Pa={label:"Custom Forge",primary:"#7cc7ff",secondary:"#4edea3",tertiary:"#ffb95f",canvas:"#0b1326",panel:"#171f33",panelHigh:"#222a3d",panelLow:"#131b2e",ink:"#eef2ff"},cs={obsidian:{label:"Obsidian",description:"Deep indigo with cool neon edges. This is the current default.",preview:{label:"Obsidian",primary:"#c0c1ff",secondary:"#4edea3",tertiary:"#ffb95f",canvas:"#0b1326",panel:"#171f33",panelHigh:"#222a3d",panelLow:"#131b2e",ink:"#eef2ff"}},solar:{label:"Catppuccin",description:"Pastel mocha surfaces inspired by the widely adopted Catppuccin palette.",preview:{label:"Catppuccin",primary:"#cba6f7",secondary:"#94e2d5",tertiary:"#fab387",canvas:"#1e1e2e",panel:"#313244",panelHigh:"#45475a",panelLow:"#181825",ink:"#cdd6f4"}},aurora:{label:"Nord",description:"Arctic blue-grey surfaces based on Nord's clean and uncluttered palette.",preview:{label:"Nord",primary:"#88c0d0",secondary:"#a3be8c",tertiary:"#ebcb8b",canvas:"#2e3440",panel:"#3b4252",panelHigh:"#434c5e",panelLow:"#242933",ink:"#eceff4"}},ember:{label:"Dracula",description:"High-contrast purple and pink accents drawn from the official Dracula specification.",preview:{label:"Dracula",primary:"#bd93f9",secondary:"#8be9fd",tertiary:"#ff79c6",canvas:"#282a36",panel:"#343746",panelHigh:"#424450",panelLow:"#21222c",ink:"#f8f8f2"}}},Xb=[{value:"obsidian",label:cs.obsidian.label,description:cs.obsidian.description},{value:"solar",label:cs.solar.label,description:cs.solar.description},{value:"aurora",label:cs.aurora.label,description:cs.aurora.description},{value:"ember",label:cs.ember.label,description:cs.ember.description},{value:"custom",label:"Custom",description:"Use your own dark-theme token set through the guided editor or direct JSON import."},{value:"system",label:"System",description:"Follow the device preference. Forge maps dark mode to Obsidian and light mode to Catppuccin."}];function el(t){const s=t.replace("#","");return{r:Number.parseInt(s.slice(0,2),16),g:Number.parseInt(s.slice(2,4),16),b:Number.parseInt(s.slice(4,6),16)}}function Vb({r:t,g:s,b:i}){return`#${[t,s,i].map(a=>Math.max(0,Math.min(255,Math.round(a))).toString(16).padStart(2,"0")).join("")}`}function ei(t,s,i){const a=el(t),n=el(s);return Vb({r:a.r+(n.r-a.r)*i,g:a.g+(n.g-a.g)*i,b:a.b+(n.b-a.b)*i})}function ns(t,s){const{r:i,g:a,b:n}=el(t);return`rgba(${i}, ${a}, ${n}, ${s})`}function Jb(t,s){return t==="system"?s?"obsidian":"solar":t}function im(t,s){return t==="custom"?s??Pa:t==="system"?cs.obsidian.preview:cs[t].preview}function Yb(t){const s=ei(t.panelHigh,t.primary,.08),i=ei(t.panelHigh,t.primary,.16),a=ei(t.canvas,t.secondary,.06);return{"--primary":t.primary,"--secondary":t.secondary,"--tertiary":t.tertiary,"--surface":t.canvas,"--surface-low":t.panelLow,"--surface-panel":t.panel,"--surface-high":t.panelHigh,"--surface-glass":ns(t.canvas,.82),"--surface-psyche":ns(ei(t.canvas,t.secondary,.12),.94),"--surface-psyche-high":ns(ei(t.panelHigh,t.secondary,.1),.96),"--hero-gradient":`linear-gradient(180deg, ${ns(i,.95)}, ${ns(a,.95)})`,"--card-gradient":`linear-gradient(180deg, ${ns(s,.96)}, ${ns(t.panelLow,.94)})`,"--card-shadow":`0 24px 60px ${ns(t.canvas,.3)}`,"--card-shadow-hover":`0 32px 80px ${ns(t.canvas,.38)}`,"--forge-body-ambient-primary":ns(t.primary,.2),"--forge-body-ambient-secondary":ns(t.secondary,.14),"--forge-body-gradient-start":ei(t.panel,t.primary,.08),"--forge-body-gradient-end":ei(t.canvas,"#000000",.16),"--forge-body-text":t.ink}}function tl(t,s){if(typeof document>"u")return;const i=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches,a=Jb(t,i),n=document.body,r=document.documentElement;if(n.classList.remove("theme-forge-obsidian","theme-forge-solar","theme-forge-aurora","theme-forge-ember","theme-forge-custom"),a==="custom"){const l=s??Pa,o=Yb(l);n.classList.add("theme-forge-custom");for(const[c,x]of Object.entries(o))r.style.setProperty(c,x);r.dataset.forgeTheme=l.label;return}for(const l of Gb)r.style.removeProperty(l);delete r.dataset.forgeTheme,n.classList.add(`theme-forge-${a}`)}const Zb=vt(["en","fr"]),Hl=Ve({contentMarkdown:je().trim().min(1,"Note content is required"),author:je().trim()}),am=Ve({title:je().trim().min(1,"Title is required"),description:je().trim(),horizon:vt(["quarter","year","lifetime"]),status:vt(["active","paused","completed"]),userId:je().trim().nullable().optional(),targetPoints:hs.number().int().min(25).max(1e4),themeColor:je().trim().regex(/^#[0-9a-fA-F]{6}$/,"Theme color must be a valid hex value"),tagIds:_e(je()),notes:_e(Hl)}),nm=Ve({goalId:je().trim().min(1,"Life goal is required"),title:je().trim().min(1,"Title is required"),description:je().trim(),status:vt(["active","paused","completed"]),userId:je().trim().nullable().optional(),targetPoints:hs.number().int().min(25).max(1e4),themeColor:je().trim().regex(/^#[0-9a-fA-F]{6}$/,"Theme color must be a valid hex value"),notes:_e(Hl)}),ev=Ve({profile:Ve({operatorName:je().trim().min(1,"Name is required"),operatorEmail:je().trim().min(1,"Email is required"),operatorTitle:je().trim().min(1,"Title is required")}),notifications:Ve({goalDriftAlerts:dn(),dailyQuestReminders:dn(),achievementCelebrations:dn()}),execution:Ve({maxActiveTasks:hs.number().int().min(1).max(8),timeAccountingMode:vt(["split","parallel","primary_only"])}),themePreference:Hb,customTheme:Zr.nullable().optional(),localePreference:Zb,calendarProviders:Ve({microsoft:Ve({clientId:je().trim(),tenantId:je().trim(),redirectUri:je().trim()}).optional()}).optional(),modelSettings:Ve({forgeAgent:Ve({basicChat:Ve({connectionId:je().trim().nullable().optional(),model:je().trim().optional()}).optional(),wiki:Ve({connectionId:je().trim().nullable().optional(),model:je().trim().optional()}).optional()}).optional()}).optional()}),tv=Ve({label:je().trim().min(1,"Label is required"),agentLabel:je().trim().min(1,"Agent name is required"),agentType:je().trim().min(1,"Agent type is required"),description:je().trim(),trustLevel:vt(["standard","trusted","autonomous"]),autonomyMode:vt(["approval_required","scoped_write","autonomous"]),approvalMode:vt(["approval_by_default","high_impact_only","none"]),scopes:_e(je().trim().min(1)).min(1)}),sv=Ve({originType:vt(["system","user","agent"]),originAgentId:je().trim(),originLabel:je().trim(),entityType:je().trim(),entityId:je().trim(),timeframeLabel:je().trim(),title:je().trim().min(1,"Title is required"),summary:je().trim().min(1,"Summary is required"),recommendation:je().trim().min(1,"Recommendation is required"),rationale:je().trim(),confidence:hs.number().min(0).max(1),ctaLabel:je().trim().min(1,"CTA label is required")}),rm=Ve({title:je().trim().min(1,"Title is required"),description:je().trim(),owner:je().trim().min(1,"Owner is required"),userId:je().trim().nullable().optional(),goalId:je().trim(),projectId:je().trim().min(1,"Project is required"),priority:vt(["low","medium","high","critical"]),status:vt(["backlog","focus","in_progress","blocked","done"]),effort:vt(["light","deep","marathon"]),energy:vt(["low","steady","high"]),dueDate:je().trim(),points:hs.number().int().min(5).max(500),tagIds:_e(je()),notes:_e(Hl)}),iv=Ve({title:je().trim().min(1,"Title is required"),description:je().trim(),status:vt(["active","paused","archived"]),userId:je().trim().nullable().optional(),polarity:vt(["positive","negative"]),frequency:vt(["daily","weekly"]),targetCount:hs.number().int().min(1).max(14),weekDays:_e(wl().int().min(0).max(6)).max(7),linkedGoalIds:_e(je().trim().min(1)),linkedProjectIds:_e(je().trim().min(1)),linkedTaskIds:_e(je().trim().min(1)),linkedValueIds:_e(je().trim().min(1)),linkedPatternIds:_e(je().trim().min(1)),linkedBehaviorIds:_e(je().trim().min(1)),linkedBeliefIds:_e(je().trim().min(1)),linkedModeIds:_e(je().trim().min(1)),linkedReportIds:_e(je().trim().min(1)),linkedBehaviorId:je().trim(),rewardXp:hs.number().int().min(1).max(100),penaltyXp:hs.number().int().min(1).max(100),generatedHealthEventTemplate:Ve({enabled:dn(),workoutType:je().trim(),title:je().trim(),durationMinutes:hs.number().int().min(1).max(1440),xpReward:hs.number().int().min(0).max(500),tags:_e(je().trim()),links:_e(Ve({entityType:je().trim().min(1),entityId:je().trim().min(1),relationshipType:je().trim().default("context")})),notesTemplate:je().trim()})}).superRefine((t,s)=>{t.frequency==="weekly"&&t.weekDays.length===0&&s.addIssue({code:_u.custom,path:["weekDays"],message:"Pick at least one weekday"})}),av=Ve({entityType:vt(["task","project"]),entityId:je().trim().min(1,"A target is required"),deltaMinutes:hs.number().int().refine(t=>t!==0,"Minutes must not be zero"),note:je().trim()});Ve({name:je().trim().min(1,"Name is required"),kind:vt(["value","category","execution"]),userId:je().trim().nullable().optional(),color:je().trim().regex(/^#[0-9a-fA-F]{6}$/,"Color must be a valid hex value"),description:je().trim()});const pr={title:"",description:"",horizon:"year",status:"active",userId:null,targetPoints:400,themeColor:"#c8a46b",tagIds:[],notes:[]};function nv(t){return{title:t.title,description:t.description,horizon:t.horizon,status:t.status,userId:t.userId??null,targetPoints:t.targetPoints,themeColor:t.themeColor,tagIds:t.tagIds,notes:[]}}function Gl({open:t,pending:s=!1,editingGoal:i,tags:a,users:n,defaultUserId:r=null,onOpenChange:l,onSubmit:o}){const{t:c}=lt(),x=n??[],v=x.find(D=>D.id===r)??null,[u,f]=d.useState(pr),[h,m]=d.useState(null),[b,w]=d.useState({}),M=D=>{w(Object.fromEntries(Object.entries(D).map(([j,S])=>[j,S==null?void 0:S[0]])))};d.useEffect(()=>{t&&(m(null),w({}),f(i?nv(i):{...pr,userId:r}))},[r,i,t]);const E=[{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:(D,j)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:c("common.dialogs.goal.title"),error:b.title??null,children:e.jsx(le,{value:D.title,onChange:S=>j({title:S.target.value}),placeholder:"Build a durable body and calm energy"})}),e.jsx(se,{label:c("common.dialogs.goal.descriptionLabel"),children:e.jsx(Me,{value:D.description,onChange:S=>j({description:S.target.value}),placeholder:"Write the goal description in Markdown. This can stay short or grow into a long strategic page."})}),e.jsx(ss,{value:D.userId,users:x,onChange:S=>j({userId:S}),label:"Owner user",defaultLabel:ts(v),help:"Goals can belong to a human or bot user. The current single-user scope becomes the default when one user is selected."})]})},{id:"cadence",eyebrow:"Cadence",title:"Choose the horizon and current posture",description:"Keep this simple: how long does this arc run, and is it currently active, paused, or already complete?",render:(D,j)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:c("common.dialogs.goal.horizon"),children:e.jsx(Ze,{value:D.horizon,onChange:S=>j({horizon:S}),options:[{value:"quarter",label:c("common.enums.goalHorizon.quarter"),description:"Tight strategic push for the coming months."},{value:"year",label:c("common.enums.goalHorizon.year"),description:"A full-cycle objective for this year."},{value:"lifetime",label:c("common.enums.goalHorizon.lifetime"),description:"A long-running life arc that projects can keep serving."}],columns:3})}),e.jsx(se,{label:c("common.dialogs.goal.status"),children:e.jsx(Ze,{value:D.status,onChange:S=>j({status:S}),options:[{value:"active",label:c("common.enums.projectStatus.active"),description:"This is live right now."},{value:"paused",label:c("common.enums.projectStatus.paused"),description:"Keep it visible, but do not push it right now."},{value:"completed",label:c("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:(D,j)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:c("common.dialogs.goal.targetXp"),error:b.targetPoints??null,children:e.jsx(le,{type:"number",value:D.targetPoints,onChange:S=>j({targetPoints:Number(S.target.value)||0})})}),e.jsx(se,{label:c("common.dialogs.goal.themeColor"),error:b.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:D.themeColor,onChange:S=>j({themeColor:S.target.value})}),e.jsx(le,{className:"border-none bg-transparent px-0 py-0",value:D.themeColor,onChange:S=>j({themeColor:S.target.value})})]})}),e.jsx(se,{label:c("common.dialogs.goal.tags"),children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map(S=>{const p=D.tagIds.includes(S.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${p?"bg-white/16 text-white":"bg-white/6 text-white/58 hover:bg-white/10 hover:text-white"}`,onClick:()=>j({tagIds:p?D.tagIds.filter(A=>A!==S.id):[...D.tagIds,S.id]}),children:S.name},S.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:(D,j)=>e.jsx(se,{label:"Creation notes",children:e.jsx(Wl,{notes:D.notes,onChange:S=>j({notes:S}),entityLabel:"goal"})})}];return e.jsx(rt,{open:t,onOpenChange:l,eyebrow:c("common.dialogs.goal.eyebrow"),title:c(i?"common.dialogs.goal.editTitle":"common.dialogs.goal.createTitle"),description:c("common.dialogs.goal.description"),value:u,onChange:f,steps:E,pending:s,pendingLabel:c(i?"common.dialogs.goal.save":"common.dialogs.goal.create"),submitLabel:c(i?"common.dialogs.goal.save":"common.dialogs.goal.create"),error:h,onSubmit:async()=>{m(null);const D=am.safeParse(u);if(!D.success){M(D.error.flatten().fieldErrors),m("Some answers still need attention before this goal arc can be saved.");return}w({});try{await o(D.data,i==null?void 0:i.id),f(pr),l(!1)}catch(j){m(j instanceof Error?j.message:c("common.dialogs.goal.submitError"))}}})}function Ue({user:t,compact:s=!1,className:i}){if(!t)return e.jsx(L,{size:s?"sm":"md",className:re("border-white/10 bg-white/[0.05] text-white/55",i),children:"Unassigned"});const a=t.kind==="bot"?Ui:Qr;return e.jsxs(L,{size:s?"sm":"md",className:re("max-w-full gap-1.5 border text-white",t.kind==="bot"?"border-cyan-300/18 bg-cyan-400/12 text-cyan-50":"border-amber-300/18 bg-amber-400/12 text-amber-50",i),children:[e.jsx(a,{className:"size-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:t.displayName}),e.jsx("span",{className:"text-white/55",children:t.kind})]})}const od={goalId:"",title:"",description:"",status:"active",userId:null,targetPoints:240,themeColor:"#c0c1ff",notes:[]};function rv(t){return{goalId:t.goalId,title:t.title,description:t.description,status:t.status,userId:t.userId??null,targetPoints:t.targetPoints,themeColor:t.themeColor,notes:[]}}function Xl({open:t,goals:s,users:i,editingProject:a,initialGoalId:n,defaultUserId:r=null,onOpenChange:l,onSubmit:o}){const{t:c}=lt(),x=i??[],[v,u]=d.useState(od),[f,h]=d.useState(null),[m,b]=d.useState({}),w=s.find(j=>j.id===v.goalId)??null,M=x.find(j=>j.id===((w==null?void 0:w.userId)??r))??null,E=j=>{b(Object.fromEntries(Object.entries(j).map(([S,p])=>[S,p==null?void 0:p[0]])))};d.useEffect(()=>{var j;t&&(h(null),b({}),u(a?rv(a):{...od,goalId:n??"",userId:((j=s.find(S=>S.id===n))==null?void 0:j.userId)??r}))},[r,a,s,n,t]);const D=[{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:(j,S)=>e.jsx(se,{label:c("common.dialogs.project.goal"),error:m.goalId??null,children:e.jsx("div",{className:"grid gap-3",children:s.map(p=>{const A=p.id===j.goalId;return e.jsxs("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${A?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.14)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"}`,onClick:()=>S({goalId:p.id}),children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx(Xe,{kind:"goal",label:p.title,className:"max-w-full"}),e.jsx(Ue,{user:p.user,compact:!0})]}),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:(j,S)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:c("common.dialogs.project.title"),error:m.title??null,children:e.jsx(le,{value:j.title,onChange:p=>S({title:p.target.value}),placeholder:"Launch the new creative practice system"})}),e.jsx(se,{label:c("common.dialogs.project.descriptionLabel"),children:e.jsx(Me,{value:j.description,onChange:p=>S({description:p.target.value}),placeholder:"Write the project description in Markdown. Use as much detail as the workstream needs."})}),e.jsx(ss,{value:j.userId,users:x,onChange:p=>S({userId:p}),label:"Owner user",defaultLabel:ts(M),help:"Projects can intentionally cross user boundaries, but the linked goal owner is suggested by default."})]})},{id:"signal",eyebrow:"Signal",title:"Set the project's posture and progress target",description:"This keeps the board, reward system, and detail views aligned without forcing you through a giant settings form.",render:(j,S)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:c("common.dialogs.project.status"),children:e.jsx(Ze,{value:j.status,onChange:p=>S({status:p}),options:[{value:"active",label:c("common.enums.projectStatus.active"),description:"Push this initiative now."},{value:"paused",label:c("common.enums.projectStatus.paused"),description:"Keep it available without active pressure."},{value:"completed",label:c("common.enums.projectStatus.completed"),description:"This initiative has landed."}]})}),e.jsx(se,{label:c("common.dialogs.project.targetXp"),error:m.targetPoints??null,children:e.jsx(le,{type:"number",value:j.targetPoints,onChange:p=>S({targetPoints:Number(p.target.value)||0})})}),e.jsx(se,{label:c("common.dialogs.project.themeColor"),error:m.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:j.themeColor,onChange:p=>S({themeColor:p.target.value})}),e.jsx(le,{className:"border-none bg-transparent px-0 py-0",value:j.themeColor,onChange:p=>S({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:(j,S)=>e.jsx(se,{label:"Creation notes",children:e.jsx(Wl,{notes:j.notes,onChange:p=>S({notes:p}),entityLabel:"project"})})}];return e.jsx(rt,{open:t,onOpenChange:l,eyebrow:c("common.dialogs.project.eyebrow"),title:c(a?"common.dialogs.project.editTitle":"common.dialogs.project.createTitle"),description:c("common.dialogs.project.description"),value:v,onChange:u,steps:D,submitLabel:c(a?"common.dialogs.project.save":"common.dialogs.project.create"),error:f,onSubmit:async()=>{h(null);const j=nm.safeParse(v);if(!j.success){E(j.error.flatten().fieldErrors),h("A couple of answers still need attention before this project can be saved.");return}b({});try{await o(j.data,a==null?void 0:a.id),l(!1)}catch(S){h(S instanceof Error?S.message:c("common.dialogs.project.submitError"))}}})}const xr={title:"",description:"",owner:"Albert",userId:null,goalId:"",projectId:"",priority:"medium",status:"focus",effort:"deep",energy:"steady",dueDate:"",points:60,tagIds:[],notes:[]};function lv(t){return{title:t.title,description:t.description,owner:t.owner,userId:t.userId??null,goalId:t.goalId??"",projectId:t.projectId??"",priority:t.priority,status:t.status,effort:t.effort,energy:t.energy,dueDate:t.dueDate??"",points:t.points,tagIds:t.tagIds,notes:[]}}function Jn({open:t,goals:s,projects:i,tags:a,users:n,editingTask:r,initialProjectId:l,defaultUserId:o=null,onOpenChange:c,onSubmit:x}){const{t:v}=lt(),u=s??[],f=i??[],h=a??[],m=n??[],[b,w]=d.useState(xr),[M,E]=d.useState(null),[D,j]=d.useState({}),S=k=>{j(Object.fromEntries(Object.entries(k).map(([$,g])=>[$,g==null?void 0:g[0]])))};d.useEffect(()=>{var k,$,g;t&&(E(null),j({}),w(r?lv(r):{...xr,owner:((k=m.find(C=>{var F;return C.id===(((F=f.find(z=>z.id===l))==null?void 0:F.userId)??o)}))==null?void 0:k.displayName)??xr.owner,userId:(($=f.find(C=>C.id===l))==null?void 0:$.userId)??o,projectId:l??"",goalId:((g=f.find(C=>C.id===l))==null?void 0:g.goalId)??""}))},[o,r,l,t,f,m]);const p=d.useMemo(()=>f.find(k=>k.id===b.projectId)??null,[b.projectId,f]),A=m.find(k=>k.id===((p==null?void 0:p.userId)??o))??null;d.useEffect(()=>{p&&b.goalId!==p.goalId&&w(k=>({...k,goalId:p.goalId}))},[b.goalId,p]);const T=[{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:(k,$)=>{var g;return e.jsxs(e.Fragment,{children:[e.jsx(se,{label:v("common.dialogs.task.project"),labelHelp:"Projects are the main home for tasks. Pick the stream of work this task belongs to.",error:D.projectId??null,children:e.jsx("div",{className:"grid gap-3",children:f.map(C=>{const F=C.id===k.projectId;return e.jsxs("button",{type:"button",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.07]"}`,onClick:()=>$({projectId:C.id,goalId:C.goalId}),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(Xe,{kind:"project",label:C.title,className:"min-w-0",showIcon:!1}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e.jsx(Te,{kind:"goal",label:C.goalTitle,compact:!0,gradient:!1}),e.jsx(Ue,{user:C.user,compact:!0})]})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:C.description})]},C.id)})})}),e.jsx(se,{label:v("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(le,{readOnly:!0,value:p?((g=u.find(C=>C.id===p.goalId))==null?void 0:g.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:(k,$)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:v("common.dialogs.task.title"),error:D.title??null,children:e.jsx(le,{value:k.title,onChange:g=>$({title:g.target.value}),placeholder:"Draft the first mode atlas sketch"})}),e.jsx(se,{label:v("common.dialogs.task.descriptionLabel"),children:e.jsx(Me,{value:k.description,onChange:g=>$({description:g.target.value}),placeholder:"Write the task description in Markdown. Keep it short or turn it into a full acceptance doc."})}),e.jsx(se,{label:v("common.dialogs.task.owner"),labelHelp:"The owner is the person or role expected to carry this task.",error:D.owner??null,children:e.jsx(le,{value:k.owner,onChange:g=>$({owner:g.target.value}),placeholder:"Albert"})}),e.jsx(ss,{value:k.userId,users:m,onChange:g=>{var C;return $({userId:g,owner:((C=m.find(F=>F.id===g))==null?void 0:C.displayName)??k.owner})},label:"Owner user",defaultLabel:ts(A),help:"Tasks can belong to a human or bot user. The linked project owner is suggested first so cross-user task routing stays explicit."})]})},{id:"execution",eyebrow:"Execution",title:"Set priority, status, effort, and energy",description:"This is the minimum the execution engine needs in order to place the task well and show the right next move.",render:(k,$)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:v("common.dialogs.task.priority"),labelHelp:"Priority controls how strongly Forge should surface this task in the board and daily views.",children:e.jsx(Ze,{value:k.priority,onChange:g=>$({priority:g}),options:[{value:"low",label:v("common.enums.priority.low")},{value:"medium",label:v("common.enums.priority.medium")},{value:"high",label:v("common.enums.priority.high")},{value:"critical",label:v("common.enums.priority.critical")}]})}),e.jsx(se,{label:v("common.dialogs.task.status"),labelHelp:"Status tells Forge whether the task is waiting, ready for focus, active, blocked, or done.",children:e.jsx(Ze,{value:k.status,onChange:g=>$({status:g}),options:[{value:"backlog",label:v("common.enums.taskStatus.backlog")},{value:"focus",label:v("common.enums.taskStatus.focus")},{value:"in_progress",label:v("common.enums.taskStatus.in_progress")},{value:"blocked",label:v("common.enums.taskStatus.blocked")}]})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(se,{label:v("common.dialogs.task.effort"),labelHelp:"Effort describes how much concentration and time this task usually needs.",children:e.jsx(Ze,{value:k.effort,onChange:g=>$({effort:g}),options:[{value:"light",label:v("common.enums.effort.light")},{value:"deep",label:v("common.enums.effort.deep")},{value:"marathon",label:v("common.enums.effort.marathon")}]})}),e.jsx(se,{label:v("common.dialogs.task.energy"),labelHelp:"Energy helps you match this task to a low-energy, steady, or high-energy moment.",children:e.jsx(Ze,{value:k.energy,onChange:g=>$({energy:g}),options:[{value:"low",label:v("common.enums.energy.low")},{value:"steady",label:v("common.enums.energy.steady")},{value:"high",label:v("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:(k,$)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(se,{label:v("common.dialogs.task.xp"),labelHelp:"XP is the reward weight for finishing this task. Higher XP should mean more meaningful work.",error:D.points??null,children:e.jsx(le,{type:"number",value:k.points,onChange:g=>$({points:Number(g.target.value)||0}),placeholder:"60"})}),e.jsx(se,{label:v("common.dialogs.task.dueDate"),labelHelp:"Only add a due date when timing really matters for this task.",children:e.jsx(le,{type:"date",value:k.dueDate,onChange:g=>$({dueDate:g.target.value})})})]}),e.jsx(se,{label:v("common.dialogs.task.tags"),children:e.jsx("div",{className:"flex flex-wrap gap-2",children:h.map(g=>{const C=k.tagIds.includes(g.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${C?"bg-white/16 text-white":"bg-white/6 text-white/58 hover:bg-white/10 hover:text-white"}`,onClick:()=>$({tagIds:C?k.tagIds.filter(F=>F!==g.id):[...k.tagIds,g.id]}),children:g.name},g.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:(k,$)=>e.jsx(se,{label:"Creation notes",children:e.jsx(Wl,{notes:k.notes,onChange:g=>$({notes:g}),entityLabel:"task"})})}];return e.jsx(rt,{open:t,onOpenChange:c,eyebrow:v("common.dialogs.task.eyebrow"),title:v(r?"common.dialogs.task.editTitle":"common.dialogs.task.createTitle"),description:v("common.dialogs.task.description"),value:b,onChange:w,steps:T,submitLabel:v(r?"common.dialogs.task.save":"common.dialogs.task.create"),error:M,onSubmit:async()=>{E(null);const k=rm.safeParse(b);if(!k.success){S(k.error.flatten().fieldErrors),E("A few task details still need attention before this move can be saved.");return}j({});try{await x(k.data,r==null?void 0:r.id),c(!1)}catch($){E($ instanceof Error?$.message:"Unable to save this task right now.")}}})}const dd="(max-width: 1023px)";function ov(){const[t,s]=d.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(dd).matches);return d.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const i=window.matchMedia(dd),a=n=>{s(n.matches)};return s(i.matches),typeof i.addEventListener=="function"?(i.addEventListener("change",a),()=>i.removeEventListener("change",a)):(i.addListener(a),()=>i.removeListener(a))},[]),t}function cd({kind:t,title:s,description:i,onClick:a}){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:a,children:[e.jsx(Te,{kind:t,label:s,compact:!0,gradient:!1,className:"max-w-full"}),e.jsx("div",{className:"mt-1 text-sm text-white/55",children:i})]})}function dv({goals:t,projects:s,tags:i,users:a,defaultUserId:n=null,onCreateGoal:r,onCreateProject:l,onCreateTask:o,className:c}){const{t:x}=lt(),v=ut(),u=t??[],f=s??[],h=i??[],m=a??[],[b,w]=d.useState(!1),[M,E]=d.useState(!1),[D,j]=d.useState(!1),[S,p]=d.useState(!1),[A,T]=d.useState(null),k=ov(),$=d.useRef(null),g=d.useRef(null);d.useEffect(()=>{if(!b||k)return;const F=()=>{var _;const O=(_=$.current)==null?void 0:_.getBoundingClientRect();O&&T({top:Math.max(24,O.top-18),right:Math.max(24,window.innerWidth-O.right)})};F();const z=O=>{var _,B;(_=$.current)!=null&&_.contains(O.target)||(B=g.current)!=null&&B.contains(O.target)||w(!1)},J=O=>{O.key==="Escape"&&w(!1)};return document.addEventListener("pointerdown",z),document.addEventListener("keydown",J),window.addEventListener("resize",F),window.addEventListener("scroll",F,!0),()=>{document.removeEventListener("pointerdown",z),document.removeEventListener("keydown",J),window.removeEventListener("resize",F),window.removeEventListener("scroll",F,!0)}},[k,b]);const C=[{id:"goal",kind:"goal",group:"Execution",title:x("common.navigation.newGoal"),description:x("common.navigation.newGoalDescription"),onSelect:()=>{w(!1),E(!0)}},{id:"project",kind:"project",group:"Execution",title:x("common.navigation.newProject"),description:x("common.navigation.newProjectDescription"),onSelect:()=>{w(!1),j(!0)}},{id:"task",kind:"task",group:"Execution",title:x("common.navigation.newTask"),description:x("common.navigation.newTaskDescription"),onSelect:()=>{w(!1),p(!0)}},{id:"strategy",kind:"strategy",group:"Execution",title:"Strategy",description:"Plan a directed path across projects and tasks toward a real end state.",onSelect:()=>{w(!1),v("/strategies?create=1")}},{id:"habit",kind:"habit",group:"Execution",title:"Habit",description:"Track a recurring commitment or recurring slip with explicit XP logic.",onSelect:()=>{w(!1),v("/habits?create=1")}},{id:"value",kind:"value",group:"Psyche",title:"Value",description:"Place one value into the goal, project, and task constellation.",onSelect:()=>{w(!1),v("/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:()=>{w(!1),v("/psyche/patterns?create=1")}},{id:"behavior",kind:"behavior",group:"Psyche",title:"Behavior",description:"Describe the move first, then classify it and link it.",onSelect:()=>{w(!1),v("/psyche/behaviors?create=1")}},{id:"report",kind:"report",group:"Psyche",title:"Report",description:"Start a Spark-to-Pivot reflective chain.",onSelect:()=>{w(!1),v("/psyche/reports?create=1")}}];return e.jsxs(e.Fragment,{children:[e.jsx("div",{ref:$,className:c,style:k?{right:"max(1rem, calc(var(--forge-safe-area-right) + 1rem))",bottom:"var(--forge-mobile-create-bottom)"}:void 0,children:e.jsxs(Q,{type:"button","data-testid":"create-floating-trigger","aria-expanded":b,"aria-haspopup":"dialog",onClick:()=>w(F=>k?!0:!F),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)] ${b?"bg-[linear-gradient(135deg,rgba(192,193,255,0.52),rgba(125,211,252,0.24))] text-white":""}`,children:[e.jsx(Tt,{className:`size-4 transition ${b?"text-white":"text-white/72"}`}),x("common.navigation.create")]})}),b&&!k&&typeof document<"u"&&A?zn.createPortal(e.jsxs("div",{ref:g,"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:`${A.top}px`,right:`${A.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(F=>e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:F}),e.jsx("div",{className:"mt-2 grid gap-2",children:C.filter(z=>z.group===F).map(z=>e.jsx(cd,{kind:z.kind,title:z.title,description:z.description,onClick:z.onSelect},z.id))})]},F))]}),document.body):null,e.jsx(Et,{open:b&&k,onOpenChange:w,children:e.jsxs(Lt,{children:[e.jsx(Dt,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.72)] backdrop-blur-xl lg:hidden"}),e.jsxs($t,{"data-testid":"create-mobile-sheet",className:"fixed inset-x-4 bottom-28 z-50 flex max-h-[min(30rem,calc(100vh-8rem))] flex-col overflow-hidden rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(24,31,50,0.98),rgba(15,21,36,0.98))] p-0 shadow-[0_30px_90px_rgba(3,8,18,0.45)] lg:hidden",style:{left:"max(1rem, calc(var(--forge-safe-area-left) + 1rem))",right:"max(1rem, calc(var(--forge-safe-area-right) + 1rem))",bottom:"calc(var(--forge-mobile-nav-clearance) - 0.5rem)"},children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 border-b border-white/8 px-5 py-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:x("common.navigation.create")}),e.jsx(Ot,{className:"mt-2 font-display text-2xl text-white",children:x("common.navigation.createTitle")}),e.jsx(qt,{className:"mt-2 text-sm leading-6 text-white/60",children:x("common.navigation.createDescription")})]}),e.jsx(Ft,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":x("common.navigation.closeCreateMenu"),className:"rounded-full bg-white/6 p-2 text-white/65 transition hover:bg-white/10 hover:text-white",children:e.jsx(mt,{className:"size-4"})})})]}),e.jsx("div",{className:"overflow-y-auto p-4 overscroll-contain",children:["Execution","Psyche"].map(F=>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:F}),C.filter(z=>z.group===F).map(z=>e.jsx(cd,{kind:z.kind,title:z.title,description:z.description,onClick:z.onSelect},z.id))]},F))})]})]})}),e.jsx(Gl,{open:M,editingGoal:null,tags:h,users:m,defaultUserId:n,onOpenChange:E,onSubmit:async F=>{await r(F)}}),e.jsx(Xl,{open:D,goals:u,users:m,editingProject:null,defaultUserId:n,onOpenChange:j,onSubmit:async F=>{await l(F)}}),e.jsx(Jn,{open:S,goals:u,projects:f,tags:h,users:m,editingTask:null,defaultUserId:n,onOpenChange:p,onSubmit:async F=>{await o(F)}})]})}function ae({className:t,...s}){return e.jsx("div",{className:re("w-full max-w-full min-w-0 rounded-[var(--radius-card)] bg-[var(--card-gradient)] p-4 shadow-[var(--card-shadow)] backdrop-blur-sm",t),...s})}const fa=[{to:"/psyche",label:"Overview",icon:bl},{to:"/psyche/values",label:"Values",icon:Ru},{to:"/psyche/patterns",label:"Patterns",icon:zu},{to:"/psyche/questionnaires",label:"Questionnaires",icon:qu},{to:"/psyche/self-observation",label:"Self Observation",icon:ah},{to:"/psyche/behaviors",label:"Behaviors",icon:Bu},{to:"/psyche/reports",label:"Reports",icon:Tt},{to:"/psyche/goal-map",label:"Goal Map",icon:Ku},{to:"/psyche/schemas-beliefs",label:"Schemas & Beliefs",icon:Uu},{to:"/psyche/modes",label:"Modes",icon:Qu},{to:"/preferences",label:"Preferences",icon:Aa},{to:"/sleep",label:"Sleep",icon:nh}];function gr(t,s){return s==="/psyche"?t==="/psyche":t===s||t.startsWith(`${s}/`)}function Bt({className:t}){const s=fi(),[i,a]=d.useState(!1),n=d.useMemo(()=>[...fa].sort((r,l)=>l.to.length-r.to.length).find(r=>gr(s.pathname,r.to))??fa[0],[s.pathname]);return d.useEffect(()=>{if(!i)return;const r=document.body.style.overflow,l=document.body.style.touchAction,o=c=>{c.key==="Escape"&&a(!1)};return document.body.style.overflow="hidden",document.body.style.touchAction="none",window.addEventListener("keydown",o),()=>{document.body.style.overflow=r,document.body.style.touchAction=l,window.removeEventListener("keydown",o)}},[i]),e.jsxs(e.Fragment,{children:[e.jsxs(ae,{className:re("overflow-hidden bg-[linear-gradient(180deg,rgba(15,24,31,0.94),rgba(10,18,25,0.92))] p-2",t),children:[e.jsx("div",{className:"hidden items-center gap-3 lg:flex",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:fa.map(r=>e.jsxs(hi,{to:r.to,end:r.to==="/psyche",className:({isActive:l})=>re("inline-flex items-center gap-2 whitespace-nowrap rounded-full px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] transition",l||gr(s.pathname,r.to)?"bg-[rgba(110,231,183,0.18)] text-[var(--tertiary)]":"bg-white/[0.04] text-white/58 hover:bg-white/[0.08] hover:text-white"),children:[e.jsx(r.icon,{className:"size-3.5"}),e.jsx("span",{children:r.label})]},r.to))})}),e.jsx("div",{className:"flex items-center justify-between gap-3 lg:hidden",children:e.jsx("button",{type:"button",className:"inline-flex min-w-0 flex-1 items-center gap-3 rounded-[22px] border border-white/8 bg-[linear-gradient(180deg,rgba(19,28,42,0.96),rgba(11,17,30,0.94))] px-3.5 py-2.5 text-left shadow-[0_18px_38px_rgba(3,8,18,0.2)] transition hover:border-white/12 hover:bg-[linear-gradient(180deg,rgba(24,34,50,0.98),rgba(12,19,34,0.96))]",onClick:()=>a(!0),children:e.jsxs("span",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-2xl border border-[rgba(110,231,183,0.2)] bg-[rgba(110,231,183,0.12)]",children:e.jsx(n.icon,{className:"size-4 text-[var(--tertiary)]"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[10px] uppercase tracking-[0.18em] text-white/40",children:"Psyche section"}),e.jsx("span",{className:"mt-0.5 block truncate text-sm font-medium text-white",children:n.label})]})]})})})]}),i&&typeof document<"u"?zn.createPortal(e.jsxs("div",{className:"lg:hidden",children:[e.jsx("div",{className:"fixed inset-0 z-50 bg-[rgba(5,10,18,0.78)] backdrop-blur-xl"}),e.jsx("button",{type:"button","aria-label":"Close psyche sections",className:"fixed inset-0 z-[51]",onClick:()=>a(!1)}),e.jsx("div",{className:"pointer-events-none fixed inset-0 z-[52] flex items-end justify-center px-3 pt-3 sm:px-4 sm:pt-4",style:{paddingLeft:"max(0.75rem, calc(var(--forge-safe-area-left) + 0.75rem))",paddingRight:"max(0.75rem, calc(var(--forge-safe-area-right) + 0.75rem))",paddingTop:"max(0.75rem, calc(env(safe-area-inset-top) + 0.75rem))",paddingBottom:"calc(var(--forge-mobile-nav-clearance) - 0.25rem)"},children:e.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Psyche sections",className:"pointer-events-auto flex max-h-[min(34rem,calc(100dvh-var(--forge-mobile-nav-clearance)-1rem))] w-full max-w-xl min-h-0 flex-col overflow-hidden rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top,rgba(110,231,183,0.12),transparent_40%),linear-gradient(180deg,rgba(18,27,42,0.98),rgba(10,15,28,0.98))] shadow-[0_36px_110px_rgba(3,8,18,0.5)]",children:[e.jsx("div",{className:"shrink-0 border-b border-white/8 px-4 pb-2.5 pt-3 sm:px-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-white/38",children:"Psyche sections"}),e.jsxs("div",{className:"mt-1.5 flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx("div",{className:"truncate text-[1.05rem] font-semibold text-white",children:"Move through Psyche"}),e.jsx("span",{className:"rounded-full border border-[rgba(110,231,183,0.18)] bg-[rgba(110,231,183,0.12)] px-2.5 py-1 text-[10px] uppercase tracking-[0.16em] text-[var(--tertiary)]",children:n.label})]})]}),e.jsx("button",{type:"button","aria-label":"Close psyche sections",className:"inline-flex size-10 shrink-0 items-center justify-center rounded-full border border-white/8 bg-white/[0.05] text-white/65 transition hover:border-white/12 hover:bg-white/[0.09] hover:text-white",onClick:()=>a(!1),children:e.jsx(mt,{className:"size-4"})})]})}),e.jsx("div",{className:"min-h-0 overflow-y-auto p-3 overscroll-contain sm:p-4",children:e.jsx("div",{className:"grid gap-2",children:fa.map(r=>{const l=gr(s.pathname,r.to);return e.jsxs(hi,{to:r.to,end:r.to==="/psyche",onClick:()=>a(!1),className:re("group flex items-center justify-between gap-3 rounded-[22px] border px-3.5 py-3 transition-[transform,border-color,background-color,color] duration-150 hover:-translate-y-[1px] hover:text-white",l?"border-[rgba(110,231,183,0.18)] bg-[rgba(110,231,183,0.12)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:border-white/12 hover:bg-white/[0.06]"),children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:re("flex size-10 shrink-0 items-center justify-center rounded-2xl border transition",l?"border-[rgba(110,231,183,0.18)] bg-[rgba(110,231,183,0.14)] text-[var(--tertiary)]":"border-white/8 bg-[rgba(255,255,255,0.03)] text-white/58 group-hover:border-white/12 group-hover:text-white/80"),children:e.jsx(r.icon,{className:"size-4"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate text-sm font-semibold text-white",children:r.label}),e.jsx("span",{className:"mt-0.5 block text-[10px] uppercase tracking-[0.16em] text-white/35",children:r.to==="/preferences"?"Preference system":"Psyche workspace"})]})]}),e.jsx("span",{className:re("rounded-full px-2.5 py-1 text-[10px] uppercase tracking-[0.16em]",l?"bg-[rgba(110,231,183,0.16)] text-[var(--tertiary)]":"bg-white/[0.05] text-white/42"),children:l?"Current":"Open"})]},r.to)})})})]})})]}),document.body):null]})}function cv(t){return t===null?"20":String(Math.max(1,Math.round(t/60)))}function hv({tasks:t,projects:s,activeRunCount:i,maxActiveTasks:a,timeAccountingMode:n,pending:r,errorMessage:l,initialTaskId:o,defaultProjectId:c,onCancel:x,onStartExisting:v,onCreateAndStart:u}){const[f,h]=d.useState("existing"),[m,b]=d.useState(""),[w,M]=d.useState(o??null),[E,D]=d.useState(""),[j,S]=d.useState(""),[p,A]=d.useState(c??""),[T,k]=d.useState("planned"),[$,g]=d.useState("20");d.useEffect(()=>{h(o?"existing":"new"),b(""),M(o??null),D(""),S(""),A(c??""),k("planned"),g("20")},[c,o]);const C=d.useMemo(()=>t.filter(B=>B.status!=="done").sort((B,K)=>B.time.hasCurrentRun!==K.time.hasCurrentRun?Number(K.time.hasCurrentRun)-Number(B.time.hasCurrentRun):B.status!==K.status?B.status.localeCompare(K.status):B.title.localeCompare(K.title)),[t]),F=d.useMemo(()=>{const B=m.trim().toLowerCase();return B?C.filter(K=>{var U,I,G,W,ne,de;const Z=s.find(we=>we.id===K.projectId);return[K.title,K.description,K.owner,((U=K.user)==null?void 0:U.displayName)??"",((I=K.user)==null?void 0:I.handle)??"",((G=K.user)==null?void 0:G.kind)??"",(Z==null?void 0:Z.title)??"",((W=Z==null?void 0:Z.user)==null?void 0:W.displayName)??"",((ne=Z==null?void 0:Z.user)==null?void 0:ne.handle)??"",((de=Z==null?void 0:Z.user)==null?void 0:de.kind)??""].some(we=>we.toLowerCase().includes(B))}):C},[s,C,m]),z=d.useMemo(()=>s.find(B=>B.id===p)??null,[p,s]),J=T==="planned"?Math.max(60,(Number.parseInt($,10)||20)*60):null,O=f==="existing"?!!w:!!(E.trim()&&p),_=n==="split"?"Split time":n==="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(L,{className:"bg-white/[0.08] text-white/72",children:[i,"/",a," live"]}),e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:_})]})]}),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(B=>{const K=f===B.value;return e.jsxs("button",{type:"button",className:re("rounded-[18px] border px-4 py-4 text-left transition",K?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.14)] text-white":"border-white/8 bg-white/[0.04] text-white/65 hover:bg-white/[0.07]"),onClick:()=>h(B.value),children:[e.jsx("div",{className:"font-medium",children:B.label}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-inherit/80",children:B.detail})]},B.value)})}),f==="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(bt,{className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-white/32"}),e.jsx(le,{value:m,onChange:B=>b(B.target.value),placeholder:"Search task, project, human, bot, or owner",className:"pl-10"})]})]}),e.jsx("div",{className:"grid max-h-[19rem] gap-2 overflow-y-auto rounded-[20px] bg-white/[0.03] p-2",children:F.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."}):F.slice(0,16).map(B=>{const K=w===B.id,Z=s.find(U=>U.id===B.projectId);return e.jsx("button",{type:"button",className:re("rounded-[16px] border px-4 py-3 text-left transition",K?"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:()=>M(B.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(Xe,{kind:"task",label:B.title,className:"max-w-full"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[Z?e.jsx(Te,{kind:"project",label:Z.title,compact:!0,gradient:!1}):null,e.jsx(L,{className:"bg-white/[0.08] text-white/70",children:B.status.replaceAll("_"," ")}),B.time.activeRunCount>0?e.jsxs(L,{className:"bg-emerald-500/12 text-emerald-200",children:[B.time.activeRunCount," live"]}):null]})]}),e.jsxs("span",{className:"text-[12px] text-white/45",children:[B.points," xp"]})]})},B.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(le,{value:E,onChange:B=>D(B.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(Me,{value:j,onChange:B=>S(B.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:p,onChange:B=>A(B.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(B=>e.jsx("option",{value:B.id,children:B.user?`${B.title} · ${B.user.displayName} (${B.user.kind})`:B.title},B.id))]})]}),z?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:z.title}),z.user?` for ${z.user.displayName} (${z.user.kind})`:""," ","and started immediately."]}):null]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("span",{className:"type-label text-white/45",children:"Timer"}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_8rem]",children:[[{value:"planned",label:"20 min planned",detail:"Pomodoro-style by default."},{value:"unlimited",label:"Unlimited",detail:"Keep tracking until you stop."}].map(B=>{const K=T===B.value;return e.jsxs("button",{type:"button",className:re("rounded-[18px] border px-4 py-3 text-left transition",K?"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:()=>k(B.value),children:[e.jsx("div",{className:"font-medium",children:B.label}),e.jsx("div",{className:"mt-1.5 text-sm leading-6 text-inherit/80",children:B.detail})]},B.value)}),e.jsxs("label",{className:re("grid gap-2",T!=="planned"&&"opacity-50"),children:[e.jsx("span",{className:"type-label text-white/45",children:"Minutes"}),e.jsx(le,{type:"number",min:1,max:240,disabled:T!=="planned",value:$,onChange:B=>g(B.target.value)})]})]})]}),l?e.jsx("div",{className:"rounded-[18px] bg-rose-500/10 px-4 py-3 text-sm leading-6 text-rose-200",children:l}):null,e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-t border-white/6 pt-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 text-[12px] text-white/45",children:[e.jsx("div",{className:"rounded-full bg-white/[0.05] px-3 py-2",children:"Starts in progress"}),e.jsx("div",{className:"rounded-full bg-white/[0.05] px-3 py-2",children:T==="planned"?`${cv(J)} min target`:"Unlimited timer"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Q,{variant:"secondary",size:"lg",onClick:x,children:"Cancel"}),e.jsxs(Q,{size:"lg",pending:r,pendingLabel:"Starting",disabled:!O,onClick:async()=>{if(O){if(f==="existing"&&w){await v(w,{timerMode:T,plannedDurationSeconds:J});return}await u({title:E.trim(),description:j.trim(),projectId:p,timerMode:T,plannedDurationSeconds:J})}},children:[f==="existing"?e.jsx(bn,{className:"size-4"}):e.jsx(rh,{className:"size-4"}),"Start work",e.jsx(Cs,{className:"size-4"})]})]})]})]})}function hd({open:t,onOpenChange:s,presentation:i="responsive",...a}){const n=e.jsx(hv,{...a,onCancel:()=>s(!1)});return e.jsxs(e.Fragment,{children:[t&&i!=="mobile_sheet"?e.jsx("div",{className:"hidden lg:block",children:e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(17,24,39,0.98),rgba(11,16,28,0.97))] p-4 shadow-[0_24px_60px_rgba(3,8,18,0.28)]",children:[e.jsx("div",{className:"mb-3 flex justify-end",children:e.jsxs(Q,{variant:"ghost",size:"sm",className:"px-3",onClick:()=>s(!1),children:[e.jsx(mt,{className:"size-4"}),"Close"]})}),n]})}):null,i!=="desktop_inline"?e.jsx("div",{className:i==="responsive"?"lg:hidden":"",children:e.jsx(bs,{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:n})}):null]})}const Vl=d.createContext({expanded:!1,setExpanded:()=>{}});function md({children:t}){const[s,i]=d.useState(!1),a=d.useRef(0);return d.useEffect(()=>{if(!s)return;a.current=performance.now();let n=window.scrollY;const r=()=>{if(performance.now()-a.current<280){n=window.scrollY;return}window.scrollY-n>16&&i(!1),n=window.scrollY};return window.addEventListener("scroll",r,{passive:!0}),()=>window.removeEventListener("scroll",r)},[s]),e.jsx(Vl.Provider,{value:{expanded:s,setExpanded:i},children:t})}function $i(t){const s=Math.max(0,Math.floor(t)),i=Math.floor(s/3600),a=Math.floor(s%3600/60),n=s%60;return i>0?`${i}:${String(a).padStart(2,"0")}:${String(n).padStart(2,"0")}`:`${String(a).padStart(2,"0")}:${String(n).padStart(2,"0")}`}function mv(t,s,i,a,n){const r=Math.max(1,t.length),l=Date.parse(i),o=Number.isFinite(l)?Math.max(0,Math.floor((n-l)/1e3)):0;return t.map(c=>{const x=s.find(b=>b.id===c.taskId),v=c.status==="active"?c.elapsedWallSeconds+o:c.elapsedWallSeconds,u=c.status!=="active"?0:a==="parallel"?o:a==="split"?o/r:c.isCurrent?o:0,f=c.creditedSeconds+u,h=c.timerMode==="planned"&&c.plannedDurationSeconds!==null?Math.max(0,c.plannedDurationSeconds-v):null,m=c.timerMode==="planned"&&c.plannedDurationSeconds!==null?Math.max(0,v-c.plannedDurationSeconds):0;return{run:c,title:(x==null?void 0:x.title)??c.taskTitle,wallSeconds:v,creditedSeconds:f,remainingSeconds:h,overtimeSeconds:m}}).sort((c,x)=>Number(x.run.isCurrent)-Number(c.run.isCurrent))}function lm(t,s,i,a){const[n,r]=d.useState(()=>Date.now());return d.useEffect(()=>{if(t.length===0)return;const l=window.setInterval(()=>r(Date.now()),1e3);return()=>window.clearInterval(l)},[t.length]),d.useMemo(()=>mv(t,s,i,a,n),[i,n,t,s,a])}function ud({runs:t,tasks:s,generatedAt:i,timeAccountingMode:a,pending:n,onOpenStartWork:r,onPause:l,onFocus:o}){const{expanded:c,setExpanded:x}=d.useContext(Vl),v=lm(t,s,i,a),u=v.find(h=>h.run.isCurrent)??v[0]??null,f=u?v.filter(h=>h.run.id!==u.run.id):[];return u?e.jsxs("div",{className:re("flex min-h-[2.125rem] min-w-0 items-center rounded-full border border-white/8 bg-white/[0.04] transition-colors",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:()=>x(h=>!h),children:[e.jsx(bn,{className:"size-3.5 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"truncate text-[12px] font-medium text-white",children:u.title}),e.jsx("span",{className:"shrink-0 text-[11px] tabular-nums text-white/44",children:$i(u.creditedSeconds)})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 pr-1",children:[f.length>0?e.jsx("button",{type:"button",title:"Switch to next task",disabled:n,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 o(f[0].run.id),children:v.length}):null,e.jsx("button",{type:"button",title:"Stop",disabled:n,className:"inline-flex size-6 items-center justify-center rounded-full text-white/50 transition hover:bg-white/[0.1] hover:text-white disabled:pointer-events-none disabled:opacity-70",onClick:()=>void l(u.run.id),children:e.jsx(Wu,{className:"size-2.5 fill-current"})}),e.jsx("button",{type:"button",title:"Start new work",disabled:n,className:"inline-flex size-6 items-center justify-center rounded-full text-white/50 transition hover:bg-white/[0.1] hover:text-white disabled:pointer-events-none disabled:opacity-70",onClick:()=>r(),children:e.jsx(Cs,{className:"size-2.5 fill-current"})})]})]}):e.jsxs("div",{className:"flex min-h-[2.125rem] min-w-0 items-center gap-1.5 rounded-full border border-white/8 bg-white/[0.04] py-1 pl-2.5 pr-1",children:[e.jsx(bn,{className:"size-3.5 shrink-0 text-white/48"}),e.jsx("span",{className:"truncate text-[12px] text-white/48",children:"No active work"}),e.jsx("button",{type:"button",className:"ml-auto inline-flex h-[1.5rem] shrink-0 items-center rounded-full bg-white/10 px-2 text-[11px] font-medium text-white transition hover:bg-white/15",onClick:r,children:"Start work"})]})}function pd({runs:t,tasks:s,generatedAt:i,timeAccountingMode:a,pending:n,onOpenStartWork:r,onFocus:l,onPause:o,onComplete:c}){const{expanded:x}=d.useContext(Vl),v=lm(t,s,i,a),u=v.find(m=>m.run.isCurrent)??v[0]??null,f=u?v.filter(m=>m.run.id!==u.run.id):[],h=a==="split"&&v.length>1?`Split across ${v.length} active tasks`:a==="parallel"&&v.length>1?`Parallel time across ${v.length} active tasks`:a==="primary_only"&&v.length>1?"Only the current task is earning credited time":null;return u?e.jsx(wn,{initial:!1,children:x?e.jsx(Kt.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(L,{tone:"signal",className:"text-white/82",children:"Current task"}),e.jsx(L,{tone:"meta",children:u.run.timerMode==="planned"?"Planned timer":"Unlimited timer"}),h?e.jsx(L,{tone:"meta",children:h}):null]}),e.jsx("div",{className:"mt-3 text-xl font-medium text-white md:text-2xl",children:u.title}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-4 text-sm text-white/62",children:[e.jsxs("span",{children:[$i(u.creditedSeconds)," credited"]}),e.jsxs("span",{children:[$i(u.wallSeconds)," wall time"]}),u.run.timerMode==="planned"?u.overtimeSeconds>0?e.jsxs("span",{className:"text-amber-200",children:["+",$i(u.overtimeSeconds)," overtime"]}):e.jsxs("span",{children:[$i(u.remainingSeconds??0)," remaining"]}):e.jsx("span",{children:"Unlimited session"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(Q,{variant:"secondary",pending:n,pendingLabel:"Opening",onClick:r,children:[e.jsx(bn,{className:"size-4"}),"Start work"]}),e.jsxs(Q,{variant:"secondary",pending:n,pendingLabel:"Pausing",onClick:()=>void o(u.run.id),children:[e.jsx(Hu,{className:"size-4"}),"Pause"]}),e.jsxs(Q,{pending:n,pendingLabel:"Completing",onClick:()=>void c(u.run.id),children:[e.jsx(Ia,{className:"size-4"}),"Complete"]})]})]}),f.length>0?e.jsx("div",{className:"mt-4 grid gap-2 lg:grid-cols-2",children:f.map(m=>e.jsxs("button",{type:"button",className:re("flex items-center justify-between gap-3 rounded-2xl bg-white/[0.04] px-4 py-3 text-left transition hover:bg-white/[0.08]",n&&"pointer-events-none opacity-70"),onClick:()=>void l(m.run.id),children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white/88",children:m.title}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-3 text-[12px] text-white/48",children:[e.jsxs("span",{children:[$i(m.creditedSeconds)," credited"]}),e.jsx("span",{children:m.run.timerMode==="planned"?"planned":"unlimited"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-[12px] text-white/42",children:[e.jsx(gi,{className:"size-3.5"}),"Switch"]})]},m.run.id))}):null]})},"timer-rail-detail"):null}):null}function nt({eyebrow:t,title:s,description:i}){const{t:a}=lt();return e.jsxs(ae,{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??a("common.labels.loading")}),e.jsx("div",{className:"type-display-section text-white",children:s??a("common.pageState.loadingTitle")}),e.jsx("p",{className:"type-body mx-auto max-w-xl text-white/60",children:i??a("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(Fl,{tone:"subtle",className:"size-3.5"}),e.jsx("span",{className:"type-meta",children:a("common.labels.syncInProgress")})]})]})}function ze({error:t,onRetry:s,eyebrow:i}){const{t:a}=lt(),{title:n,description:r,code:l}=Cx(t);return e.jsxs(ae,{className:"mx-auto grid max-w-2xl gap-4",children:[e.jsx("div",{className:"type-label text-rose-200/72",children:i??a("common.labels.connectionState")}),e.jsx("div",{className:"type-display-section text-white",children:n}),e.jsx("p",{className:"type-body text-white/62",children:r}),e.jsx("div",{className:"type-meta text-white/40",children:a("common.labels.errorCode",{code:l})}),s?e.jsx("div",{className:"flex flex-wrap gap-3",children:e.jsxs(Q,{type:"button",variant:"secondary",onClick:s,children:[e.jsx(Is,{className:"mr-2 size-4"}),a("common.actions.retry")]})}):null]})}function gt({eyebrow:t,title:s,description:i,action:a}){const{t:n}=lt();return e.jsxs(ae,{className:"mx-auto grid max-w-2xl gap-4 text-center",children:[e.jsx("div",{className:"type-label text-white/38",children:t??n("common.labels.loading")}),e.jsx("div",{className:"type-display-section text-white",children:s}),e.jsx("p",{className:"type-body mx-auto max-w-xl text-white/60",children:i}),a?e.jsx("div",{className:"flex justify-center",children:a}):null]})}function uv(){const t=We();d.useEffect(()=>{const s=new EventSource(ui("/api/v1/events/stream")),i=()=>{Promise.all([t.invalidateQueries({queryKey:["forge-snapshot"]}),t.invalidateQueries({queryKey:["task-context"]})])};return s.addEventListener("snapshot",i),s.addEventListener("activity",i),s.onerror=()=>{s.close()},()=>{s.removeEventListener("snapshot",i),s.removeEventListener("activity",i),s.close()}},[t])}const om=d.createContext(null),Yn=[{id:"overview",to:"/overview",labelKey:"common.routeLabels.overview",detailKey:"common.routeDetails.overview",icon:sh},{id:"goals",to:"/goals",labelKey:"common.routeLabels.goals",detailKey:"common.routeDetails.goals",icon:Fn},{id:"habits",to:"/habits",labelKey:"common.routeLabels.habits",detailKey:"common.routeDetails.habits",icon:gl},{id:"projects",to:"/projects",labelKey:"common.routeLabels.projects",detailKey:"common.routeDetails.projects",icon:ih},{id:"strategies",to:"/strategies",labelKey:"common.routeLabels.strategies",detailKey:"common.routeDetails.strategies",icon:fl},{id:"preferences",to:"/preferences",labelKey:"common.routeLabels.preferences",detailKey:"common.routeDetails.preferences",icon:Aa},{id:"calendar",to:"/calendar",labelKey:"common.routeLabels.calendar",detailKey:"common.routeDetails.calendar",icon:Xt},{id:"connectors",to:"/connectors",label:"Connectors",detail:"Global AI connector graphs and published outputs",icon:lh},{id:"movement",to:"/movement",labelKey:"common.routeLabels.movement",detailKey:"common.routeDetails.movement",icon:oh},{id:"sleep",to:"/sleep",labelKey:"common.routeLabels.sleep",detailKey:"common.routeDetails.sleep",icon:nh},{id:"sports",to:"/sports",labelKey:"common.routeLabels.sports",detailKey:"common.routeDetails.sports",icon:yl},{id:"kanban",to:"/kanban",labelKey:"common.routeLabels.kanban",detailKey:"common.routeDetails.kanban",icon:Ca},{id:"today",to:"/today",labelKey:"common.routeLabels.today",detailKey:"common.routeDetails.today",icon:gi},{id:"notes",to:"/notes",labelKey:"common.routeLabels.notes",detailKey:"common.routeDetails.notes",icon:Ki},{id:"wiki",to:"/wiki",labelKey:"common.routeLabels.wiki",detailKey:"common.routeDetails.wiki",icon:Rn},{id:"psyche",to:"/psyche",labelKey:"common.routeLabels.psyche",detailKey:"common.routeDetails.psyche",icon:bl},{id:"activity",to:"/activity",labelKey:"common.routeLabels.activity",detailKey:"common.routeDetails.activity",icon:Ms},{id:"insights",to:"/insights",labelKey:"common.routeLabels.insights",detailKey:"common.routeDetails.insights",icon:th},{id:"review",to:"/review/weekly",labelKey:"common.routeLabels.review",detailKey:"common.routeDetails.review",icon:Gu},{id:"settings",to:"/settings",labelKey:"common.routeLabels.settings",detailKey:"common.routeDetails.settings",icon:vl}],dm={id:"workbench",to:"/workbench",icon:ch,label:"Workbench",detail:"Custom widgets and utility surface"},pv=fa.filter(t=>t.to!=="/psyche").map(t=>({id:`psyche:${t.to}`,to:t.to,icon:t.icon,label:t.label,detail:"Psyche shortcut"})),Ss=[...Yn,dm,...pv],xv=Yn.filter(t=>t.to!=="/preferences"&&t.to!=="/sleep");function jt(t){const s=Yn.find(i=>i.id===t);if(!s)throw new Error(`Missing primary route: ${t}`);return s}jt("overview"),jt("today"),jt("kanban"),jt("notes");jt("goals"),jt("habits"),jt("projects"),jt("strategies"),jt("calendar"),jt("connectors"),jt("movement"),jt("sports"),jt("wiki"),jt("psyche"),jt("activity"),jt("insights");const cm="forge.selected-user-ids",xd="forge.desktop-nav-layout",gd="forge.mobile-nav-layout";function gv(t,s,i){return Math.min(Math.max(t,s),i)}function ft(t,s,i){return s+(i-s)*t}function fv(t,s){t&&(t.style.setProperty("--forge-shell-collapse",s.toFixed(4)),t.style.setProperty("--forge-shell-desktop-header-padding-top",`${ft(s,18,4)}px`),t.style.setProperty("--forge-shell-desktop-header-padding-bottom",`${ft(s,15,4)}px`),t.style.setProperty("--forge-shell-desktop-title-size",`${ft(s,1.42,.96)}rem`),t.style.setProperty("--forge-shell-desktop-primary-translate-y",`${ft(s,0,2)}px`),t.style.setProperty("--forge-shell-desktop-primary-scale",`${ft(s,1,.98)}`),t.style.setProperty("--forge-shell-desktop-secondary-opacity",`${ft(s,1,0)}`),t.style.setProperty("--forge-shell-desktop-secondary-max-height",`${ft(s,176,0)}px`),t.style.setProperty("--forge-shell-desktop-secondary-spacing",`${ft(s,14,0)}px`),t.style.setProperty("--forge-shell-desktop-secondary-translate-y",`${ft(s,0,-18)}px`),t.style.setProperty("--forge-shell-mobile-header-padding-top",`${ft(s,14,4)}px`),t.style.setProperty("--forge-shell-mobile-header-padding-bottom",`${ft(s,12,4)}px`),t.style.setProperty("--forge-shell-mobile-title-size",`${ft(s,1.2,.9)}rem`),t.style.setProperty("--forge-shell-mobile-primary-translate-y",`${ft(s,0,1)}px`),t.style.setProperty("--forge-shell-mobile-primary-scale",`${ft(s,1,.98)}`),t.style.setProperty("--forge-shell-mobile-copy-opacity",`${ft(s,1,0)}`),t.style.setProperty("--forge-shell-mobile-copy-max-height",`${ft(s,320,0)}px`),t.style.setProperty("--forge-shell-mobile-copy-translate-y",`${ft(s,0,-14)}px`),t.style.setProperty("--forge-shell-hero-padding-top",`${ft(s,20,15)}px`),t.style.setProperty("--forge-shell-hero-padding-bottom",`${ft(s,20,14)}px`),t.style.setProperty("--forge-shell-hero-title-translate-y",`${ft(s,0,-6)}px`),t.style.setProperty("--forge-shell-hero-title-scale",`${ft(s,1,.94)}`),t.style.setProperty("--forge-shell-hero-description-opacity",`${ft(s,1,.45)}`),t.style.setProperty("--forge-shell-hero-description-translate-y",`${ft(s,0,-5)}px`))}function bv(){var t,s,i;return typeof window>"u"?0:Math.max(window.scrollY||0,((t=document.scrollingElement)==null?void 0:t.scrollTop)||0,((s=document.documentElement)==null?void 0:s.scrollTop)||0,((i=document.body)==null?void 0:i.scrollTop)||0)}function hm(t){return new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:t>=1e3?1:0}).format(t)}function vv(t){return t==="/wiki"||t.startsWith("/wiki/page/")?"/wiki":t==="/wiki/new"||t.startsWith("/wiki/edit/")?"/wiki/editor":t}function wv(t){return t==="/wiki"||t.startsWith("/wiki/page/")||t==="/wiki/new"||t.startsWith("/wiki/edit/")}function mn(t){return t.startsWith("/psyche")||t==="/preferences"||t.startsWith("/preferences/")||t==="/sleep"||t.startsWith("/sleep/")}function yv(t){const s=new URLSearchParams;return t.job.spaceId&&s.set("spaceId",t.job.spaceId),s.set("ingest","1"),s.set("ingestJobId",t.job.id),{pathname:"/wiki",search:`?${s.toString()}`}}function jv(t){return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(t))}function Nv(){if(typeof window>"u")return[];try{const t=window.localStorage.getItem(cm);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean):[]}catch{return[]}}function kv(t){if(!(typeof window>"u"))try{window.localStorage.setItem(cm,JSON.stringify(Array.from(new Set(t))))}catch{return}}function mm(t,s){if(t.length!==s.length)return!1;const i=[...t].sort().join("|"),a=[...s].sort().join("|");return i===a}function Cn(t,s){return s.to==="/psyche"?mn(t):t===s.to||t.startsWith(`${s.to}/`)}function pi(t,s){return t.labelKey?s(t.labelKey):t.label??t.to}function Jl(t,s){return t.detailKey?s(t.detailKey):t.detail??t.to}function fd(t,s){if(typeof window>"u")return s;try{const i=window.localStorage.getItem(t);if(!i)return s;const a=JSON.parse(i);if(!Array.isArray(a))return s;const n=new Set(Ss.map(l=>l.id)),r=a.filter(l=>typeof l=="string"&&n.has(l));return r.length>0?r:s}catch{return s}}function bd(t,s){if(!(typeof window>"u"))try{window.localStorage.setItem(t,JSON.stringify(s))}catch{return}}function Sv(t){const s=t.split(/\s+/).map(i=>i.trim()).filter(Boolean);return s.length===0?"??":s.length===1?s[0].slice(0,2).toUpperCase():`${s[0][0]??""}${s[1][0]??""}`.toUpperCase()}function um(t){const s=t.filter(a=>a.kind==="human"),i=t.filter(a=>a.kind==="bot");return[{id:"all",label:"All",shortLabel:"All",description:"Show every human and bot together.",userIds:[],token:"ALL",icon:jl},{id:"humans",label:"Humans",shortLabel:"Humans",description:"Focus only on human-owned work.",userIds:s.map(a=>a.id),token:"HU",icon:Qr},{id:"bots",label:"Bots",shortLabel:"Bots",description:"Focus only on bot-owned work.",userIds:i.map(a=>a.id),token:"AI",icon:Ui},...t.map(a=>({id:a.id,label:a.displayName,shortLabel:a.displayName,description:`${a.kind==="human"?"Human":"Bot"} · ${a.handle}`,userIds:[a.id],token:Sv(a.displayName),icon:a.kind==="human"?Qr:Ui}))]}function Cv(t,s){return um(t).find(i=>mm(s,i.userIds))??{id:"custom",label:s.length>1?`${s.length} selected`:"Custom",shortLabel:s.length>1?`${s.length} selected`:"Custom",description:"Using a custom combination of users.",userIds:s,token:s.length>1?String(s.length):"C",icon:jl}}function vd({users:t,selectedUserIds:s,onChange:i,compact:a=!1}){const[n,r]=d.useState(!1),l=d.useMemo(()=>um(t),[t]),o=d.useMemo(()=>Cv(t,s),[s,t]);return e.jsxs(Et,{open:n,onOpenChange:r,children:[e.jsx(ax,{asChild:!0,children:e.jsxs("button",{type:"button",className:re("shell-scope-trigger inline-flex items-center gap-2",a?"px-2.5 text-[12px]":"px-3.5 text-[13px]"),children:[e.jsx("span",{className:"shell-scope-avatar",children:o.token}),e.jsx("span",{className:re("truncate text-left",a?"max-w-[7.5rem]":"max-w-[11rem]"),children:o.shortLabel})]})}),e.jsxs(Lt,{children:[e.jsx(Dt,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.72)] backdrop-blur-sm"}),e.jsxs($t,{className:"fixed left-1/2 top-[12vh] z-50 w-[min(40rem,calc(100vw-1.5rem))] -translate-x-1/2 rounded-[30px] border border-white/10 bg-[rgba(10,15,28,0.97)] p-4 shadow-[0_32px_90px_rgba(0,0,0,0.45)] sm:p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(Ot,{className:"font-display text-[1.25rem] tracking-[-0.04em] text-white",children:"Choose user scope"}),e.jsx(qt,{className:"mt-1 text-[13px] leading-6 text-white/56",children:"Change which humans and bots shape the current Forge view."})]}),e.jsx(Ft,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-[12px] font-medium text-white/70 transition hover:bg-white/[0.08] hover:text-white",children:"Close"})})]}),e.jsx("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:l.map(c=>{const x=mm(s,c.userIds),v=c.icon;return e.jsxs("button",{type:"button",className:re("flex items-center justify-between gap-3 rounded-[24px] border px-4 py-4 text-left transition",x?"border-[rgba(192,193,255,0.24)] bg-[rgba(192,193,255,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/78 hover:bg-white/[0.06] hover:text-white"),onClick:()=>{i(c.userIds),r(!1)},children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"shell-scope-avatar",children:e.jsx(v,{className:"size-3.5"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate text-[14px] font-semibold",children:c.label}),e.jsx("span",{className:"mt-1 block text-[12px] leading-5 text-white/52",children:c.description})]})]}),x?e.jsx(Vi,{className:"size-4 shrink-0 text-[var(--primary)]"}):null]},c.id)})})]})]})]})}function Iv({route:t,compact:s=!1}){const{t:i}=lt(),a=fi(),n=pi(t,i),r=t.icon,l=Cn(a.pathname,t);return e.jsxs(hi,{to:t.to,title:s?n:void 0,"aria-label":n,className:({isActive:o})=>`interactive-tap flex items-center rounded-[18px] text-sm transition ${o||l?"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"} ${s?"justify-center px-3 py-3.5":"gap-3 px-4 py-3"}`,children:[e.jsx(r,{className:"size-4 shrink-0"}),s?null:e.jsx("span",{children:n})]})}function Tv({routes:t,onOpenEditor:s}){const[i,a]=d.useState(!1),{t:n}=lt(),r=fi(),l=d.useRef(null),o=d.useRef(!1),c=t.slice(0,4),x=Ss.filter(f=>!c.some(h=>h.id===f.id));function v(){o.current=!1,l.current!==null&&window.clearTimeout(l.current),l.current=window.setTimeout(()=>{o.current=!0,a(!1),s==null||s()},520)}function u(){l.current!==null&&(window.clearTimeout(l.current),l.current=null)}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:[c.map(f=>e.jsxs(hi,{to:f.to,onPointerDown:v,onPointerUp:u,onPointerLeave:u,onClick:h=>{o.current&&(h.preventDefault(),o.current=!1)},className:({isActive:h})=>`flex min-h-11 flex-col items-center justify-center gap-1 rounded-2xl px-2 py-2 text-[12px] ${h||Cn(r.pathname,f)?"bg-white/[0.08] text-[var(--primary)]":"text-white/55"}`,children:[e.jsx(f.icon,{className:"size-4"}),e.jsx("span",{children:pi(f,n)})]},f.id)),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:()=>{if(o.current){o.current=!1;return}a(!0)},onPointerDown:v,onPointerUp:u,onPointerLeave:u,children:[e.jsx(vl,{className:"size-4"}),e.jsx("span",{children:n("common.shell.more")})]})]})}),e.jsxs(bs,{open:i,onOpenChange:a,eyebrow:n("common.shell.moreRoutesEyebrow"),title:n("common.shell.moreRoutesTitle"),description:n("common.shell.moreRoutesDescription"),children:[e.jsx("div",{className:"mb-3 flex items-center justify-between gap-3",children:e.jsxs("button",{type:"button",className:"inline-flex min-h-10 items-center gap-2 rounded-full bg-white/[0.05] px-3 py-2 text-sm text-white/72",onClick:()=>{a(!1),s==null||s()},children:[e.jsx(qn,{className:"size-4"}),"Customize navigation"]})}),e.jsx("div",{className:"grid gap-3",children:x.map(f=>e.jsxs(hi,{to:f.to,onClick:()=>a(!1),className:({isActive:h})=>`interactive-tap flex items-center justify-between rounded-[24px] px-4 py-4 ${h||Cn(r.pathname,f)?"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(f.icon,{className:"size-4 text-[var(--primary)]"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-base font-medium",children:pi(f,n)}),e.jsx("span",{className:"mt-1 block text-sm text-white/54",children:Jl(f,n)})]})]}),e.jsx(Ms,{className:"size-4 text-white/35"})]},f.id))})]})]})}function Pv({open:t,onOpenChange:s,desktopNavIds:i,onDesktopNavIdsChange:a,mobileNavIds:n,onMobileNavIdsChange:r}){const{t:l}=lt();i.map(h=>Ss.find(m=>m.id===h)??null).filter(h=>h!==null),n.map(h=>Ss.find(m=>m.id===h)??null).filter(h=>h!==null);const o=Ss.filter(h=>!i.includes(h.id)||!n.includes(h.id)),c=10,x=4;function v(h,m,b,w,M){return Array.from({length:m},(E,D)=>{const j=h[D]??null,S=j?Ss.find(p=>p.id===j)??null:null;return S?e.jsxs("div",{className:"flex min-h-16 items-center justify-between gap-3 rounded-[20px] bg-white/[0.04] px-4 py-3",children:[e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(S.icon,{className:"size-4 text-[var(--primary)]"}),e.jsx("span",{className:"text-sm text-white",children:pi(S,l)})]}),e.jsx("button",{type:"button",className:"rounded-full bg-white/[0.05] px-3 py-1.5 text-[12px] text-white/70",onClick:()=>f(h,S.id,b,w),children:"Remove"})]},`${M}-${S.id}`):e.jsxs("div",{className:"flex min-h-16 items-center justify-between gap-3 rounded-[20px] border border-dashed border-white/12 bg-white/[0.02] px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-white/44",children:"Empty slot"}),e.jsx("div",{className:"text-[12px] text-white/30",children:"Add a route below to fill this slot"})]}),e.jsxs("div",{className:"rounded-full bg-white/[0.05] px-2.5 py-1 text-[11px] text-white/46",children:["Slot ",D+1]})]},`${M}-empty-${D}`)})}function u(h,m,b,w){if(h.includes(m))return;const M=[...h,m];b(w?M.slice(0,w):M)}function f(h,m,b,w=1){const M=h.filter(E=>E!==m);M.length<w||b(M)}return e.jsx(bs,{open:t,onOpenChange:s,eyebrow:"Navigation",title:"Customize navigation",description:"Add or remove main routes, Psyche shortcuts, and the custom workbench surface.",children:e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Desktop sidebar"}),e.jsx("div",{className:"grid gap-2",children:v(i,c,a,4,"desktop")})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Mobile bar"}),e.jsx("div",{className:"grid gap-2",children:v(n,x,r,2,"mobile")})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Available routes"}),e.jsx("div",{className:"grid gap-2",children:o.map(h=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[20px] bg-white/[0.03] px-4 py-3",children:[e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(h.icon,{className:"size-4 text-[var(--primary)]"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm text-white",children:pi(h,l)}),e.jsx("span",{className:"block text-[12px] text-white/48",children:Jl(h,l)})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[i.includes(h.id)?null:e.jsx("button",{type:"button",className:"rounded-full bg-white/[0.05] px-3 py-1.5 text-[12px] text-white/70",onClick:()=>u(i,h.id,a),children:"Add to sidebar"}),n.includes(h.id)?null:e.jsx("button",{type:"button",className:"rounded-full bg-white/[0.05] px-3 py-1.5 text-[12px] text-white/70",onClick:()=>u(n,h.id,r,4),children:"Add to mobile"})]})]},`available-${h.id}`))})]})]})})}function Mv({onClick:t}){const{t:s}=lt();return e.jsxs(Q,{variant:"secondary",size:"sm",className:"min-w-[8.25rem] px-3.5",onClick:t,children:[e.jsx(bt,{className:"size-4"}),s("common.shell.command"),e.jsx(L,{size:"sm",tone:"meta",className:"ml-1 hidden bg-white/[0.06] text-white/52 xl:inline-flex",children:"Shift Shift"}),e.jsx(L,{size:"sm",tone:"meta",className:"hidden bg-white/[0.06] text-white/52 2xl:inline-flex",children:"Cmd K"})]})}function Av({children:t,routeLocation:s,settings:i,timerPending:a,startWorkOpen:n,startWorkPending:r,startWorkError:l,startWorkDefaults:o,onOpenStartWork:c,onCloseStartWork:x,onStartExistingTask:v,onCreateAndStartTask:u,onFocusRun:f,onPauseRun:h,onCompleteRun:m}){var Y,R;const b=Je(),{t:w}=lt(),M=Ss.find(X=>Cn(s.pathname,X))??Yn[0],E=vv(s.pathname),[D,j]=d.useState(!1),[S,p]=d.useState(!1),A=d.useRef(null),T=d.useRef(0),[k,$]=d.useState(!1),[g,C]=d.useState(()=>fd(xd,[...xv.map(X=>X.id),dm.id])),[F,z]=d.useState(()=>fd(gd,[jt("overview").id,jt("today").id,jt("kanban").id,jt("notes").id])),[J,O]=d.useState(!1),_=d.useRef(!1),B=d.useRef(!1),K=d.useRef(!1),Z=mn(s.pathname),U=wv(s.pathname),I=mn(s.pathname),G=U||I,W=g.map(X=>Ss.find(be=>be.id===X)??null).filter(X=>X!==null),ne=F.map(X=>Ss.find(be=>be.id===X)??null).filter(X=>X!==null),de=dh(),we=Ju(),Ne=de+we,H=fe({queryKey:["forge-background-wiki-ingest-jobs"],queryFn:()=>_h({limit:12}),refetchInterval:X=>{var Ie;const be=((Ie=X.state.data)==null?void 0:Ie.jobs)??[];return S||be.some(te=>["queued","processing"].includes(te.job.status))?2e3:!1}}),me=[{id:"streak",label:w("common.shell.momentum.streak"),compactValue:String(b.snapshot.metrics.streakDays),expandedValue:w(b.snapshot.metrics.streakDays===1?"common.shell.momentum.streakBadgeOne":"common.shell.momentum.streakBadgeOther",{count:b.snapshot.metrics.streakDays}),icon:Yu},{id:"xp",label:w("common.shell.momentum.xp"),compactValue:String(b.snapshot.metrics.totalXp),expandedValue:`${b.snapshot.metrics.totalXp} XP`,icon:Ca},{id:"momentum",label:w("common.shell.momentum.momentum"),compactValue:`${b.snapshot.metrics.momentumScore}%`,expandedValue:w("common.shell.momentum.liveMomentum",{count:b.snapshot.metrics.momentumScore}),icon:Zu}],y=(((Y=H.data)==null?void 0:Y.jobs)??[]).some(X=>["queued","processing"].includes(X.job.status))?(()=>{var be,Ie,te;const X=(((be=H.data)==null?void 0:be.jobs)??[]).filter(ce=>["queued","processing"].includes(ce.job.status));return X.length===1?((Ie=X[0])==null?void 0:Ie.job.latestMessage)||((te=X[0])==null?void 0:te.job.titleHint)||"1 ingest running":`${X.length} ingest jobs running`})():we>0?w(we===1?"common.shell.savingOne":"common.shell.savingOther",{count:we}):de>0?w(de===1?"common.shell.refreshingOne":"common.shell.refreshingOther",{count:de}):w("common.shell.settled"),P=((R=H.data)==null?void 0:R.jobs)??[],q=P.some(X=>["queued","processing"].includes(X.job.status)),pe=d.useMemo(()=>s.pathname.startsWith("/tasks/")?[{to:"/kanban",label:w("common.shell.rail.taskBackToKanban")},{to:"/today",label:w("common.shell.rail.taskOpenToday")}]:s.pathname.startsWith("/projects/")?[{to:"/projects",label:w("common.shell.rail.projectAll")},{to:"/goals",label:w("common.shell.rail.projectGoals")}]:s.pathname.startsWith("/goals/")?[{to:"/goals",label:w("common.shell.rail.goalAll")},{to:"/projects",label:w("common.shell.rail.goalProjects")}]:s.pathname.startsWith("/strategies")?[{to:"/strategies",label:w("common.routeLabels.strategies")},{to:"/projects",label:w("common.shell.rail.projectAll")}]:mn(s.pathname)?[{to:"/psyche",label:w("common.shell.rail.psycheHub")},{to:"/psyche/reports",label:w("common.shell.rail.psycheReports")}]:[{to:"/overview",label:w("common.shell.rail.overview")},{to:"/today",label:w("common.shell.rail.today")}],[s.pathname,w]);d.useEffect(()=>{let X=0;const be=Ie=>{if((Ie.metaKey||Ie.ctrlKey)&&Ie.key.toLowerCase()==="k"){Ie.preventDefault(),j(te=>!te),X=0;return}if(Ie.key==="Shift"&&!Ie.metaKey&&!Ie.ctrlKey&&!Ie.altKey&&!Ie.repeat){const te=window.performance.now();if(te-X<=360){Ie.preventDefault(),j(!0),X=0;return}X=te;return}!Ie.metaKey&&!Ie.ctrlKey&&!Ie.altKey&&(X=0)};return window.addEventListener("keydown",be),()=>window.removeEventListener("keydown",be)},[]),d.useEffect(()=>{try{window.localStorage.getItem("forge.desktop-nav-collapsed")==="true"&&$(!0)}catch{return}},[]),d.useEffect(()=>{if(K.current){K.current=!1;return}try{window.localStorage.setItem("forge.desktop-nav-collapsed",String(k))}catch{return}},[k]),d.useEffect(()=>{bd(xd,g)},[g]),d.useEffect(()=>{bd(gd,F)},[F]),d.useEffect(()=>{if(G){_.current||(B.current=k,_.current=!0,k||(K.current=!0,$(!0)));return}_.current&&(_.current=!1,k!==B.current&&(K.current=!0,$(B.current)))},[G,k]),d.useEffect(()=>{const X=()=>{const be=window.innerWidth>=1024?124:96,Ie=document.scrollingElement??document.documentElement??document.body,ce=Math.max(0,Ie.scrollHeight-window.innerHeight)<be?0:gv(bv()/be,0,1);Math.abs(T.current-ce)<.001||(T.current=ce,fv(A.current,ce))};return X(),window.addEventListener("scroll",X,{passive:!0}),window.addEventListener("resize",X),()=>{window.removeEventListener("scroll",X),window.removeEventListener("resize",X)}},[]);const ee=d.useMemo(()=>({"--forge-shell-collapse":"0","--forge-shell-desktop-header-padding-top":"18px","--forge-shell-desktop-header-padding-bottom":"15px","--forge-shell-desktop-title-size":"1.42rem","--forge-shell-desktop-primary-translate-y":"0px","--forge-shell-desktop-primary-scale":"1","--forge-shell-desktop-secondary-opacity":"1","--forge-shell-desktop-secondary-max-height":"176px","--forge-shell-desktop-secondary-spacing":"14px","--forge-shell-desktop-secondary-translate-y":"0px","--forge-shell-mobile-header-padding-top":"14px","--forge-shell-mobile-header-padding-bottom":"12px","--forge-shell-mobile-title-size":"1.2rem","--forge-shell-mobile-primary-translate-y":"0px","--forge-shell-mobile-primary-scale":"1","--forge-shell-mobile-copy-opacity":"1","--forge-shell-mobile-copy-max-height":"320px","--forge-shell-mobile-copy-translate-y":"0px","--forge-shell-hero-padding-top":"20px","--forge-shell-hero-padding-bottom":"20px","--forge-shell-hero-title-translate-y":"0px","--forge-shell-hero-title-scale":"1","--forge-shell-hero-description-opacity":"1","--forge-shell-hero-description-translate-y":"0px"}),[]);return e.jsxs("div",{ref:A,className:`min-h-screen ${b.snapshot.meta.mode==="transitional-node"?"theme-forge-obsidian":""}`,style:ee,children:[e.jsx(qb,{open:D,onOpenChange:j,snapshot:b.snapshot,selectedUserIds:b.selectedUserIds}),e.jsxs("div",{className:"hidden lg:grid lg:min-h-screen",style:{gridTemplateColumns:k?"5.75rem minmax(0,1fr)":"17.75rem minmax(0,1fr)"},children:[e.jsxs("aside",{className:re("flex min-h-screen flex-col border-r border-white/5 bg-[rgba(8,13,28,0.78)] py-6 backdrop-blur-xl transition-[padding,width]",k?"px-3":"px-5"),children:[e.jsxs("div",{className:re("flex items-start",k?"flex-col items-center gap-3":"justify-between gap-3"),children:[e.jsxs(Ae,{to:"/overview",className:re("block min-w-0",k&&"text-center"),children:[e.jsx("div",{className:re("font-display text-[var(--primary)]",k?"text-2xl":"text-3xl"),children:w("common.shell.appMark")}),k?null:e.jsxs("div",{className:"type-meta mt-2 text-white/40",children:["Level ",b.snapshot.metrics.level]})]}),e.jsx(Q,{type:"button",variant:"secondary",size:"sm",className:"mt-0.5 px-2.5",onClick:()=>$(X=>!X),"aria-label":w(k?"common.shell.expandSidebar":"common.shell.collapseSidebar"),title:w(k?"common.shell.expandSidebar":"common.shell.collapseSidebar"),children:k?e.jsx(ep,{className:"size-4"}):e.jsx(tp,{className:"size-4"})})]}),e.jsxs(Q,{type:"button",variant:"secondary",size:"sm",className:re("mt-3",k?"px-2.5":"w-full justify-start px-3"),onClick:()=>O(!0),children:[e.jsx(qn,{className:"size-4"}),k?null:"Customize nav"]}),e.jsx("div",{className:re("grid gap-2",k?"mt-6":"mt-8"),children:W.map(X=>e.jsx(Iv,{route:X,compact:k},X.id))}),e.jsx("div",{className:re(k?"mt-4":"mt-6"),children:e.jsxs("div",{className:re("rounded-[24px] bg-white/[0.04]",k?"px-2 py-2.5":"p-4"),children:[k?null:e.jsx("div",{className:"type-label text-white/40",children:w("common.shell.momentum.title")}),e.jsx("div",{className:re("grid",k?"gap-1.5":"mt-3 gap-3"),children:me.map(X=>{const be=X.icon;return k?e.jsxs("div",{title:`${X.label}: ${X.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(be,{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:X.compactValue})]},X.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:X.label}),e.jsx("div",{className:"mt-1 text-lg font-semibold leading-tight text-white",children:X.expandedValue})]},X.id)})})]})})]}),e.jsxs("div",{className:"min-h-screen",children:[e.jsx(md,{children:e.jsxs("header",{className:"sticky top-0 z-30 border-b border-white/5 bg-[rgba(10,16,30,0.82)] px-6 backdrop-blur-xl",style:{paddingTop:"var(--forge-shell-desktop-header-padding-top)",paddingBottom:"var(--forge-shell-desktop-header-padding-bottom)",willChange:"padding, background-color"},children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",style:{transform:"translateY(var(--forge-shell-desktop-primary-translate-y)) scale(var(--forge-shell-desktop-primary-scale))",transformOrigin:"top center",willChange:"transform"},children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-5",children:[e.jsx("div",{className:"shrink-0 font-display text-white",style:{fontSize:"var(--forge-shell-desktop-title-size)",lineHeight:1,willChange:"font-size"},children:pi(M,w)}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(ud,{runs:b.snapshot.activeTaskRuns,tasks:b.snapshot.tasks,generatedAt:b.snapshot.meta.generatedAt,timeAccountingMode:i.execution.timeAccountingMode,pending:a,onOpenStartWork:()=>c(),onPause:h,onFocus:f})})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-2",children:[e.jsx(Vo,{active:Ne>0||q,label:y,onClick:()=>p(!0)}),e.jsx(Mv,{onClick:()=>j(!0)}),e.jsxs(Q,{variant:"secondary",size:"sm",className:"min-w-[7.25rem] px-3.5",onClick:()=>void b.refresh(),children:[e.jsx(Is,{className:"size-4"}),w("common.actions.refresh")]})]})]}),e.jsx(pd,{runs:b.snapshot.activeTaskRuns,tasks:b.snapshot.tasks,generatedAt:b.snapshot.meta.generatedAt,timeAccountingMode:i.execution.timeAccountingMode,pending:a,onOpenStartWork:()=>c(),onFocus:f,onPause:h,onComplete:m}),e.jsxs("div",{className:"flex items-center justify-between gap-4 overflow-hidden border-t border-white/6",style:{opacity:"var(--forge-shell-desktop-secondary-opacity)",maxHeight:"var(--forge-shell-desktop-secondary-max-height)",marginTop:"var(--forge-shell-desktop-secondary-spacing)",paddingTop:"var(--forge-shell-desktop-secondary-spacing)",transform:"translateY(var(--forge-shell-desktop-secondary-translate-y))",willChange:"opacity, max-height, transform"},children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[pe.map(X=>e.jsx(Ae,{to:X.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:X.label},X.to)),e.jsx(vd,{users:b.snapshot.users,selectedUserIds:b.selectedUserIds,onChange:b.setSelectedUserIds,compact:!0})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(L,{tone:"meta",children:w(b.snapshot.metrics.streakDays===1?"common.shell.momentum.streakBadgeOne":"common.shell.momentum.streakBadgeOther",{count:b.snapshot.metrics.streakDays})}),e.jsx(L,{tone:"meta",children:w("common.shell.momentum.weeklyXp",{count:b.snapshot.metrics.weeklyXp})}),e.jsx(L,{tone:Z?"signal":"meta",children:Z?w("common.shell.momentum.psycheMode"):w("common.shell.momentum.liveMomentum",{count:b.snapshot.metrics.momentumScore})})]})]})]})}),e.jsx("div",{className:"px-6 pt-3",children:e.jsx(hd,{open:n,onOpenChange:X=>{X||x()},presentation:"desktop_inline",tasks:b.snapshot.tasks,projects:b.snapshot.dashboard.projects,activeRunCount:b.snapshot.activeTaskRuns.length,maxActiveTasks:i.execution.maxActiveTasks,timeAccountingMode:i.execution.timeAccountingMode,pending:r,errorMessage:l,initialTaskId:o.taskId??null,defaultProjectId:o.projectId??null,onStartExisting:v,onCreateAndStart:u})}),e.jsx("main",{className:"px-6 pb-3",children:e.jsx(rd,{routeKey:E,tone:Z?"psyche":"core",children:t})})]})]}),e.jsxs("div",{className:"min-h-[100dvh] overflow-x-clip lg:hidden",children:[e.jsx(md,{children:e.jsxs("header",{className:"sticky top-0 z-30 border-b border-white/6 bg-[rgba(8,13,28,0.92)] px-4 backdrop-blur-xl",style:{paddingTop:"var(--forge-shell-mobile-header-padding-top)",paddingBottom:"var(--forge-shell-mobile-header-padding-bottom)",willChange:"padding, background-color"},children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",style:{transform:"translateY(var(--forge-shell-mobile-primary-translate-y)) scale(var(--forge-shell-mobile-primary-scale))",transformOrigin:"top center",willChange:"transform"},children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[e.jsx("div",{className:"min-w-0 truncate font-display text-white",style:{fontSize:"var(--forge-shell-mobile-title-size)",willChange:"font-size"},children:pi(M,w)}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(ud,{runs:b.snapshot.activeTaskRuns,tasks:b.snapshot.tasks,generatedAt:b.snapshot.meta.generatedAt,timeAccountingMode:i.execution.timeAccountingMode,pending:a,onOpenStartWork:()=>c(),onPause:h,onFocus:f})})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsx(Q,{variant:"secondary",size:"sm",className:"min-h-[2.125rem] px-2.5",onClick:()=>j(!0),children:e.jsx(bt,{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(Ca,{className:"size-3.5 shrink-0"}),e.jsxs("span",{className:"max-w-[5.5rem] truncate",children:[hm(b.snapshot.metrics.totalXp)," XP"]})]})]})]}),e.jsx(pd,{runs:b.snapshot.activeTaskRuns,tasks:b.snapshot.tasks,generatedAt:b.snapshot.meta.generatedAt,timeAccountingMode:i.execution.timeAccountingMode,pending:a,onOpenStartWork:()=>c(),onFocus:f,onPause:h,onComplete:m}),e.jsxs("div",{className:"overflow-hidden",style:{opacity:"var(--forge-shell-mobile-copy-opacity)",maxHeight:"var(--forge-shell-mobile-copy-max-height)",transform:"translateY(var(--forge-shell-mobile-copy-translate-y))",willChange:"opacity, max-height, transform"},children:[e.jsx("div",{className:"mt-2 text-[13px] leading-5 text-white/52",children:Jl(M,w)}),e.jsx("div",{className:"mt-2",children:e.jsx(Vo,{active:Ne>0||q,label:y,onClick:()=>p(!0)})}),e.jsx("div",{className:"mt-3 overflow-x-auto pb-1",children:e.jsx(vd,{users:b.snapshot.users,selectedUserIds:b.selectedUserIds,onChange:b.setSelectedUserIds,compact:!0})})]})]})}),e.jsx(hd,{open:n,onOpenChange:X=>{X||x()},presentation:"mobile_sheet",tasks:b.snapshot.tasks,projects:b.snapshot.dashboard.projects,activeRunCount:b.snapshot.activeTaskRuns.length,maxActiveTasks:i.execution.maxActiveTasks,timeAccountingMode:i.execution.timeAccountingMode,pending:r,errorMessage:l,initialTaskId:o.taskId??null,defaultProjectId:o.projectId??null,onStartExisting:v,onCreateAndStart:u}),e.jsx("main",{className:"overflow-x-clip px-4 pb-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(rd,{routeKey:E,tone:Z?"psyche":"core",children:t})}),e.jsx(Tv,{routes:ne,onOpenEditor:()=>O(!0)}),e.jsx(Pv,{open:J,onOpenChange:O,desktopNavIds:g,onDesktopNavIdsChange:C,mobileNavIds:F,onMobileNavIdsChange:z})]}),e.jsx(Et,{open:S,onOpenChange:p,children:e.jsxs(Lt,{children:[e.jsx(Dt,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.72)] backdrop-blur-sm"}),e.jsxs($t,{className:"fixed left-1/2 top-[10vh] z-50 w-[min(42rem,calc(100vw-1.5rem))] -translate-x-1/2 rounded-[30px] border border-white/10 bg-[rgba(10,15,28,0.97)] p-4 shadow-[0_32px_90px_rgba(0,0,0,0.45)] sm:p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(Ot,{className:"font-display text-[1.25rem] tracking-[-0.04em] text-white",children:"Background activity"}),e.jsx(qt,{className:"mt-1 text-[13px] leading-6 text-white/56",children:"Follow active wiki ingest jobs and reopen completed reviews without leaving your current context."})]}),e.jsx(Ft,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-[12px] font-medium text-white/70 transition hover:bg-white/[0.08] hover:text-white",children:"Close"})})]}),e.jsx("div",{className:"mt-4 max-h-[65vh] overflow-y-auto",children:H.isLoading?e.jsx(nt,{eyebrow:"Background",title:"Loading activity",description:"Checking the latest queued and completed ingest jobs."}):H.isError?e.jsx(ze,{eyebrow:"Background",error:H.error,onRetry:()=>void H.refetch()}):P.length===0?e.jsx("div",{className:"rounded-[24px] border border-dashed border-white/10 px-4 py-10 text-center text-[13px] leading-6 text-white/42",children:"No background ingest jobs yet."}):e.jsx("div",{className:"grid gap-3",children:P.map(X=>{const be=["queued","processing"].includes(X.job.status);return e.jsx(Ae,{to:yv(X),onClick:()=>p(!1),className:"rounded-[24px] border border-white/8 bg-white/[0.03] px-4 py-4 transition hover:bg-white/[0.06]",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Wiki ingest"}),e.jsx("div",{className:"mt-2 text-[14px] font-semibold text-white",children:X.job.titleHint||X.job.latestMessage||"Background ingest"}),e.jsxs("div",{className:"mt-1 text-[12px] leading-5 text-white/56",children:[X.job.status," · ",X.job.phase," ·"," ",X.job.progressPercent,"% ·"," ",jv(X.job.updatedAt)]}),e.jsxs("div",{className:"mt-2 text-[12px] leading-5 text-white/46",children:[X.job.createdPageCount," pages ·"," ",X.job.createdEntityCount," entities ·"," ",X.job.acceptedCount," accepted ·"," ",X.job.rejectedCount," rejected"]})]}),e.jsx("div",{className:"shrink-0",children:be?e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-xs text-white/58",children:[e.jsx(Is,{className:"size-3.5 animate-spin"}),"Running"]}):e.jsx(L,{tone:"meta",children:X.job.phase})})]})},X.job.id)})})})]})]})}),e.jsx(dv,{className:"fixed z-40 lg:bottom-6 lg:right-6",goals:b.snapshot.dashboard.goals,projects:b.snapshot.dashboard.projects,tags:b.snapshot.tags,users:b.snapshot.users,defaultUserId:b.selectedUserIds.length===1?b.selectedUserIds[0]:null,onCreateGoal:b.createGoal,onCreateProject:b.createProject,onCreateTask:b.createTask})]})}function Ev(){var we,Ne;uv();const t=d.useRef(`forge_session_${Math.random().toString(36).slice(2,10)}`),s=d.useRef(null),i=d.useRef(null),a=We(),n=fi(),r=d.useContext(Ro),l=Xu(),o=dh(),[c,x]=d.useState(Nv),[v,u]=d.useState(!1),[f,h]=d.useState({}),[m,b]=d.useState(null),[w,M]=d.useState(null),E=`${n.pathname}${n.search}${n.hash}`,D=d.useRef(o),j=d.useRef(null),[S,p]=d.useState({key:E,node:l,location:n}),[A,T]=d.useState(null),k=fe({queryKey:["forge-shell-operator-session"],queryFn:Zi,retry:!1,staleTime:5*6e4}),$=fe({queryKey:["forge-snapshot",...c],queryFn:()=>zx(c),enabled:k.isSuccess}),g=fe({queryKey:["forge-settings"],queryFn:vi,enabled:k.isSuccess});d.useEffect(()=>{kv(c)},[c]),d.useEffect(()=>{k.isSuccess&&a.invalidateQueries({predicate:H=>{const[me]=H.queryKey;return me==="notes-index"||me==="project-board"||me==="task-context"||typeof me=="string"&&me.startsWith("forge-")}})},[k.isSuccess,a,c]),d.useEffect(()=>{var y;const H=(y=$.data)==null?void 0:y.metrics.totalXp;if(typeof H!="number")return;if(i.current===null){i.current=H;return}const me=H-i.current;i.current=H,me!==0&&(M({deltaXp:me,totalXp:H}),s.current!==null&&window.clearTimeout(s.current),s.current=window.setTimeout(()=>{M(null),s.current=null},2600))},[(we=$.data)==null?void 0:we.metrics.totalXp]),d.useEffect(()=>()=>{s.current!==null&&window.clearTimeout(s.current)},[]),d.useEffect(()=>{var q;const H=(q=g.data)==null?void 0:q.settings;if(!H)return;const me=()=>{tl(H.themePreference,H.customTheme??null)};if(me(),H.themePreference!=="system"||typeof window>"u"||typeof window.matchMedia!="function")return;const y=window.matchMedia("(prefers-color-scheme: dark)"),P=()=>me();return typeof y.addEventListener=="function"?(y.addEventListener("change",P),()=>y.removeEventListener("change",P)):(y.addListener(P),()=>y.removeListener(P))},[(Ne=g.data)==null?void 0:Ne.settings]),d.useEffect(()=>{if(!k.isSuccess)return;let H=!1,me=!1,y=!1;const P=()=>{H=!0},q=(Y,R)=>Pb({sessionId:t.current,eventType:Y,metrics:R}).catch(()=>{});q("session_started",{visible:document.visibilityState==="visible",interacted:!1});const pe=window.setTimeout(()=>{document.visibilityState==="visible"&&H&&!me&&(me=!0,q("dwell_120_seconds",{visible:!0,interacted:!0}))},12e4),ee=()=>{const Y=Math.max(1,document.documentElement.scrollHeight-window.innerHeight),R=Math.round(window.scrollY/Y*100);R>=75&&H&&!y&&(y=!0,q("scroll_depth_75",{visible:document.visibilityState==="visible",interacted:!0,scrollDepth:R}))};return window.addEventListener("pointerdown",P),window.addEventListener("keydown",P),window.addEventListener("scroll",ee,{passive:!0}),()=>{window.clearTimeout(pe),window.removeEventListener("pointerdown",P),window.removeEventListener("keydown",P),window.removeEventListener("scroll",ee)}},[k.isSuccess]);const C=xe({mutationFn:H=>Sn(H),onSuccess:async()=>{await a.invalidateQueries({queryKey:["forge-snapshot"]})}}),F=xe({mutationFn:H=>Qh(H),onSuccess:async()=>{await a.invalidateQueries({queryKey:["forge-snapshot"]})}}),z=xe({mutationFn:H=>Wh(H),onSuccess:async()=>{await a.invalidateQueries({queryKey:["forge-snapshot"]})}}),J=xe({mutationFn:({goalId:H,patch:me})=>Sb(H,me),onSuccess:async()=>{await a.invalidateQueries({queryKey:["forge-snapshot"]})}}),O=xe({mutationFn:({projectId:H,patch:me})=>Hh(H,me),onSuccess:async()=>{await a.invalidateQueries({queryKey:["forge-snapshot"]})}}),_=xe({mutationFn:({taskId:H,status:me})=>Oa(H,{status:me}),onSuccess:async()=>{await a.invalidateQueries({queryKey:["forge-snapshot"]})}}),B=xe({mutationFn:({taskId:H,input:me})=>Mb(H,me),onSuccess:async()=>{await a.invalidateQueries({queryKey:["forge-snapshot"]})}}),K=xe({mutationFn:H=>Eb(H),onSuccess:async()=>{await a.invalidateQueries({queryKey:["forge-snapshot"]})}}),Z=xe({mutationFn:({runId:H,actor:me,note:y})=>Jh(H,{actor:me,note:y??""}),onSuccess:async()=>{await a.invalidateQueries({queryKey:["forge-snapshot"]})}}),U=xe({mutationFn:({runId:H,actor:me,note:y})=>Vh(H,{actor:me,note:y??""}),onSuccess:async()=>{await a.invalidateQueries({queryKey:["forge-snapshot"]})}}),I=xe({mutationFn:async H=>{var pe,ee;const me=(pe=$.data)==null?void 0:pe.dashboard.projects.find(Y=>Y.id===H.projectId);if(!me)throw new Error("Select a project before starting work.");const y=((ee=g.data)==null?void 0:ee.settings.profile.operatorName)??"Albert",P=await Sn({title:H.title,description:H.description,owner:y,userId:me.userId??(c.length===1?c[0]:null),goalId:me.goalId,projectId:me.id,priority:"medium",status:"in_progress",effort:"deep",energy:"steady",dueDate:"",points:60,tagIds:[],notes:[]});if(!await G(P.task.id,{actor:y,timerMode:H.timerMode,plannedDurationSeconds:H.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 P.task},onSuccess:async()=>{await a.invalidateQueries({queryKey:["forge-snapshot"]})}}),G=async(H,me)=>{try{return await B.mutateAsync({taskId:H,input:me}),!0}catch(y){if(y instanceof Ea&&y.code==="task_run_calendar_blocked"&&typeof window<"u"){const P=window.prompt("Calendar rules block this task right now. Add a reason to override and start anyway.");return!P||P.trim().length===0?!1:(await B.mutateAsync({taskId:H,input:{...me,overrideReason:P.trim()}}),!0)}throw y}};if(d.useEffect(()=>{const H=$.data;if(!H||H.activeTaskRuns.length===0)return;const me=window.setInterval(()=>{if(document.visibilityState==="visible"){for(const y of H.activeTaskRuns)Ab(y.id,{actor:y.actor,leaseTtlSeconds:y.leaseTtlSeconds,note:y.note}).catch(()=>{});a.invalidateQueries({queryKey:["forge-snapshot"]})}},3e4);return()=>window.clearInterval(me)},[a,$.data]),d.useEffect(()=>{D.current=o},[o]),d.useEffect(()=>{if(E===S.key&&A===null){p(H=>H.node===l&&H.location===n?H:{...H,node:l,location:n});return}E!==S.key&&T(H=>(H==null?void 0:H.key)===E&&H.node===l?H:{key:E,node:l,location:n,baselineFetching:D.current})},[S.key,l,A,E,n]),d.useEffect(()=>{if(!A){j.current!==null&&(window.clearTimeout(j.current),j.current=null);return}if(o>A.baselineFetching){j.current!==null&&(window.clearTimeout(j.current),j.current=null);return}if(j.current===null)return j.current=window.setTimeout(()=>{p({key:A.key,node:A.node,location:A.location}),T(null),j.current=null},140),()=>{j.current!==null&&(window.clearTimeout(j.current),j.current=null)}},[o,A]),d.useEffect(()=>()=>{j.current!==null&&window.clearTimeout(j.current)},[]),k.isLoading||$.isLoading||g.isLoading)return e.jsx("div",{className:"grid min-h-screen place-items-center p-6",children:e.jsx(nt,{eyebrow:"Forge shell",title:"Loading Forge",description:"Checking your operator session and loading your latest snapshot."})});if(k.isError)return e.jsx("div",{className:"grid min-h-screen place-items-center p-6",children:e.jsx(ze,{eyebrow:"Forge operator session",error:k.error,onRetry:()=>void a.invalidateQueries({queryKey:["forge-shell-operator-session"]})})});if(g.isError)return e.jsx("div",{className:"grid min-h-screen place-items-center p-6",children:e.jsx(ze,{eyebrow:"Forge settings",error:g.error,onRetry:()=>void a.invalidateQueries({queryKey:["forge-settings"]})})});if($.isError||!$.data||!g.data)return e.jsx("div",{className:"grid min-h-screen place-items-center p-6",children:e.jsx(ze,{eyebrow:"Forge state",error:$.error,onRetry:()=>void a.invalidateQueries({queryKey:["forge-snapshot"]})})});const W={snapshot:$.data,selectedUserIds:c,setSelectedUserIds:x,refresh:async()=>{await a.invalidateQueries({queryKey:["forge-snapshot"]})},createTask:async H=>{await C.mutateAsync(H)},startTaskNow:async(H,me={})=>{const y=g.data.settings.profile.operatorName;await G(H,{actor:y,timerMode:me.timerMode??"planned",plannedDurationSeconds:me.plannedDurationSeconds===void 0?1200:me.plannedDurationSeconds,isCurrent:!0,leaseTtlSeconds:1800,note:""})},createGoal:async H=>{await F.mutateAsync(H)},createProject:async H=>{await z.mutateAsync(H)},patchGoal:async(H,me)=>{await J.mutateAsync({goalId:H,patch:me})},patchProject:async(H,me)=>{await O.mutateAsync({projectId:H,patch:me})},patchTaskStatus:async(H,me)=>{await _.mutateAsync({taskId:H,status:me})},openStartWork:(H={})=>{h(H),b(null),u(!0)}},ne=A?S.location:n,de=r?{...r,location:S.location}:null;return e.jsx(yx,{locale:g.data.settings.localePreference,children:e.jsx(om.Provider,{value:W,children:e.jsxs(e.Fragment,{children:[e.jsx(Av,{routeLocation:ne,settings:g.data.settings,timerPending:K.isPending||Z.isPending||U.isPending,startWorkOpen:v,startWorkPending:B.isPending||I.isPending,startWorkError:m,startWorkDefaults:f,onOpenStartWork:H=>{h(H??{}),b(null),u(!0)},onCloseStartWork:()=>{u(!1),b(null)},onStartExistingTask:async(H,me)=>{try{const y=g.data.settings.profile.operatorName;await G(H,{actor:y,timerMode:me.timerMode,plannedDurationSeconds:me.plannedDurationSeconds,isCurrent:!0,leaseTtlSeconds:1800,note:""})&&(u(!1),b(null))}catch(y){b(y instanceof Error?y.message:"Could not start work.")}},onCreateAndStartTask:async H=>{try{await I.mutateAsync(H),u(!1),b(null)}catch(me){b(me instanceof Error?me.message:"Could not create and start the task.")}},onFocusRun:async H=>{await K.mutateAsync(H)},onPauseRun:async H=>{const me=$.data.activeTaskRuns.find(y=>y.id===H);await Z.mutateAsync({runId:H,actor:me==null?void 0:me.actor,note:me==null?void 0:me.note})},onCompleteRun:async H=>{const me=$.data.activeTaskRuns.find(y=>y.id===H);await U.mutateAsync({runId:H,actor:me==null?void 0:me.actor,note:me==null?void 0:me.note})},children:e.jsxs("div",{className:"relative min-w-0",children:[de?e.jsx(Ro.Provider,{value:de,children:S.node}):S.node,A?e.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 overflow-hidden opacity-0",children:A.node}):null]})}),w?e.jsx("div",{className:"pointer-events-none fixed inset-x-0 bottom-24 z-50 flex justify-center px-4 lg:bottom-6",children:e.jsxs("div",{className:re("inline-flex items-center gap-2 rounded-full border px-4 py-2 text-sm font-medium shadow-[0_18px_48px_rgba(3,8,18,0.38)] backdrop-blur-xl",w.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(Ca,{className:"size-4 shrink-0"}),e.jsxs("span",{children:[w.deltaXp>0?`XP +${w.deltaXp}`:`XP ${w.deltaXp}`," ","· ",hm(w.totalXp)," total"]})]})}):null]})})})}function Je(){return d.useContext(om)??Vu()}function fr(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g," ")}function Lv({eyebrow:t,titleText:s,entityKind:i,copyMode:a}){if(!t||a==="title_only"||typeof t!="string")return null;const n=fr(t),r=s?fr(s):null,l=i?fr(Ts(i).label):null;return!n||r&&(n===r||r.includes(n)||n.includes(r))||l&&n===l?null:t}function qe({eyebrow:t,entityKind:s,title:i,titleText:a,description:n,badge:r,actions:l,copyMode:o="title_only"}){const c=s?Ts(s):null,x=c==null?void 0:c.icon,v=Lv({eyebrow:t,titleText:a,entityKind:s,copyMode:o}),u=!!(c||v||r);return e.jsxs("header",{className:"relative min-w-0 w-full max-w-full overflow-hidden border-b border-white/6 bg-[linear-gradient(135deg,rgba(24,34,60,0.68)_0%,rgba(15,24,44,0.42)_58%,rgba(10,16,31,0.18)_100%)] px-5 py-5 sm:px-6 lg:grid lg:grid-cols-[minmax(0,1fr)_auto] lg:items-end lg:px-7 lg:py-6",style:{paddingTop:"var(--forge-shell-hero-padding-top)",paddingBottom:"var(--forge-shell-hero-padding-bottom)"},children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(121,136,255,0.16),transparent_34%)]"}),e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-px bg-white/10"}),e.jsxs("div",{className:"relative min-w-0 w-full max-w-full",children:[u?e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2 text-[11px] font-medium uppercase tracking-[0.2em] text-white/40",children:[c&&x?e.jsxs("span",{className:"inline-flex items-center gap-2 text-white/56","aria-label":c.label,title:c.label,children:[e.jsx(x,{className:re("size-3.5",c.iconClassName)}),e.jsx("span",{children:c.label})]}):null,v?e.jsx("span",{className:"text-[var(--secondary)]/80",children:v}):null,r?e.jsx(L,{tone:"signal",className:"h-8 rounded-full border border-white/8 bg-white/[0.04] px-3 text-[11px] font-medium tracking-[0.14em] text-white/80 uppercase",children:r}):null]}):null,e.jsx("div",{className:re("min-w-0 max-w-4xl text-[clamp(1.85rem,3.5vw,4rem)] font-medium leading-[0.92] text-white",u?"mt-3":""),style:{transform:"translateY(var(--forge-shell-hero-title-translate-y)) scale(var(--forge-shell-hero-title-scale))",transformOrigin:"top left",willChange:"transform"},children:i}),e.jsx("div",{className:"mt-2 min-w-0 max-w-3xl text-[14px] leading-6 text-white/58 sm:text-[15px]",style:{opacity:"var(--forge-shell-hero-description-opacity)",transform:"translateY(var(--forge-shell-hero-description-translate-y))",willChange:"opacity, transform"},children:n})]}),l?e.jsx("div",{className:"relative mt-4 flex min-w-0 w-full max-w-full flex-wrap items-center gap-2 lg:mt-0 lg:max-w-[26rem] lg:justify-end",children:l}):null]})}function Gs(t){return t.entityType==="goal"?`/goals/${t.entityId}`:t.entityType==="project"?`/projects/${t.entityId}`:t.entityType==="task"?`/tasks/${t.entityId}`:t.entityType==="strategy"?`/strategies/${t.entityId}`:t.entityType==="task_run"&&typeof t.metadata.taskId=="string"?`/tasks/${t.metadata.taskId}`:null}function In(t){return t.entityType==="goal"?"Open goal":t.entityType==="project"?"Open project":t.entityType==="strategy"?"Open strategy":t.entityType==="task"||t.entityType==="task_run"?"Open task":null}const Oi=nx(),wd=[Oi.accessor("title",{header:"Event",cell:t=>{const s=Gs(t.row.original);return s?e.jsx(Ae,{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()})}}),Oi.accessor("source",{header:"Source",cell:t=>e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/50",children:t.getValue()})}),Oi.display({id:"owner",header:"Owner",cell:t=>t.row.original.user?e.jsx(Ue,{user:t.row.original.user,compact:!0}):e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/32",children:"Unowned"})}),Oi.accessor("createdAt",{header:"When",cell:t=>e.jsx("div",{className:"text-sm text-white/55",children:Ol(t.getValue())})}),Oi.display({id:"actions",header:"Open",cell:t=>{const s=Gs(t.row.original);return s?e.jsx(Ae,{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 Dv({rows:t,onRemove:s}){const i=s?[...wd,Oi.display({id:"remove",header:"Correct",cell:n=>e.jsx(Q,{variant:"ghost",className:"h-auto px-0 py-0 text-[11px] uppercase tracking-[0.16em] text-white/55",onClick:()=>{s(n.row.original.id)},children:"Remove log"})})]:wd,a=rx({columns:i,data:t,getCoreRowModel:lx()});return e.jsx(ae,{className:"overflow-hidden p-0",children:e.jsxs("table",{className:"w-full border-collapse",children:[e.jsx("thead",{children:a.getHeaderGroups().map(n=>e.jsx("tr",{className:"bg-white/[0.03]",children:n.headers.map(r=>e.jsx("th",{className:"px-5 py-4 text-left font-label text-[11px] uppercase tracking-[0.18em] text-white/40",children:r.isPlaceholder?null:Ho(r.column.columnDef.header,r.getContext())},r.id))},n.id))}),e.jsx("tbody",{children:a.getRowModel().rows.map(n=>e.jsx("tr",{className:"bg-white/[0.015] transition hover:bg-white/[0.035]",children:n.getVisibleCells().map(r=>e.jsx("td",{className:"px-5 py-4 align-top",children:Ho(r.column.columnDef.cell,r.getContext())},r.id))},n.id))})]})})}function $v(){var u;const t=Je(),s=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],[i]=Pt(),a=We(),n=i.get("entityId")??void 0,r=i.get("entityType")??void 0,l=i.get("eventId"),o=fe({queryKey:["activity-archive",r,n,...s],queryFn:()=>jb({limit:100,entityType:r,entityId:n,userIds:s})}),c=xe({mutationFn:f=>Xh(f),onSuccess:async()=>{await Promise.all([a.invalidateQueries({queryKey:["activity-archive"]}),a.invalidateQueries({queryKey:["forge-snapshot"]}),a.invalidateQueries({queryKey:["task-context"]}),a.invalidateQueries({queryKey:["project-board"]})])}}),x=((u=o.data)==null?void 0:u.activity)??[];if(o.isLoading)return e.jsx(nt,{eyebrow:"Evidence archive",title:"Loading activity",description:"Pulling the visible audit trail, grouped evidence, and correction history."});if(o.isError)return e.jsx(ze,{eyebrow:"Evidence archive",error:o.error,onRetry:()=>void o.refetch()});if(x.length===0)return e.jsx(gt,{eyebrow:"Evidence archive",title:n?"No evidence matched this filter":"No activity recorded yet",description:n?"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 v=x.reduce((f,h)=>{const m=h.createdAt.slice(0,10);return f[m]=[...f[m]??[],h],f},{});return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{title:"Activity",description:n?"This filtered archive shows the evidence connected to the item you opened, so you can confirm what changed and when.":"Activity is your visible audit trail. Use it to inspect progress, confirm corrections, and trace work back to the goal, project, or task it came from.",badge:`${x.length} recent events`}),e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]",children:[e.jsx(Dv,{rows:x,onRemove:async f=>{await c.mutateAsync(f)}}),e.jsx("div",{className:"grid gap-4",children:Object.entries(v).slice(0,6).map(([f,h])=>e.jsxs(ae,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:f}),e.jsx("div",{className:"mt-4 grid gap-3",children:h.slice(0,3).map(m=>e.jsxs("div",{className:`rounded-[18px] p-4 ${l===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:Ol(m.createdAt)}),Gs(m)&&In(m)?e.jsx(Ae,{to:Gs(m),className:"mt-3 inline-flex text-[11px] uppercase tracking-[0.16em] text-[var(--primary)]",children:In(m)}):null]},m.id))})]},f))})]})]})}function br(t){return t.trim().toLowerCase()}function yd(t,s){return t.includes(s)?t:[...t,s]}function et({options:t,selectedValues:s,onChange:i,placeholder:a="Search or create…",emptyMessage:n="No matching entries yet.",createLabel:r="Create",onCreate:l,className:o}){const[c,x]=d.useState(""),[v,u]=d.useState(!1),[f,h]=d.useState(0),[m,b]=d.useState(!1),[w,M]=d.useState(null),[E,D]=d.useState([]),j=t??[],S=s??[],p=d.useMemo(()=>{const z=new Map;return[...E,...j].forEach(J=>{z.set(J.value,J)}),Array.from(z.values())},[E,j]),A=d.useMemo(()=>S.map(z=>p.find(J=>J.value===z)??{value:z,label:z}),[p,S]),T=br(c),k=d.useMemo(()=>{const z=p.filter(J=>!S.includes(J.value));return T?z.filter(J=>`${J.label} ${J.description??""} ${J.searchText??""}`.toLowerCase().includes(T)).slice(0,8):z.slice(0,8)},[p,T,S]),$=p.some(z=>br(z.label)===T),g=z=>{i(yd(S,z)),x(""),M(null),h(0),u(!1)},C=z=>{i(S.filter(J=>J!==z))},F=async()=>{const z=c.trim();if(!(!l||!z)){b(!0);try{const J=await l(z);D(O=>O.some(_=>_.value===J.value)?O:[J,...O]),i(yd(S,J.value)),x(""),M(null),h(0),u(!1)}catch(J){M(J instanceof Error?J.message:"Unable to create that link right now.")}finally{b(!1)}}};return e.jsxs("div",{className:re("relative grid gap-2",o),children:[e.jsxs("div",{className:"rounded-[22px] border border-white/10 bg-white/[0.04] px-3 py-3",children:[A.length>0?e.jsx("div",{className:"mb-2 flex flex-wrap gap-2",children:A.map(z=>e.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-2",children:[z.kind?e.jsx(Te,{kind:z.kind,label:z.label,compact:!0,className:"max-w-[16rem]"}):z.badge?z.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:z.label})}),e.jsx("button",{type:"button",className:"rounded-full text-white/50 transition hover:text-white","aria-label":`Remove ${z.label}`,onClick:()=>C(z.value),children:e.jsx(mt,{className:"size-3.5"})})]},z.value))}):null,e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bt,{className:"size-4 text-white/34"}),e.jsx("input",{value:c,onChange:z=>{x(z.target.value),M(null),u(!0),h(0)},onFocus:()=>u(!0),onBlur:()=>{window.setTimeout(()=>u(!1),120)},onKeyDown:z=>{if(z.key==="Backspace"&&!c&&S.length>0){C(S[S.length-1]);return}if(z.key==="ArrowDown"){z.preventDefault(),u(!0),h(_=>k.length===0?0:Math.min(k.length-1,_+1));return}if(z.key==="ArrowUp"){z.preventDefault(),h(_=>Math.max(0,_-1));return}if(z.key==="Escape"){u(!1);return}if(z.key!=="Enter")return;z.preventDefault();const J=k[f];if(J){g(J.value);return}const O=p.find(_=>br(_.label)===T);if(O&&!S.includes(O.value)){g(O.value);return}F()},placeholder:a,className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]})]}),v?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:[k.map((z,J)=>e.jsx("button",{type:"button",className:re("flex w-full items-start justify-between gap-3 rounded-[18px] px-3 py-2.5 text-left transition",J===f?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>h(J),onMouseDown:O=>O.preventDefault(),onClick:()=>g(z.value),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:z.kind?e.jsx(Te,{kind:z.kind,label:z.label,compact:!0,gradient:!1}):z.menuBadge?z.menuBadge:z.badge?z.badge:z.label}),z.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/46",children:z.description}):null]})},z.value)),!$&&T&&l?e.jsxs("button",{type:"button",disabled:m,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:z=>z.preventDefault(),onClick:()=>void F(),children:[e.jsx(zt,{className:"size-4"}),e.jsx("span",{className:"truncate",children:m?"Creating…":`${r} "${c.trim()}"`})]}):null,k.length===0&&(!T||$||!l)?e.jsx("div",{className:"px-3 py-2.5 text-sm text-white/42",children:n}):null]}):null,w?e.jsx("div",{className:"text-sm text-rose-300",children:w}):null]})}const Ov={goal:"goal",project:"project",task:"task",strategy:"strategy",habit:"habit"};function wi(t){const s=new Date(t);return new Date(s.getTime()-s.getTimezoneOffset()*6e4).toISOString().slice(0,16)}function jd(t,s){var r,l,o,c,x;const i=new Date,a=new Date(i.getTime()+30*6e4),n=new Date(a.getTime()+60*6e4);return{title:(s==null?void 0:s.title)??(t==null?void 0:t.title)??"",description:(s==null?void 0:s.description)??(t==null?void 0:t.description)??"",location:(s==null?void 0:s.location)??(t==null?void 0:t.location)??"",placeAddress:((r=s==null?void 0:s.place)==null?void 0:r.address)??((l=t==null?void 0:t.place)==null?void 0:l.address)??"",placeTimezone:((o=s==null?void 0:s.place)==null?void 0:o.timezone)??((c=t==null?void 0:t.place)==null?void 0:c.timezone)??"",startAtLocal:t?wi(t.startAt):s!=null&&s.startAt?wi(s.startAt):wi(a.toISOString()),endAtLocal:t?wi(t.endAt):s!=null&&s.endAt?wi(s.endAt):wi(n.toISOString()),timezone:(s==null?void 0:s.timezone)??(t==null?void 0:t.timezone)??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",availability:(s==null?void 0:s.availability)??(t==null?void 0:t.availability)??"busy",preferredCalendarId:s&&"preferredCalendarId"in s?s.preferredCalendarId:(t==null?void 0:t.calendarId)??void 0,categoriesText:((x=s==null?void 0:s.categories)==null?void 0:x.join(", "))??(t==null?void 0:t.categories.join(", "))??"",linkQuery:"",links:(s==null?void 0:s.links)??(t==null?void 0:t.links.map(v=>({entityType:v.entityType,entityId:v.entityId,relationshipType:v.relationshipType,label:`${v.entityType.replaceAll("_"," ")} · ${v.entityId}`})))??[]}}function Fv({open:t,onOpenChange:s,writableCalendars:i,linkOptions:a,event:n,seed:r,onSubmit:l,pending:o=!1}){const[c,x]=d.useState(()=>jd(n,r)),[v,u]=d.useState(null);d.useEffect(()=>{t&&(x(jd(n,r)),u(null))},[n,t,r]);const f=d.useMemo(()=>a.map(m=>{const b=Ov[m.entityType];return{value:`${m.entityType}:${m.entityId}`,label:m.label,description:m.subtitle,searchText:`${m.label} ${m.subtitle} ${m.entityType}`,kind:b,menuBadge:b?e.jsx(Te,{kind:b,label:m.label,compact:!0,gradient:!1}):void 0,badge:b?e.jsx(Te,{kind:b,label:m.label,compact:!0}):void 0}}),[a]),h=d.useMemo(()=>[{id:"identity",eyebrow:"Event",title:n?"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:(m,b)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(se,{label:"Title",children:e.jsx(le,{value:m.title,onChange:w=>b({title:w.target.value}),placeholder:"Weekly research supervision"})}),e.jsx(se,{label:"Description",children:e.jsx(Me,{value:m.description,onChange:w=>b({description:w.target.value}),placeholder:"Agenda, context, or outcomes you want this event to carry."})}),e.jsx(se,{label:"Location",children:e.jsx(le,{value:m.location,onChange:w=>b({location:w.target.value}),placeholder:"Clinic room 2 or Zoom"})}),e.jsx(se,{label:"Place address",children:e.jsx(le,{value:m.placeAddress,onChange:w=>b({placeAddress:w.target.value}),placeholder:"Bahnhofstrasse 10, Zurich"})}),e.jsx(se,{label:"Place timezone",children:e.jsx(le,{value:m.placeTimezone,onChange:w=>b({placeTimezone:w.target.value}),placeholder:"Europe/Zurich"})})]})},{id:"timing",eyebrow:"Timing",title:"Set the time and visibility",description:"Forge stores the real event window, timezone, and whether it should behave like a busy or free slot for scheduling rules.",render:(m,b)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(se,{label:"Starts",children:e.jsx(le,{type:"datetime-local",value:m.startAtLocal,onChange:w=>b({startAtLocal:w.target.value})})}),e.jsx(se,{label:"Ends",children:e.jsx(le,{type:"datetime-local",value:m.endAtLocal,onChange:w=>b({endAtLocal:w.target.value})})})]}),e.jsx(se,{label:"Timezone",children:e.jsx(le,{value:m.timezone,onChange:w=>b({timezone:w.target.value}),placeholder:"Europe/Zurich"})}),e.jsx(se,{label:"Availability",children:e.jsx(Ze,{value:m.availability,onChange:w=>b({availability:w}),options:[{value:"busy",label:"Busy",description:"This event should block timebox recommendations and rule checks."},{value:"free",label:"Free",description:"This event stays visible in the calendar without blocking work."}]})})]})},{id:"links",eyebrow:"Meaning",title:"Connect the event to Forge entities",description:"Attach this event to strategies, goals, projects, tasks, or habits so the calendar carries multi-user operating context instead of staying isolated.",render:(m,b)=>e.jsx("div",{className:"grid gap-4",children:e.jsx(se,{label:"Search Forge entities",description:"Search across human and bot-owned entities; the linked records use the same icon, color, and owner system as the rest of Forge.",children:e.jsx(et,{options:f,selectedValues:m.links.map(w=>`${w.entityType}:${w.entityId}`),onChange:w=>{b({links:w.map(M=>{const[E,...D]=M.split(":"),j=D.join(":"),S=a.find(p=>p.entityType===E&&p.entityId===j);return S?{entityType:S.entityType,entityId:S.entityId,relationshipType:"context",label:S.label}:null}).filter(M=>M!==null)})},placeholder:"Search strategies, goals, projects, tasks, habits, human, or bot owners",emptyMessage:"No matching Forge entities found."})})})},{id:"projection",eyebrow:"Projection",title:"Choose where this event should live remotely",description:"You can keep the event local to Forge, or choose a writable connected calendar so Forge also keeps a synced remote copy.",render:(m,b)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"grid gap-3",children:[i.length>0?e.jsxs("button",{type:"button",onClick:()=>b({preferredCalendarId:void 0}),className:`rounded-[22px] border px-4 py-4 text-left transition ${m.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(Xt,{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:()=>b({preferredCalendarId:null}),className:`rounded-[22px] border px-4 py-4 text-left transition ${m.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(Tt,{className:"size-4"}),"Forge only"]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/55",children:"Keep the event in Forge without creating a remote provider copy yet."})]}),i.map(w=>e.jsxs("button",{type:"button",onClick:()=>b({preferredCalendarId:w.id}),className:`rounded-[22px] border px-4 py-4 text-left transition ${m.preferredCalendarId===w.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(Xt,{className:"size-4"}),w.title]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/55",children:w.description||`${w.timezone} · writable`})]},w.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(Nl,{className:"size-4 text-[var(--primary)]"}),"Categories and filtering"]}),e.jsx(le,{value:m.categoriesText,onChange:w=>b({categoriesText:w.target.value}),placeholder:"meeting, clinic, research"})]})]})}],[n,a,f,i]);return e.jsx(rt,{open:t,onOpenChange:s,eyebrow:n?"Edit event":"New event",title:n?"Edit calendar event":"Create calendar event",description:"Forge-owned events can stay local or publish to a connected provider calendar.",value:c,onChange:x,steps:h,onSubmit:async()=>{if(!c.title.trim()){u("Add an event title before saving.");return}if(!c.startAtLocal||!c.endAtLocal){u("Set both the start and end time before saving.");return}if(new Date(c.endAtLocal).getTime()<=new Date(c.startAtLocal).getTime()){u("The event end time must be after the start time.");return}u(null),await l({title:c.title.trim(),description:c.description.trim(),location:c.location.trim(),place:{label:c.location.trim(),address:c.placeAddress.trim(),timezone:c.placeTimezone.trim(),latitude:null,longitude:null,source:c.placeAddress.trim()?"manual":"",externalPlaceId:""},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(m=>m.trim()).filter(Boolean),links:c.links.map(m=>({entityType:m.entityType,entityId:m.entityId,relationshipType:m.relationshipType})),...c.preferredCalendarId!==void 0?{preferredCalendarId:c.preferredCalendarId}:{}})},submitLabel:n?"Save event":"Create event",pending:o,pendingLabel:n?"Saving":"Creating",error:v})}function _v({open:t,onOpenChange:s,initialTitle:i,pending:a=!1,onSubmit:n}){const[r,l]=d.useState(i),[o,c]=d.useState(null);return d.useEffect(()=>{t&&(l(i),c(null))},[i,t]),e.jsx(rt,{open:t,onOpenChange:s,eyebrow:"Calendar",title:"Quick rename",description:"Rename the event without reopening the full event guide.",value:{title:r},onChange:x=>l(x.title),steps:[{id:"rename",eyebrow:"Rename",title:"Update the event title",description:"Keep the rename fast and direct. Everything else on the event stays unchanged.",render:(x,v)=>e.jsx(se,{label:"Event title",children:e.jsx(le,{value:x.title,onChange:u=>v({title:u.target.value}),placeholder:"Weekly research supervision"})})}],submitLabel:"Save title",pending:a,pendingLabel:"Saving",error:o,onSubmit:async()=>{const x=r.trim();if(!x){c("Add a title before saving.");return}c(null),await n(x),s(!1)}})}const Rv=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],sl=[{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 Tn(t=new Date){const s=new Date(t),i=s.getUTCDay(),a=i===0?-6:1-i;return s.setUTCDate(s.getUTCDate()+a),s.setUTCHours(0,0,0,0),s}function oi(t,s){const i=new Date(t);return i.setUTCDate(i.getUTCDate()+s),i}function pm(t){return Array.from({length:7},(s,i)=>oi(t,i))}function di(t){return new Intl.DateTimeFormat("en",{weekday:"short",month:"short",day:"numeric"}).format(t)}function Nd(t){const s=Math.floor(t/60).toString().padStart(2,"0"),i=String(t%60).padStart(2,"0");return`${s}:${i}`}function kd(t){return`${t.toString().padStart(2,"0")}:00`}function xm({eyebrow:t="Week view",description:s,weekStart:i,status:a,badges:n,onPrevious:r,onCurrent:l,onNext:o}){return e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:t}),e.jsx("p",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/60",children:s}),a?e.jsx("div",{className:"mt-3",children:a}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(L,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[e.jsx(Xt,{className:"mr-1 size-3.5"}),"Week of ",di(i)]}),n,e.jsx(Q,{variant:"secondary",onClick:r,children:"Previous"}),e.jsx(Q,{variant:"secondary",onClick:l,children:"This week"}),e.jsx(Q,{variant:"secondary",onClick:o,children:"Next"})]})]})}const Sd=[{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"}],Cd=[{value:"busy",label:"Busy"},{value:"free",label:"Free"}],rs={allowWorkBlockKinds:[],blockWorkBlockKinds:[],allowCalendarIds:[],blockCalendarIds:[],allowEventTypes:[],blockEventTypes:[],allowEventKeywords:[],blockEventKeywords:[],allowAvailability:[],blockAvailability:[]};function yi(t){return t.join(", ")}function ji(t){return t.split(",").map(s=>s.trim()).filter(Boolean)}function Ba({label:t,selected:s,onToggle:i,options:a}){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:a.map(n=>{const r=s.includes(n.value);return e.jsx("button",{type:"button",onClick:()=>i(n.value),className:`rounded-full px-3 py-2 text-sm transition ${r?"bg-[var(--primary)]/18 text-[var(--primary)] shadow-[inset_0_0_0_1px_rgba(192,193,255,0.24)]":"bg-white/[0.05] text-white/62 hover:bg-white/[0.08]"}`,children:n.label},n.value)})})]})}function Yl({title:t,subtitle:s,initialRules:i,initialPlannedDurationSeconds:a,onSave:n,saveLabel:r="Save scheduling rules",allowPlannedDuration:l=!1}){const[o,c]=d.useState((i==null?void 0:i.allowWorkBlockKinds)??rs.allowWorkBlockKinds),[x,v]=d.useState((i==null?void 0:i.blockWorkBlockKinds)??rs.blockWorkBlockKinds),[u,f]=d.useState((i==null?void 0:i.allowAvailability)??rs.allowAvailability),[h,m]=d.useState((i==null?void 0:i.blockAvailability)??rs.blockAvailability),[b,w]=d.useState(yi((i==null?void 0:i.allowCalendarIds)??rs.allowCalendarIds)),[M,E]=d.useState(yi((i==null?void 0:i.blockCalendarIds)??rs.blockCalendarIds)),[D,j]=d.useState(yi((i==null?void 0:i.allowEventTypes)??rs.allowEventTypes)),[S,p]=d.useState(yi((i==null?void 0:i.blockEventTypes)??rs.blockEventTypes)),[A,T]=d.useState(yi((i==null?void 0:i.allowEventKeywords)??rs.allowEventKeywords)),[k,$]=d.useState(yi((i==null?void 0:i.blockEventKeywords)??rs.blockEventKeywords)),[g,C]=d.useState(a?String(Math.round(a/60)):"30"),[F,z]=d.useState(!1),J=d.useMemo(()=>({allowWorkBlockKinds:o,blockWorkBlockKinds:x,allowCalendarIds:ji(b),blockCalendarIds:ji(M),allowEventTypes:ji(D),blockEventTypes:ji(S),allowEventKeywords:ji(A),blockEventKeywords:ji(k),allowAvailability:u,blockAvailability:h}),[u,b,A,D,o,h,M,k,S,x]),O=Object.values(J).every(B=>B.length===0),_=(B,K,Z)=>{K(B.includes(Z)?B.filter(U=>U!==Z):[...B,Z])};return e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:t}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:s})]}),l?e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Planned duration"}),e.jsx(le,{type:"number",min:15,step:15,value:g,onChange:B=>C(B.target.value),placeholder:"30"})]}):null,e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx(Ba,{label:"Allow work blocks",selected:o,onToggle:B=>_(o,c,B),options:Sd}),e.jsx(Ba,{label:"Block work blocks",selected:x,onToggle:B=>_(x,v,B),options:Sd}),e.jsx(Ba,{label:"Allow availability",selected:u,onToggle:B=>_(u,f,B),options:Cd}),e.jsx(Ba,{label:"Block availability",selected:h,onToggle:B=>_(h,m,B),options:Cd})]}),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(le,{value:b,onChange:B=>w(B.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(le,{value:M,onChange:B=>E(B.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(le,{value:D,onChange:B=>j(B.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(le,{value:S,onChange:B=>p(B.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(le,{value:A,onChange:B=>T(B.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(le,{value:k,onChange:B=>$(B.target.value),placeholder:"psychiatrist, clinic, rest"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(Q,{pending:F,pendingLabel:"Saving",onClick:async()=>{z(!0);try{await n({schedulingRules:O?rs:J,plannedDurationSeconds:l?Math.max(15,Number(g||30))*60:void 0})}finally{z(!1)}},children:r}),e.jsx(Q,{variant:"secondary",onClick:async()=>{z(!0);try{c([]),v([]),f([]),m([]),w(""),E(""),j(""),p(""),T(""),$(""),await n({schedulingRules:null,plannedDurationSeconds:l?Math.max(15,Number(g||30))*60:void 0})}finally{z(!1)}},children:"Clear custom rules"})]})]})}function zv({open:t,onOpenChange:s,tasks:i,onSave:a}){const n=d.useMemo(()=>i.filter(c=>c.status!=="done"),[i]),[r,l]=d.useState("");d.useEffect(()=>{if(t){if(n.length===0){l("");return}l(c=>c&&n.some(x=>x.id===c)?c:n[0].id)}},[n,t]);const o=n.find(c=>c.id===r)??null;return e.jsx(bs,{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(ae,{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(Tt,{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."})]})]})}),n.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Task"}),e.jsx("select",{value:r,onChange:c=>l(c.target.value),className:"rounded-[22px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none",children:n.map(c=>e.jsx("option",{value:c.id,children:c.title},c.id))})]}),o?e.jsx(Yl,{title:"Task rules",subtitle:"These rules are saved directly on the task. They drive blocked-now checks and future timebox recommendations.",initialRules:o.schedulingRules,initialPlannedDurationSeconds:o.plannedDurationSeconds,allowPlannedDuration:!0,saveLabel:"Save task rules",onSave:async({schedulingRules:c,plannedDurationSeconds:x})=>{await a({taskId:o.id,schedulingRules:c,plannedDurationSeconds:x===void 0?o.plannedDurationSeconds:x??null}),s(!1)}}):null]}):e.jsxs(ae,{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(Q,{variant:"secondary",onClick:()=>s(!1),children:"Close"})})]})]})})}function qv({open:t,onOpenChange:s,tasks:i,from:a,to:n,onCreateTimebox:r}){const l=d.useMemo(()=>i.filter(w=>w.status!=="done"),[i]),[o,c]=d.useState({taskId:"",selectedTimeboxId:""}),[x,v]=d.useState(null),[u,f]=d.useState(!1);d.useEffect(()=>{var M;if(!t)return;const w=((M=l[0])==null?void 0:M.id)??"";v(null),c({taskId:w,selectedTimeboxId:""})},[l,t]);const h=l.find(w=>w.id===o.taskId)??null,m=fe({queryKey:["forge-calendar-suggestions-dialog",o.taskId,a,n],queryFn:()=>df({taskId:o.taskId,from:a,to:n,limit:8}),enabled:t&&o.taskId.length>0});d.useEffect(()=>{var M;if(!t)return;const w=((M=m.data)==null?void 0:M.timeboxes)??[];if(!w.length){c(E=>E.selectedTimeboxId?{...E,selectedTimeboxId:""}:E);return}c(E=>E.selectedTimeboxId&&w.some(D=>D.id===E.selectedTimeboxId)?E:{...E,selectedTimeboxId:w[0].id})},[t,m.data]);const b=d.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:(w,M)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(se,{label:"Task",children:e.jsx("select",{value:w.taskId,onChange:E=>M({taskId:E.target.value,selectedTimeboxId:""}),className:"rounded-[22px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none",children:l.map(E=>e.jsx("option",{value:E.id,children:E.title},E.id))})}),h?e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:h.title}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(L,{className:"bg-white/[0.08] text-white/74",children:h.plannedDurationSeconds?`${Math.round(h.plannedDurationSeconds/60)} min target`:"No duration yet"}),e.jsx(L,{className:"bg-white/[0.08] text-white/74",children:h.schedulingRules?"Custom scheduling rules":"Inherits project rules"})]})]}):null]})},{id:"slot",eyebrow:"Suggestion",title:"Pick one of Forge's recommended timeboxes",description:"The slots below come from your connected calendar, work blocks, and the current task rules.",render:(w,M)=>{var D;const E=((D=m.data)==null?void 0:D.timeboxes)??[];return m.isLoading?e.jsx("div",{className:"text-sm text-white/62",children:"Looking for valid upcoming slots…"}):E.length?e.jsx("div",{className:"grid gap-3",children:E.map(j=>{const S=w.selectedTimeboxId===j.id;return e.jsxs("button",{type:"button",onClick:()=>M({selectedTimeboxId:j.id}),className:`rounded-[24px] border px-4 py-4 text-left transition ${S?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.14)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium",children:j.title}),e.jsx(L,{className:"bg-white/[0.08] text-white/76",children:j.source})]}),e.jsxs("div",{className:"mt-2 text-sm leading-6 text-white/58",children:[di(new Date(j.startsAt))," ·"," ",new Date(j.startsAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," ","-"," ",new Date(j.endsAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]},j.id)})}):e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"rounded-[24px] border border-amber-400/20 bg-amber-400/10 px-4 py-4 text-sm leading-6 text-amber-100/86",children:"Forge could not find a valid slot in the selected window. Adjust work blocks or task rules, then try again."}),e.jsx(Q,{variant:"secondary",onClick:()=>void m.refetch(),children:"Refresh suggestions"})]})}}],[l,h,m]);return e.jsx(rt,{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:o,onChange:c,steps:b,submitLabel:"Schedule timebox",pending:u,pendingLabel:"Scheduling",error:x,onSubmit:async()=>{var M;const w=(((M=m.data)==null?void 0:M.timeboxes)??[]).find(E=>E.id===o.selectedTimeboxId);if(!w){v("Pick one suggested slot before scheduling the timebox.");return}try{f(!0),v(null),await r({taskId:w.taskId,projectId:w.projectId,title:w.title,startsAt:w.startsAt,endsAt:w.endsAt,source:"suggested"}),s(!1)}catch(E){v(E instanceof Error?E.message:"Forge could not create the selected timebox.")}finally{f(!1)}}})}function Id(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=sl[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 Td(t){return t??""}function Bv({open:t,onOpenChange:s,onSubmit:i,pending:a=!1,template:n=null}){const[r,l]=d.useState(()=>Id(n)),[o,c]=d.useState(null),x=n!==null;d.useEffect(()=>{t&&(c(null),l(Id(n)))},[t,n]);const v=d.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:(u,f)=>e.jsx("div",{className:"grid gap-4",children:e.jsx(se,{label:"Block type",children:e.jsx(Ze,{value:u.kind,columns:3,onChange:h=>{const m=sl.find(b=>b.kind===h);if(m){const b=m.kind==="holiday"?[0,1,2,3,4,5,6]:[1,2,3,4,5];f({kind:m.kind,title:m.title,color:m.color,weekDays:b,startMinute:m.startMinute,endMinute:m.endMinute,blockingState:m.blockingState});return}f({kind:"custom",title:"Custom block",color:"#7dd3fc"})},options:[...sl.map(h=>({value:h.kind,label:h.title,description:`${Nd(h.startMinute)}-${Nd(h.endMinute)}`})),{value:"custom",label:"Custom",description:"Build a different recurring window."}]})})})},{id:"shape",eyebrow:"Schedule",title:"Define when this recurring block should exist",description:"Weekdays and times describe the recurring pattern. Optional start and end dates bound when the template is active.",render:(u,f)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(se,{label:"Block title",children:e.jsx(le,{value:u.title,onChange:h=>f({title:h.target.value}),placeholder:"Main Activity"})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(se,{label:"Start minute",children:e.jsx(le,{type:"number",min:0,max:1440,step:15,value:u.startMinute,onChange:h=>f({startMinute:Number(h.target.value)||0})})}),e.jsx(se,{label:"End minute",children:e.jsx(le,{type:"number",min:0,max:1440,step:15,value:u.endMinute,onChange:h=>f({endMinute:Number(h.target.value)||0})})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(se,{label:"Start date",children:e.jsx(le,{type:"date",value:Td(u.startsOn),onChange:h=>f({startsOn:h.target.value.trim()||null})})}),e.jsx(se,{label:"End date",children:e.jsx(le,{type:"date",value:Td(u.endsOn),onChange:h=>f({endsOn:h.target.value.trim()||null})})})]}),e.jsx("div",{className:"text-sm leading-6 text-white/54",children:"Leave the end date empty to keep repeating indefinitely. Holiday blocks work well with all seven weekdays and `0-1440`."}),e.jsx(se,{label:"Weekdays",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:Rv.map((h,m)=>{const b=u.weekDays.includes(m);return e.jsx("button",{type:"button",onClick:()=>f({weekDays:b?u.weekDays.filter(w=>w!==m):[...u.weekDays,m].sort((w,M)=>w-M)}),className:`rounded-full px-3 py-2 text-sm transition ${b?"bg-[var(--primary)]/18 text-[var(--primary)] shadow-[inset_0_0_0_1px_rgba(192,193,255,0.24)]":"bg-white/[0.05] text-white/62 hover:bg-white/[0.08]"}`,children:h},h)})})})]})},{id:"policy",eyebrow:"Policy",title:"Tell Forge whether this block allows or blocks work",description:"Use blocked mode for time that should normally stop optional work. Use allowed mode for protected focus windows.",render:(u,f)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(se,{label:"Work effect",children:e.jsx(Ze,{value:u.blockingState,onChange:h=>f({blockingState:h}),options:[{value:"blocked",label:"Blocks work",description:"Starting blocked tasks should require an explicit override."},{value:"allowed",label:"Allows work",description:"Use this for protected windows where the right tasks should fit."}]})}),e.jsx(se,{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:u.color,onChange:h=>f({color:h.target.value})}),e.jsx(le,{className:"border-none bg-transparent px-0 py-0",value:u.color,onChange:h=>f({color:h.target.value})})]})})]})}],[]);return e.jsx(rt,{open:t,onOpenChange:s,eyebrow:"Calendar",title:x?"Edit work block":"Create a work block",description:x?"Adjust the recurring pattern, date bounds, or work policy for this block.":"Build recurring half-day, holiday, or custom blocks so Forge can understand when work should be protected or blocked.",value:r,onChange:l,steps:v,submitLabel:x?"Save changes":"Save work block",pending:a,pendingLabel:x?"Saving changes":"Saving",error:o,onSubmit:async()=>{if(!r.title.trim()){c("Give the block a title so it stays readable in the calendar.");return}if(r.weekDays.length===0){c("Select at least one weekday for the recurring block.");return}if(r.endMinute<=r.startMinute){c("The end minute needs to be later than the start minute.");return}if(r.startsOn&&r.endsOn&&r.endsOn<r.startsOn){c("The end date needs to be on or after the start date.");return}try{c(null),await i({...r,title:r.title.trim()}),s(!1)}catch(u){c(u instanceof Error?u.message:"Forge could not save this work block.")}}})}function Yt({className:t}){return e.jsx("div",{className:re("surface-pulse rounded-2xl bg-white/[0.05]",t)})}function It({header:t=!0,sideRail:s=!0,className:i,eyebrow:a,title:n,description:r,columns:l=2,blocks:o=4}){const c=Array.from({length:Math.max(2,o)});return e.jsxs("div",{className:re("grid gap-5",i),"aria-hidden":"true",children:[t?e.jsxs(ae,{className:"grid gap-4",children:[e.jsx(Yt,{className:re("h-3",a?"w-40":"w-32")}),e.jsx(Yt,{className:re("h-12",n?"max-w-2xl":"max-w-3xl")}),e.jsx(Yt,{className:re("h-5",r?"max-w-3xl":"max-w-2xl")})]}):null,e.jsxs("section",{className:re("grid gap-5",s?"xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]":""),children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ae,{className:"grid gap-4",children:[e.jsx(Yt,{className:"h-3 w-28"}),e.jsx(Yt,{className:"h-28 w-full"})]}),e.jsxs(ae,{className:"grid gap-4",children:[e.jsx(Yt,{className:"h-3 w-40"}),e.jsx("div",{className:re("grid gap-3",l>1?"md:grid-cols-2":""),children:c.map((x,v)=>e.jsx(Yt,{className:"h-28 w-full"},v))})]})]}),s?e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ae,{className:"grid gap-4",children:[e.jsx(Yt,{className:"h-3 w-24"}),e.jsx(Yt,{className:"h-20 w-full"})]}),e.jsxs(ae,{className:"grid gap-4",children:[e.jsx(Yt,{className:"h-3 w-36"}),e.jsx(Yt,{className:"h-16 w-full"}),e.jsx(Yt,{className:"h-16 w-full"})]})]}):null]})]})}function gm({open:t,title:s,subtitle:i,items:a,position:n,onClose:r}){return d.useEffect(()=>{if(!t)return;let l=!1;const o=window.setTimeout(()=>{l=!0},0),c=v=>{v.key==="Escape"&&r()},x=()=>{l&&r()};return window.addEventListener("keydown",c),window.addEventListener("pointerdown",x),()=>{window.clearTimeout(o),window.removeEventListener("keydown",c),window.removeEventListener("pointerdown",x)}},[r,t]),!t||!n||typeof document>"u"?null:zn.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(n.x,window.innerWidth-24-352),top:Math.min(n.y,window.innerHeight-24-320)},onPointerDown:l=>l.stopPropagation(),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-[20px] bg-white/[0.03] px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:s}),i?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/50",children:i}):null]}),e.jsx("button",{type:"button",className:"rounded-full bg-white/[0.04] p-2 text-white/55 transition hover:bg-white/[0.08] hover:text-white",onClick:r,children:e.jsx(mt,{className:"size-4"})})]}),e.jsx("div",{className:"mt-2 grid gap-1",children:a.map(l=>{const o=l.icon;return e.jsxs("button",{type:"button",disabled:l.disabled,onClick:()=>{l.disabled||(l.onSelect(),r())},className:re("flex w-full items-start gap-3 rounded-[20px] px-4 py-3 text-left transition",l.disabled?"cursor-not-allowed bg-white/[0.02] text-white/28":l.tone==="danger"?"bg-rose-400/[0.05] text-rose-100 hover:bg-rose-400/[0.12]":"bg-white/[0.03] text-white/76 hover:bg-white/[0.08] hover:text-white"),children:[o?e.jsx("span",{className:re("mt-0.5 rounded-[14px] p-2",l.disabled?"bg-white/[0.03] text-white/28":l.tone==="danger"?"bg-rose-400/[0.12] text-rose-100":"bg-[var(--primary)]/12 text-[var(--primary)]"),children:e.jsx(o,{className:"size-4"})}):null,e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium",children:l.label}),l.description?e.jsx("span",{className:"mt-1 block text-xs leading-5 text-white/48",children:l.description}):null]})]},l.id)})})]})}),document.body)}const fm="forge.calendar-display-preferences",Pd=["#7dd3fc","#34d399","#f59e0b","#fb7185","#60a5fa","#a3e635","#f97316","#22c55e"],vr={useCalendarColors:!0,calendarColors:{}};function bm(t){return typeof t=="string"&&/^#[0-9a-fA-F]{6}$/.test(t)}function vm(){if(typeof window>"u")return vr;const t=window.localStorage.getItem(fm);if(!t)return vr;try{const s=JSON.parse(t);return{useCalendarColors:s.useCalendarColors??!0,calendarColors:s.calendarColors&&typeof s.calendarColors=="object"?Object.fromEntries(Object.entries(s.calendarColors).filter(i=>bm(i[1]))):{}}}catch{return vr}}function Kv(t){typeof window>"u"||window.localStorage.setItem(fm,JSON.stringify(t))}function wm(t){return Pd[t%Pd.length]??"#7dd3fc"}function ym(t,s){return Object.fromEntries(t.map((i,a)=>[i.id,bm(s[i.id])?s[i.id]:wm(a)]))}function Md(t){let s=0;for(let i=0;i<t.length;i+=1)s=s*31+t.charCodeAt(i)>>>0;return wm(s)}const Ka=hh(t=>({entry:null,setEntry:s=>t({entry:s}),clear:()=>t({entry:null}),completePaste:()=>t(s=>{var i;return{entry:((i=s.entry)==null?void 0:i.mode)==="cut"?null:s.entry}})})),Uv={goal:"goal",project:"project",task:"task",habit:"habit"};function Qv(t){const s=new Date(t);s.setUTCHours(9,0,0,0);const i=new Date(s.getTime()+3600*1e3);return{startAt:s.toISOString(),endAt:i.toISOString(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",availability:"busy"}}function Ad(t){const s=typeof t.location=="string"?t.location:"",i=t.place??{label:s,address:"",timezone:"",latitude:null,longitude:null,source:"",externalPlaceId:""};return{...t,place:{label:i.label||s,address:i.address??"",timezone:i.timezone??"",latitude:i.latitude??null,longitude:i.longitude??null,source:i.source??"",externalPlaceId:i.externalPlaceId??""}}}function Ed(t,s){const i=new Date(t.startAt),n=new Date(t.endAt).getTime()-i.getTime(),r=new Date(s);r.setUTCHours(i.getUTCHours(),i.getUTCMinutes(),0,0);const l=new Date(r.getTime()+n);return{startAt:r.toISOString(),endAt:l.toISOString()}}function Ld(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 Wv(t){switch(t){case"apple":return"Apple";case"google":return"Google";case"caldav":return"CalDAV";case"native":return"Forge";default:return"Derived"}}function Hv(t,s){var i;if(t.calendarId){const a=(i=s.get(t.calendarId))==null?void 0:i.trim();if(a)return a}return t.originType==="native"?"Forge only":Wv(t.originType)}function Dd(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 $d(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 Gv(){var wt,kt,Qt;const t=ut(),s=Je(),i=Array.isArray(s.selectedUserIds)?s.selectedUserIds:[],a=Mt(i),n=We(),r=Ka(oe=>oe.entry),l=Ka(oe=>oe.setEntry),o=Ka(oe=>oe.clear),c=Ka(oe=>oe.completePaste),[x,v]=d.useState(()=>Tn()),[u,f]=d.useState(null),[h,m]=d.useState(null),[b,w]=d.useState(!1),[M,E]=d.useState(null),[D,j]=d.useState(!1),[S,p]=d.useState(!1),[A,T]=d.useState(!1),[k,$]=d.useState(null),[g,C]=d.useState(null),F=d.useMemo(()=>vm(),[]),[z,J]=d.useState(null),[O,_]=d.useState(null),[B,K]=d.useState(null),Z=d.useMemo(()=>{const oe=x.toISOString(),ke=oi(x,7).toISOString();return{from:oe,to:ke}},[x]),U=fe({queryKey:["forge-calendar-overview",Z.from,Z.to,...i],queryFn:()=>Xn({...Z,userIds:i})}),I=["forge-calendar-overview",Z.from,Z.to,...i],G=oe=>{if(oe.deletedAt)return!1;const ke=new Date(oe.startAt).getTime();return ke>=new Date(Z.from).getTime()&&ke<new Date(Z.to).getTime()},W=oe=>{n.setQueryData(I,ke=>ke&&oe(ke))},ne=async()=>{await Promise.all([n.invalidateQueries({queryKey:["forge-calendar-overview"]}),n.invalidateQueries({queryKey:["forge-snapshot"]}),n.invalidateQueries({queryKey:["task-context"]}),n.invalidateQueries({queryKey:["project-board"]})])},de=xe({mutationFn:oe=>ef({...oe,userId:oe.userId??a}),onSuccess:ne}),we=xe({mutationFn:({templateId:oe,patch:ke})=>tf(oe,ke),onSuccess:ne}),Ne=xe({mutationFn:sf,onSuccess:ne}),H=xe({mutationFn:oe=>lf({...oe,userId:a}),onSuccess:ne}),me=xe({mutationFn:({timeboxId:oe,startsAt:ke,endsAt:$e})=>of(oe,{startsAt:ke,endsAt:$e}),onSuccess:ne}),y=xe({mutationFn:oe=>af({...oe,userId:oe.userId??a}),onMutate:async oe=>{var ve,Ee,Oe,tt,Qe,St,Le;K({tone:"saving",message:"Saving event changes in the background…"}),await n.cancelQueries({queryKey:I});const ke=n.getQueryData(I),$e=(ke==null?void 0:ke.calendar.calendars.find(pt=>pt.canWrite&&pt.selectedForSync))??(ke==null?void 0:ke.calendar.calendars.find(pt=>pt.canWrite))??null,Ye=new Date().toISOString(),Pe={id:`calendar_event_optimistic_${Date.now()}`,connectionId:($e==null?void 0:$e.connectionId)??null,calendarId:oe.preferredCalendarId===void 0?($e==null?void 0:$e.id)??null:oe.preferredCalendarId,remoteId:null,ownership:"forge",originType:"native",status:"confirmed",title:oe.title,description:oe.description??"",location:oe.location??"",place:{label:((ve=oe.place)==null?void 0:ve.label)??oe.location??"",address:((Ee=oe.place)==null?void 0:Ee.address)??"",timezone:((Oe=oe.place)==null?void 0:Oe.timezone)??oe.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",latitude:((tt=oe.place)==null?void 0:tt.latitude)??null,longitude:((Qe=oe.place)==null?void 0:Qe.longitude)??null,source:((St=oe.place)==null?void 0:St.source)??"forge",externalPlaceId:((Le=oe.place)==null?void 0:Le.externalPlaceId)??""},startAt:oe.startAt,endAt:oe.endAt,timezone:oe.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",isAllDay:oe.isAllDay??!1,availability:oe.availability??"busy",eventType:oe.eventType??"general",categories:oe.categories??[],sourceMappings:[],links:(oe.links??[]).map((pt,_t)=>({id:`calendar_event_link_optimistic_${Date.now()}_${_t}`,entityType:pt.entityType,entityId:pt.entityId,relationshipType:pt.relationshipType??"context",createdAt:Ye,updatedAt:Ye})),remoteUpdatedAt:null,deletedAt:null,createdAt:Ye,updatedAt:Ye};return ke&&G(Pe)&&W(pt=>({...pt,calendar:{...pt.calendar,events:[Pe,...pt.calendar.events]}})),{previous:ke,optimisticEventId:Pe.id}},onError:(oe,ke,$e)=>{$e!=null&&$e.previous&&n.setQueryData(I,$e.previous),K({tone:"error",message:oe instanceof Error?oe.message:"Forge could not sync that event change."})},onSuccess:({event:oe},ke,$e)=>{K(null),W(Ye=>({...Ye,calendar:{...Ye.calendar,events:(G(oe)?[oe,...Ye.calendar.events.filter(Pe=>Pe.id!==($e==null?void 0:$e.optimisticEventId))]:Ye.calendar.events.filter(Pe=>Pe.id!==($e==null?void 0:$e.optimisticEventId))).filter((Pe,ve,Ee)=>Ee.findIndex(Oe=>Oe.id===Pe.id)===ve)}}))},onSettled:ne}),P=xe({mutationFn:({eventId:oe,patch:ke})=>nf(oe,ke),onMutate:async({eventId:oe,patch:ke})=>{K({tone:"saving",message:"Saving event changes in the background…"}),await n.cancelQueries({queryKey:I});const $e=n.getQueryData(I);return $e&&W(Ye=>{var Oe;const Pe=Ye.calendar.events.find(tt=>tt.id===oe);if(!Pe)return Ye;const ve=Ad(Pe),Ee={...ve,...ke,place:ke.place?{...ve.place,...ke.place}:ve.place,calendarId:ke.preferredCalendarId===void 0?ve.calendarId:ke.preferredCalendarId,links:((Oe=ke.links)==null?void 0:Oe.map((tt,Qe)=>{var St,Le;return{id:((St=ve.links[Qe])==null?void 0:St.id)??`calendar_event_link_optimistic_${Date.now()}_${Qe}`,entityType:tt.entityType,entityId:tt.entityId,relationshipType:tt.relationshipType??"context",createdAt:((Le=ve.links[Qe])==null?void 0:Le.createdAt)??ve.createdAt,updatedAt:new Date().toISOString()}}))??ve.links,updatedAt:new Date().toISOString()};return{...Ye,calendar:{...Ye.calendar,events:Ye.calendar.events.map(tt=>tt.id===oe?Ee:tt).filter(G)}}}),{previous:$e}},onError:(oe,ke,$e)=>{$e!=null&&$e.previous&&n.setQueryData(I,$e.previous),K({tone:"error",message:oe instanceof Error?oe.message:"Forge could not sync that event change."})},onSuccess:({event:oe})=>{K(null),W(ke=>({...ke,calendar:{...ke.calendar,events:ke.calendar.events.map($e=>$e.id===oe.id?oe:$e).filter(G)}}))},onSettled:ne}),q=xe({mutationFn:rf,onMutate:async oe=>{K({tone:"saving",message:"Removing the event in the background…"}),await n.cancelQueries({queryKey:I});const ke=n.getQueryData(I);return ke&&W($e=>({...$e,calendar:{...$e.calendar,events:$e.calendar.events.filter(Ye=>Ye.id!==oe)}})),{previous:ke}},onError:(oe,ke,$e)=>{$e!=null&&$e.previous&&n.setQueryData(I,$e.previous),K({tone:"error",message:oe instanceof Error?oe.message:"Forge could not delete that event."})},onSuccess:()=>{K(null)},onSettled:ne}),pe=(wt=U.data)==null?void 0:wt.calendar,ee=d.useMemo(()=>pm(x),[x]),Y=d.useMemo(()=>pe?{...pe,events:pe.events.map(Ad)}:{generatedAt:"",providers:[],connections:[],calendars:[],events:[],workBlockTemplates:[],workBlockInstances:[],timeboxes:[]},[pe]),R=d.useMemo(()=>new Map(Y.calendars.map(oe=>[oe.id,oe.title])),[Y.calendars]),X=d.useMemo(()=>ym(Y.calendars,F.calendarColors),[F.calendarColors,Y.calendars]),be=y.isPending||P.isPending||q.isPending,Ie=Y.timeboxes.filter(oe=>oe.status==="planned"),te=Y.calendars.filter(oe=>oe.canWrite),ce=(oe,ke)=>ke?`${oe} · ${ke}`:oe,Se=[...s.snapshot.goals.map(oe=>({entityType:"goal",entityId:oe.id,label:oe.title,subtitle:ce("Goal",Nt(oe.user))})),...s.snapshot.projects.map(oe=>({entityType:"project",entityId:oe.id,label:oe.title,subtitle:ce("Project",Nt(oe.user))})),...s.snapshot.tasks.map(oe=>({entityType:"task",entityId:oe.id,label:oe.title,subtitle:ce("Task",Nt(oe.user))})),...s.snapshot.strategies.map(oe=>({entityType:"strategy",entityId:oe.id,label:oe.title,subtitle:ce("Strategy",Nt(oe.user))})),...s.snapshot.habits.map(oe=>({entityType:"habit",entityId:oe.id,label:oe.title,subtitle:ce("Habit",Nt(oe.user))}))],he=d.useMemo(()=>new Map(Se.map(oe=>[`${oe.entityType}:${oe.entityId}`,oe.label])),[Se]),Ge=Y.connections.length===0?"No providers connected":`${Y.connections.filter(oe=>oe.status==="connected").length}/${Y.connections.length} healthy`,De=(r==null?void 0:r.items.filter(oe=>oe.type==="calendar_event"))??[],ue=oe=>{$(null),J(Qv(oe)),T(!0)},Fe=async(oe,ke)=>{const $e=Ed({startAt:oe.startAt,endAt:oe.endAt},ke);await P.mutateAsync({eventId:oe.id,patch:$e})},dt=async oe=>{if(De.length!==0){for(const ke of De){const $e=Ed(ke,oe);(r==null?void 0:r.mode)==="cut"?await P.mutateAsync({eventId:ke.eventId,patch:$e}):await y.mutateAsync({title:ke.title,description:ke.description,location:ke.location,startAt:$e.startAt,endAt:$e.endAt,timezone:ke.timezone,availability:ke.availability,preferredCalendarId:ke.preferredCalendarId,categories:ke.categories,links:ke.links})}c()}},yt=d.useMemo(()=>{if(!O)return[];if(O.kind==="day"){const ke=ee.find($e=>$e.toISOString().slice(0,10)===O.dayKey);return ke?[{id:"create-event",label:"Create event",description:"Open the event guide with this day already selected.",icon:Ns,onSelect:()=>ue(ke)},{id:"create-work-block",label:"Create work block",description:"Open the guided work-block flow while you are looking at this day.",icon:ya,onSelect:()=>{E(null),w(!0)}},{id:"paste",label:(r==null?void 0:r.mode)==="cut"?"Paste moved event":"Paste copied event",description:De.length>0?`${De.length} calendar item${De.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:sp,disabled:De.length===0,onSelect:()=>void dt(ke)}]:[]}if(O.kind==="work-block"){const ke=Y.workBlockTemplates.find($e=>$e.id===O.templateId);return ke?[{id:"edit-work-block",label:"Edit",description:"Adjust the recurring pattern, date bounds, or work policy.",icon:Ns,onSelect:()=>{E(ke),w(!0)}},{id:"delete-work-block",label:"Delete",description:"Remove this recurring work block from Forge.",icon:ct,tone:"danger",onSelect:()=>{(M==null?void 0:M.id)===ke.id&&E(null),Ne.mutateAsync(ke.id)}}]:[]}const oe=Y.events.find(ke=>ke.id===O.eventId);return oe?[{id:"rename",label:"Quick rename",description:"Change the event title without opening the full event flow.",icon:Ns,onSelect:()=>C(oe)},{id:"copy",label:"Copy",description:"Put this event on the Forge clipboard so you can paste it into another day.",icon:mh,onSelect:()=>l({id:`clipboard_${oe.id}_${Date.now()}`,mode:"copy",source:"calendar",label:oe.title,createdAt:new Date().toISOString(),items:[Ld(oe)]})},{id:"cut",label:"Cut",description:"Move this event by pasting it into another day.",icon:ip,onSelect:()=>l({id:`clipboard_cut_${oe.id}_${Date.now()}`,mode:"cut",source:"calendar",label:oe.title,createdAt:new Date().toISOString(),items:[Ld(oe)]})},{id:"delete",label:"Delete",description:"Remove the event from Forge and delete any connected remote projection.",icon:ct,tone:"danger",onSelect:()=>{(r==null?void 0:r.mode)==="cut"&&De.some(ke=>ke.eventId===oe.id)&&o(),q.mutateAsync(oe.id)}}]:[]},[o,De,r,ee,q,Ne,O,Y.events,Y.workBlockTemplates,M,l]);return U.isLoading?e.jsx(It,{}):U.isError||!U.data?e.jsx(ze,{eyebrow:"Calendar",error:U.error??new Error("Calendar data is unavailable"),onRetry:()=>void U.refetch()}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{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:`${Y.connections.length} connection${Y.connections.length===1?"":"s"}`}),e.jsxs(ae,{className:"grid gap-4 rounded-[32px] border border-white/8 bg-[linear-gradient(180deg,rgba(17,28,39,0.985),rgba(10,17,29,0.985))]",children:[e.jsx(xm,{description:"The calendar is the priority surface here. Connected provider events, recurring work blocks, and owned task timeboxes all stay visible together.",weekStart:x,status:B?e.jsx("div",{className:`inline-flex max-w-full items-center gap-2 rounded-full px-3 py-1.5 text-xs ${B.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:B.message}):null,badges:e.jsxs(e.Fragment,{children:[be?e.jsxs(L,{className:"bg-white/[0.08] text-white/78",children:[e.jsx(Is,{className:"mr-1 size-3.5 animate-spin"}),"Syncing changes"]}):null,r?e.jsxs(L,{className:"bg-white/[0.08] text-white/74",children:[r.mode==="cut"?"Cut":"Copied"," · ",r.label]}):null]}),onPrevious:()=>v(oi(x,-7)),onCurrent:()=>v(Tn()),onNext:()=>v(oi(x,7))}),e.jsx("div",{className:"grid gap-3 [grid-template-columns:repeat(auto-fit,minmax(min(100%,17rem),1fr))] 2xl:[grid-template-columns:repeat(7,minmax(0,1fr))]",children:ee.map(oe=>{const ke=oe.toISOString().slice(0,10),$e=Y.events.filter(ve=>ve.startAt.slice(0,10)===ke&&!ve.deletedAt),Ye=Y.workBlockInstances.filter(ve=>ve.dateKey===ke),Pe=Y.timeboxes.filter(ve=>ve.startsAt.slice(0,10)===ke);return e.jsxs("div",{"data-calendar-day":ke,onClick:ve=>{ve.target.closest("[data-calendar-item='true']")||_({kind:"day",dayKey:ke,position:{x:ve.clientX,y:ve.clientY}})},onDragOver:ve=>{ve.preventDefault()},onDrop:ve=>{ve.preventDefault();const Ee=ve.dataTransfer.getData("text/forge-event-id")||h;if(Ee){const Jt=Y.events.find(ws=>ws.id===Ee);Jt&&Fe(Jt,oe),m(null);return}const Oe=ve.dataTransfer.getData("text/forge-timebox-id")||u;if(!Oe)return;const tt=Y.timeboxes.find(Jt=>Jt.id===Oe);if(!tt)return;const Qe=new Date(tt.startsAt),Le=new Date(tt.endsAt).getTime()-Qe.getTime(),pt=new Date(oe);pt.setUTCHours(Qe.getUTCHours(),Qe.getUTCMinutes(),0,0);const _t=new Date(pt.getTime()+Le);me.mutateAsync({timeboxId:Oe,startsAt:pt.toISOString(),endsAt:_t.toISOString()}),f(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:di(oe)}),e.jsx("button",{type:"button","aria-label":`Open actions for ${di(oe)}`,className:"rounded-full bg-white/[0.06] p-2 text-white/58 transition hover:bg-white/[0.1] hover:text-white",onClick:ve=>{ve.stopPropagation(),_({kind:"day",dayKey:ke,position:{x:ve.clientX,y:ve.clientY}})},children:e.jsx(cn,{className:"size-4"})})]}),e.jsxs("div",{className:"mt-3 grid min-w-0 gap-2",children:[Ye.map(ve=>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:`${ve.color}22`,border:`1px solid ${ve.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:ve.title}),e.jsxs("div",{className:"mt-1 flex min-w-0 flex-wrap items-center gap-1.5",children:[e.jsx(L,{size:"sm",className:"shrink-0 bg-white/[0.08] text-white/78",children:ve.blockingState}),e.jsx(L,{size:"sm",className:"shrink-0 bg-white/[0.08] text-white/78",children:Dd(ve.kind)})]})]}),e.jsx("button",{type:"button","aria-label":`Open actions for ${ve.title}`,className:"rounded-full bg-white/[0.05] p-1.5 text-white/56 transition hover:bg-white/[0.1] hover:text-white",onClick:Ee=>{Ee.stopPropagation(),_({kind:"work-block",templateId:ve.templateId,position:{x:Ee.clientX,y:Ee.clientY}})},children:e.jsx(cn,{className:"size-4"})})]}),e.jsxs("div",{className:"mt-1 text-white/60",children:[new Date(ve.startAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," ","-"," ",new Date(ve.endAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),e.jsx("div",{className:"mt-2 text-xs text-white/48",children:$d(Y.workBlockTemplates.find(Ee=>Ee.id===ve.templateId)??{id:ve.templateId,title:ve.title,kind:ve.kind,color:ve.color,startsOn:null,endsOn:null,blockingState:ve.blockingState,createdAt:ve.createdAt,updatedAt:ve.updatedAt})})]},ve.id)),$e.map(ve=>e.jsxs("div",{"data-calendar-item":"true",draggable:!0,onDragStart:Ee=>{m(ve.id),Ee.dataTransfer.setData("text/forge-event-id",ve.id)},onClick:Ee=>{Ee.stopPropagation(),$(ve),J(null),T(!0)},className:`min-w-0 cursor-move overflow-hidden rounded-[18px] px-3 py-2 text-left text-sm text-white/82 transition ${F.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:F.useCalendarColors?{backgroundColor:`${(ve.calendarId?X[ve.calendarId]:null)??Md(`origin:${ve.originType}`)}1f`,border:`1px solid ${(ve.calendarId?X[ve.calendarId]:null)??Md(`origin:${ve.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:ve.title}),e.jsxs("div",{className:"mt-1 text-white/55",children:[new Date(ve.startAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," ","-"," ",new Date(ve.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 ${ve.title}`,className:"rounded-full bg-white/[0.05] p-1.5 text-white/56 transition hover:bg-white/[0.1] hover:text-white",onClick:Ee=>{Ee.stopPropagation(),_({kind:"event",eventId:ve.id,position:{x:Ee.clientX,y:Ee.clientY}})},children:e.jsx(cn,{className:"size-4"})})})]}),e.jsxs("div",{className:"mt-2 flex min-w-0 flex-wrap items-center gap-1.5",children:[e.jsx(L,{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:Hv(ve,R)}),ve.calendarId&&F.useCalendarColors?e.jsx("span",{"aria-hidden":"true",className:"size-2.5 shrink-0 rounded-full",style:{backgroundColor:X[ve.calendarId]}}):null]}),ve.place.address||ve.place.timezone?e.jsxs("div",{className:"mt-2 text-xs leading-5 text-white/50",children:[ve.place.address||ve.location,ve.place.address&&ve.place.timezone?" · ":"",ve.place.timezone]}):null,ve.links.length>0?e.jsx("div",{className:"mt-2 flex min-w-0 flex-wrap gap-1.5",children:ve.links.slice(0,3).map(Ee=>{const Oe=Uv[Ee.entityType];return Oe?e.jsx(Te,{kind:Oe,label:he.get(`${Ee.entityType}:${Ee.entityId}`)??Ee.entityType,compact:!0,gradient:!1},Ee.id):e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:Ee.entityType},Ee.id)})}):null]},ve.id)),Pe.map(ve=>e.jsxs("div",{"data-calendar-item":"true",draggable:!0,onDragStart:Ee=>{f(ve.id),Ee.dataTransfer.setData("text/forge-timebox-id",ve.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:ve.title}),e.jsx(L,{size:"sm",className:"shrink-0 bg-white/[0.08] text-white/78",children:ve.status})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-white/70",children:[e.jsx(gi,{className:"size-3.5"}),new Date(ve.startsAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," ","-"," ",new Date(ve.endsAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]},ve.id)),Ye.length===0&&$e.length===0&&Pe.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]})]},ke)})})]}),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(ae,{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(Ns,{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(Q,{onClick:()=>{E(null),$(null),J(null),T(!0)},children:[e.jsx(Ns,{className:"size-4"}),"Open event guide"]})})]}),e.jsxs(ae,{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(ya,{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(Q,{onClick:()=>{E(null),w(!0)},children:[e.jsx(ya,{className:"size-4"}),"Open work-block guide"]})})]}),e.jsxs(ae,{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(Tt,{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(Q,{onClick:()=>p(!0),children:[e.jsx(Tt,{className:"size-4"}),"Open planning guide"]})})]}),e.jsxs(ae,{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(fs,{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:Ge})]})]}),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(Q,{variant:"secondary",onClick:()=>t("/settings/calendar"),children:[e.jsx(Ms,{className:"size-4"}),"Open calendar settings"]}),e.jsxs(Q,{variant:"secondary",onClick:()=>t("/settings/calendar?intent=connect"),children:[e.jsx(fs,{className:"size-4"}),"Connect provider"]})]})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(ae,{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(Q,{variant:"secondary",onClick:()=>void U.refetch(),children:[e.jsx(Is,{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:Y.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:Y.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:Ie.length})]})]})]}),e.jsxs(ae,{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:()=>j(!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(L,{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(L,{className:"bg-white/[0.08] text-white/74",children:Y.workBlockTemplates.length})]}),e.jsxs("div",{className:"mt-3 grid gap-2",children:[Y.workBlockTemplates.slice(0,4).map(oe=>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:oe.title}),e.jsxs("div",{className:"mt-1 text-white/56",children:[Dd(oe.kind)," · ",oe.weekDays.length," day",oe.weekDays.length===1?"":"s"," · ",oe.blockingState]}),e.jsx("div",{className:"mt-1 text-white/46",children:$d(oe)}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(Q,{variant:"secondary",size:"sm",onClick:()=>{E(oe),w(!0)},children:[e.jsx(Ns,{className:"size-3.5"}),"Edit"]}),e.jsxs(Q,{variant:"secondary",size:"sm",onClick:()=>void Ne.mutateAsync(oe.id),children:[e.jsx(ct,{className:"size-3.5"}),"Delete"]})]})]},oe.id)),Y.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(Bv,{open:b,onOpenChange:oe=>{w(oe),oe||E(null)},pending:de.isPending||we.isPending,template:M,onSubmit:async oe=>{if(M){await we.mutateAsync({templateId:M.id,patch:oe});return}await de.mutateAsync(oe)}}),e.jsx(zv,{open:D,onOpenChange:j,tasks:s.snapshot.tasks,onSave:async({taskId:oe,schedulingRules:ke,plannedDurationSeconds:$e})=>{await Oa(oe,{schedulingRules:ke,plannedDurationSeconds:$e}),await s.refresh(),await ne(),await n.invalidateQueries({queryKey:["task-context",oe]})}}),e.jsx(qv,{open:S,onOpenChange:p,tasks:s.snapshot.tasks,from:Z.from,to:Z.to,onCreateTimebox:async oe=>{await H.mutateAsync(oe)}}),e.jsx(Fv,{open:A,onOpenChange:oe=>{T(oe),oe||($(null),J(null))},writableCalendars:te,linkOptions:Se,event:k,seed:z??void 0,onSubmit:async oe=>{if(k){const ke=k.id;T(!1),$(null),J(null),P.mutateAsync({eventId:ke,patch:oe}).catch(()=>{});return}else{T(!1),$(null),J(null),y.mutateAsync(oe).catch(()=>{});return}},pending:y.isPending||P.isPending}),e.jsx(_v,{open:g!==null,onOpenChange:oe=>{oe||C(null)},initialTitle:(g==null?void 0:g.title)??"",pending:P.isPending,onSubmit:async oe=>{if(!g)return;const ke=g.id;C(null),P.mutateAsync({eventId:ke,patch:{title:oe}}).catch(()=>{})}}),e.jsx(gm,{open:O!==null,title:(O==null?void 0:O.kind)==="event"?((kt=Y.events.find(oe=>oe.id===O.eventId))==null?void 0:kt.title)??"Event actions":(O==null?void 0:O.kind)==="work-block"?((Qt=Y.workBlockTemplates.find(oe=>oe.id===O.templateId))==null?void 0:Qt.title)??"Work block actions":(O==null?void 0:O.kind)==="day"?di(ee.find(oe=>oe.toISOString().slice(0,10)===O.dayKey)??x):"Calendar actions",subtitle:(O==null?void 0:O.kind)==="day"?"Choose what to create or paste into this day.":(O==null?void 0:O.kind)==="work-block"?"Edit or remove this recurring work block.":r?`Clipboard ready: ${r.label}`:"Quick calendar event actions.",items:yt,position:(O==null?void 0:O.position)??null,onClose:()=>_(null)})]})}function Od(t){return{id:t.id,type:"connector",position:t.position,data:{...t.data,nodeType:t.type}}}function Fd(t){return{id:t.id,source:t.source,target:t.target,sourceHandle:t.sourceHandle??void 0,targetHandle:t.targetHandle??void 0,label:t.label??void 0,animated:!1,style:{stroke:"rgba(194, 198, 255, 0.42)",strokeWidth:1.8}}}function Xv(t){return{id:t.id,type:t.data.nodeType,position:t.position,data:{label:t.data.label,description:t.data.description,boxId:t.data.boxId??null,prompt:t.data.prompt??"",systemPrompt:t.data.systemPrompt??"",outputKey:t.data.outputKey??"",enabledToolKeys:t.data.enabledToolKeys??[],modelConfig:t.data.modelConfig}}}function Vv(t){return{id:t.id,source:t.source,target:t.target,sourceHandle:t.sourceHandle??null,targetHandle:t.targetHandle??null,label:typeof t.label=="string"?t.label:null}}function Jv(t){switch(t){case"box_input":return{icon:e.jsx(ph,{className:"size-4"}),badge:"box",accent:"rgba(121, 196, 255, 0.7)"};case"chat":return{icon:e.jsx(cp,{className:"size-4"}),badge:"chat",accent:"rgba(117, 255, 201, 0.7)"};case"functor":return{icon:e.jsx(uh,{className:"size-4"}),badge:"functor",accent:"rgba(255, 210, 121, 0.72)"};case"output":return{icon:e.jsx(dp,{className:"size-4"}),badge:"output",accent:"rgba(213, 160, 255, 0.78)"};default:return{icon:e.jsx(op,{className:"size-4"}),badge:"input",accent:"rgba(255, 255, 255, 0.56)"}}}function Yv(t){var i;const s=Jv(t.data.nodeType);return e.jsxs("div",{className:"min-w-[240px] rounded-[22px] border border-white/10 bg-[#11172b]/95 p-4 shadow-[0_24px_80px_rgba(0,0,0,0.38)] backdrop-blur",style:{boxShadow:t.selected?`0 0 0 1px ${s.accent}, 0 24px 80px rgba(0,0,0,0.38)`:void 0},children:[t.data.nodeType!=="output"?e.jsx(zo,{type:"target",position:qo.Left,className:"!size-3 !border !border-white/90 !bg-[#9fb3ff]"}):null,e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[s.icon,e.jsx("div",{className:"text-sm font-semibold",children:t.data.label})]}),e.jsx("div",{className:"text-[12px] text-white/48",children:t.data.description})]}),e.jsx("div",{className:"rounded-full px-2.5 py-1 text-[10px] uppercase tracking-[0.18em] text-slate-950",style:{backgroundColor:s.accent},children:s.badge})]}),t.data.boxId?e.jsx("div",{className:"mt-3 rounded-full bg-white/[0.06] px-3 py-1.5 text-[11px] text-white/68",children:t.data.boxId}):null,t.data.prompt?e.jsx("div",{className:"mt-3 line-clamp-3 rounded-[16px] bg-white/[0.04] px-3 py-2 text-[12px] leading-5 text-white/72",children:t.data.prompt}):null,(i=t.data.enabledToolKeys)!=null&&i.length?e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:t.data.enabledToolKeys.map(a=>e.jsx("span",{className:"rounded-full bg-white/[0.06] px-2.5 py-1 text-[11px] text-white/68",children:a},a))}):null,t.data.nodeType!=="user_input"?e.jsx(zo,{type:"source",position:qo.Right,className:"!size-3 !border !border-white/90 !bg-[#9fb3ff]"}):null]})}const Zv={connector:Yv};function ew(t){return{x:80+t.length%3*280,y:80+Math.floor(t.length/3)*180}}function la(t,s,i,a={}){return{id:`node_${crypto.randomUUID().replaceAll("-","").slice(0,8)}`,type:"connector",position:ew(i),data:{nodeType:t,label:s,description:t==="box_input"?"Registered Forge box input.":t==="functor"?"Single transformation node.":t==="chat"?"Conversational connector node.":t==="output"?"Published connector output.":"Manual runtime input.",prompt:"",systemPrompt:"",outputKey:t==="output"?"primary":"",enabledToolKeys:[],modelConfig:{connectionId:null,provider:null,baseUrl:null,model:"",thinking:null,verbosity:null},...a}}}function tw({connector:t,boxes:s,modelConnections:i,onSave:a,onDelete:n,onRun:r,onChat:l,runs:o}){var C,F,z,J;const[c,x]=d.useState(t.title),[v,u]=d.useState(t.description),[f,h]=d.useState(t.kind),[m,b]=d.useState(()=>t.graph.nodes.map(Od)),[w,M]=d.useState(()=>t.graph.edges.map(Fd)),[E,D]=d.useState(null),[j,S]=d.useState(""),[p,A]=d.useState("");d.useEffect(()=>{x(t.title),u(t.description),h(t.kind),b(t.graph.nodes.map(Od)),M(t.graph.edges.map(Fd))},[t]);const T=d.useMemo(()=>m.find(O=>O.id===E)??null,[m,E]),k=d.useMemo(()=>{const O=j.trim().toLowerCase();return O?s.filter(_=>[_.label,_.description,_.category,_.routePath??"",_.surfaceId??""].join(" ").toLowerCase().includes(O)):s},[s,j]);function $(O){E&&b(_=>_.map(B=>B.id===E?O(B):B))}async function g(){await a({title:c,description:v,kind:f,graph:{nodes:m.map(Xv),edges:w.map(Vv)}})}return e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[280px_minmax(0,1fr)_340px]",children:[e.jsx("div",{className:"grid gap-4",children:e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-[0.16em] text-white/40",children:"Add nodes"}),e.jsxs("div",{className:"mt-3 grid gap-2",children:[e.jsx("input",{value:j,onChange:O=>S(O.target.value),placeholder:"Search boxes",className:"w-full rounded-[16px] border border-white/10 bg-black/20 px-3 py-2 text-sm text-white outline-none placeholder:text-white/28"}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Q,{type:"button",variant:"secondary",onClick:()=>b(O=>[...O,la("user_input","User input",O)]),children:"Add user input"}),e.jsx(Q,{type:"button",variant:"secondary",onClick:()=>b(O=>[...O,la("functor","Functor",O)]),children:"Add functor"}),e.jsx(Q,{type:"button",variant:"secondary",onClick:()=>b(O=>[...O,la("chat","Chat connector",O)]),children:"Add chat node"}),e.jsx(Q,{type:"button",variant:"secondary",onClick:()=>b(O=>[...O,la("output","Output",O)]),children:"Add output"})]}),e.jsx("div",{className:"mt-3 text-[12px] uppercase tracking-[0.16em] text-white/40",children:"Forge boxes"}),e.jsx("div",{className:"grid max-h-[28rem] gap-2 overflow-auto pr-1",children:k.map(O=>e.jsxs("button",{type:"button",className:"rounded-[18px] border border-white/8 bg-white/[0.04] px-3 py-3 text-left transition hover:bg-white/[0.07]",onClick:()=>b(_=>[..._,la("box_input",O.label,_,{description:O.description,boxId:O.boxId,enabledToolKeys:O.toolAdapters.map(B=>B.key)})]),children:[e.jsx("div",{className:"text-sm font-medium text-white",children:O.label}),e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/50",children:O.description}),e.jsx("div",{className:"mt-2 text-[11px] uppercase tracking-[0.14em] text-white/34",children:O.category})]},O.boxId))})]})]})}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{value:c,onChange:O=>x(O.target.value),className:"min-w-[16rem] flex-1 rounded-[16px] border border-white/10 bg-black/20 px-4 py-2.5 text-white outline-none placeholder:text-white/28"}),e.jsxs("select",{value:f,onChange:O=>h(O.target.value),className:"rounded-[16px] border border-white/10 bg-black/20 px-4 py-2.5 text-white outline-none",children:[e.jsx("option",{value:"functor",children:"Functor"}),e.jsx("option",{value:"chat",children:"Chat"})]}),e.jsx(Q,{type:"button",variant:"primary",onClick:()=>void g(),children:"Save connector"}),e.jsx(Q,{type:"button",variant:"secondary",onClick:()=>void n(),children:"Delete"})]}),e.jsx("textarea",{value:v,onChange:O=>u(O.target.value),rows:2,placeholder:"Connector description",className:"w-full rounded-[18px] border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none placeholder:text-white/28"}),e.jsx("div",{className:"h-[70vh] overflow-hidden rounded-[28px] border border-white/8 bg-[#0d1324]",children:e.jsxs(kl,{nodeTypes:Zv,nodes:m,edges:w,onNodesChange:O=>b(_=>lp(O,_)),onEdgesChange:O=>M(_=>rp(O,_)),onConnect:O=>M(_=>np({...O,id:`edge_${crypto.randomUUID().replaceAll("-","").slice(0,8)}`,style:{stroke:"rgba(194, 198, 255, 0.42)",strokeWidth:1.8}},_)),onNodeClick:(O,_)=>D(_.id),fitView:!0,className:"bg-transparent",children:[e.jsx(Sl,{color:"rgba(255,255,255,0.08)",gap:22}),e.jsx(ap,{pannable:!0,zoomable:!0,nodeColor:()=>"rgba(154, 168, 255, 0.55)",maskColor:"rgba(7,10,20,0.52)"}),e.jsx(Cl,{})]})})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-[0.16em] text-white/40",children:"Node inspector"}),T?e.jsxs("div",{className:"mt-3 grid gap-3",children:[e.jsx("input",{value:T.data.label,onChange:O=>$(_=>({..._,data:{..._.data,label:O.target.value}})),className:"w-full rounded-[16px] border border-white/10 bg-black/20 px-3 py-2 text-sm text-white outline-none"}),e.jsx("textarea",{rows:2,value:T.data.description,onChange:O=>$(_=>({..._,data:{..._.data,description:O.target.value}})),className:"w-full rounded-[16px] border border-white/10 bg-black/20 px-3 py-2 text-sm text-white outline-none"}),T.data.nodeType==="box_input"?e.jsxs(e.Fragment,{children:[e.jsxs("select",{value:T.data.boxId??"",onChange:O=>{const _=s.find(B=>B.boxId===O.target.value);$(B=>({...B,data:{...B.data,boxId:O.target.value,label:(_==null?void 0:_.label)??B.data.label,description:(_==null?void 0:_.description)??B.data.description,enabledToolKeys:(_==null?void 0:_.toolAdapters.map(K=>K.key))??[]}}))},className:"rounded-[16px] border border-white/10 bg-black/20 px-3 py-2 text-sm text-white outline-none",children:[e.jsx("option",{value:"",children:"Select Forge box"}),s.map(O=>e.jsx("option",{value:O.boxId,children:O.label},O.boxId))]}),T.data.boxId?e.jsx("div",{className:"rounded-[16px] bg-white/[0.04] p-3 text-[12px] leading-5 text-white/62",children:(((C=s.find(O=>O.boxId===T.data.boxId))==null?void 0:C.toolAdapters)??[]).map(O=>e.jsx("div",{children:O.key},O.key))}):null]}):null,T.data.nodeType==="functor"||T.data.nodeType==="chat"?e.jsxs(e.Fragment,{children:[e.jsx("textarea",{rows:5,value:T.data.prompt??"",onChange:O=>$(_=>({..._,data:{..._.data,prompt:O.target.value}})),placeholder:"Prompt",className:"w-full rounded-[16px] border border-white/10 bg-black/20 px-3 py-2 text-sm text-white outline-none"}),e.jsx("textarea",{rows:3,value:T.data.systemPrompt??"",onChange:O=>$(_=>({..._,data:{..._.data,systemPrompt:O.target.value}})),placeholder:"System prompt",className:"w-full rounded-[16px] border border-white/10 bg-black/20 px-3 py-2 text-sm text-white outline-none"}),e.jsxs("select",{value:((F=T.data.modelConfig)==null?void 0:F.connectionId)??"",onChange:O=>{const _=i.find(B=>B.id===O.target.value);$(B=>{var K,Z;return{...B,data:{...B.data,modelConfig:{connectionId:(_==null?void 0:_.id)??null,provider:(_==null?void 0:_.provider)??null,baseUrl:(_==null?void 0:_.baseUrl)??null,model:(_==null?void 0:_.model)??"",thinking:((K=B.data.modelConfig)==null?void 0:K.thinking)??null,verbosity:((Z=B.data.modelConfig)==null?void 0:Z.verbosity)??null}}}})},className:"rounded-[16px] border border-white/10 bg-black/20 px-3 py-2 text-sm text-white outline-none",children:[e.jsx("option",{value:"",children:"Select model connection"}),i.map(O=>e.jsx("option",{value:O.id,children:O.label},O.id))]}),e.jsx("input",{value:((z=T.data.modelConfig)==null?void 0:z.thinking)??"",onChange:O=>$(_=>{var B,K,Z,U,I;return{..._,data:{..._.data,modelConfig:{..._.data.modelConfig,connectionId:((B=_.data.modelConfig)==null?void 0:B.connectionId)??null,provider:((K=_.data.modelConfig)==null?void 0:K.provider)??null,baseUrl:((Z=_.data.modelConfig)==null?void 0:Z.baseUrl)??null,model:((U=_.data.modelConfig)==null?void 0:U.model)??"",thinking:O.target.value||null,verbosity:((I=_.data.modelConfig)==null?void 0:I.verbosity)??null}}}}),placeholder:"Thinking effort",className:"rounded-[16px] border border-white/10 bg-black/20 px-3 py-2 text-sm text-white outline-none"}),e.jsx("input",{value:((J=T.data.modelConfig)==null?void 0:J.verbosity)??"",onChange:O=>$(_=>{var B,K,Z,U,I;return{..._,data:{..._.data,modelConfig:{..._.data.modelConfig,connectionId:((B=_.data.modelConfig)==null?void 0:B.connectionId)??null,provider:((K=_.data.modelConfig)==null?void 0:K.provider)??null,baseUrl:((Z=_.data.modelConfig)==null?void 0:Z.baseUrl)??null,model:((U=_.data.modelConfig)==null?void 0:U.model)??"",thinking:((I=_.data.modelConfig)==null?void 0:I.thinking)??null,verbosity:O.target.value||null}}}}),placeholder:"Verbosity",className:"rounded-[16px] border border-white/10 bg-black/20 px-3 py-2 text-sm text-white outline-none"}),e.jsx("textarea",{rows:3,value:(T.data.enabledToolKeys??[]).join(", "),onChange:O=>$(_=>({..._,data:{..._.data,enabledToolKeys:O.target.value.split(",").map(B=>B.trim()).filter(Boolean)}})),placeholder:"Enabled tool keys, comma separated",className:"w-full rounded-[16px] border border-white/10 bg-black/20 px-3 py-2 text-sm text-white outline-none"})]}):null,T.data.nodeType==="output"?e.jsx("input",{value:T.data.outputKey??"",onChange:O=>$(_=>({..._,data:{..._.data,outputKey:O.target.value}})),placeholder:"Output key",className:"rounded-[16px] border border-white/10 bg-black/20 px-3 py-2 text-sm text-white outline-none"}):null]}):e.jsx("div",{className:"mt-3 text-sm text-white/56",children:"Select a node to edit its label, prompt, model, or box binding."})]}),e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-[0.16em] text-white/40",children:"Run connector"}),e.jsx("textarea",{rows:4,value:p,onChange:O=>A(O.target.value),placeholder:"User input for run or chat",className:"mt-3 w-full rounded-[16px] border border-white/10 bg-black/20 px-3 py-2 text-sm text-white outline-none"}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(Q,{type:"button",variant:"primary",onClick:()=>void r(p),children:"Run"}),e.jsx(Q,{type:"button",variant:"secondary",onClick:()=>void l(p),children:"Chat"})]}),e.jsx("div",{className:"mt-4 grid gap-3",children:o.slice(0,4).map(O=>{var _;return e.jsxs("div",{className:re("rounded-[18px] border p-3",O.status==="failed"?"border-rose-400/20 bg-rose-500/5":"border-white/8 bg-white/[0.04]"),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-[12px] text-white/50",children:[e.jsx("span",{children:O.mode}),e.jsx("span",{children:new Date(O.createdAt).toLocaleString()})]}),e.jsx("div",{className:"mt-2 text-sm text-white",children:((_=O.result)==null?void 0:_.primaryText)??O.error??"No output yet."})]},O.id)})})]})]})]})}function sw(){var u,f;const t=es(),s=ut(),i=We(),a=t.connectorId??"",n=fe({queryKey:["forge-ai-connector",a],queryFn:()=>Mf(a),enabled:a.length>0}),r=fe({queryKey:["forge-box-catalog"],queryFn:If}),l=fe({queryKey:["forge-settings"],queryFn:vi}),o=xe({mutationFn:h=>Af(a,h),onSuccess:()=>{i.invalidateQueries({queryKey:["forge-ai-connector",a]}),i.invalidateQueries({queryKey:["forge-ai-connectors"]})}}),c=xe({mutationFn:()=>Ef(a),onSuccess:()=>{i.invalidateQueries({queryKey:["forge-ai-connectors"]}),s("/connectors")}}),x=xe({mutationFn:h=>Lf(a,h),onSuccess:()=>{i.invalidateQueries({queryKey:["forge-ai-connector",a]})}}),v=xe({mutationFn:h=>Df(a,h),onSuccess:()=>{i.invalidateQueries({queryKey:["forge-ai-connector",a]})}});return n.isLoading||r.isLoading||l.isLoading?e.jsx(nt,{title:"Loading connector",description:"Preparing the connector graph editor."}):n.isError||r.isError||l.isError||!n.data?!n.data&&!n.isError&&!r.isError&&!l.isError?e.jsx(gt,{eyebrow:"Connectors",title:"Connector unavailable",description:"Forge could not find that connector."}):e.jsx(ze,{eyebrow:"Connectors",error:n.error??r.error??l.error??null}):e.jsx(tw,{connector:n.data.connector,boxes:((u=r.data)==null?void 0:u.boxes)??[],modelConnections:(((f=l.data)==null?void 0:f.settings.modelSettings.connections)??[]).map(h=>({id:h.id,label:h.label,provider:h.provider,model:h.model,baseUrl:h.baseUrl})),runs:n.data.runs,onSave:async h=>{await o.mutateAsync(h)},onDelete:async()=>{await c.mutateAsync()},onRun:async(h,m)=>{await x.mutateAsync({userInput:h,conversationId:m})},onChat:async(h,m)=>{await v.mutateAsync({userInput:h,conversationId:m})}})}function iw(){var o;const t=ut(),s=We(),[i]=Pt(),a=i.get("surface"),n=fe({queryKey:["forge-ai-connectors"],queryFn:Tf}),r=xe({mutationFn:c=>Pf({title:c==="chat"?"New chat connector":"New functor",description:c==="chat"?"Conversational connector graph.":"Single transformation connector graph.",kind:c,homeSurfaceId:a}),onSuccess:({connector:c})=>{s.invalidateQueries({queryKey:["forge-ai-connectors"]}),t(`/connectors/${c.id}`)}}),l=((o=n.data)==null?void 0:o.connectors)??[];return e.jsxs("div",{className:"grid gap-6",children:[e.jsx(qe,{title:"AI connectors",titleText:"AI connectors",description:"Global graph-based connectors that can pull from Forge boxes, run models, and publish outputs through the API.",badge:"graph runtime"}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(Q,{type:"button",variant:"primary",onClick:()=>void r.mutateAsync("functor"),children:"Create functor"}),e.jsx(Q,{type:"button",variant:"secondary",onClick:()=>void r.mutateAsync("chat"),children:"Create chat connector"})]}),e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:l.map(c=>e.jsxs("button",{type:"button",className:"rounded-[24px] border border-white/8 bg-white/[0.03] p-5 text-left transition hover:bg-white/[0.05]",onClick:()=>t(`/connectors/${c.id}`),children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-semibold text-white",children:c.title}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:c.description||"No description yet."})]}),e.jsx("div",{className:"rounded-full bg-white/[0.06] px-3 py-1 text-[11px] uppercase tracking-[0.16em] text-white/56",children:c.kind})]}),e.jsxs("div",{className:"mt-4 text-[12px] text-white/46",children:[c.graph.nodes.length," nodes · ",c.graph.edges.length," edges"]})]},c.id))})]})}const aw={spark:"Spark stage",story:"Story stage",state:"State stage",lens:"Lens stage",pivot:"Pivot stage"};function nw(t,s){return`${t}:${s}`}function is(t,s,i){return(t==null?void 0:t[nw(s,i)])??{count:0,latestNoteId:null,latestCreatedAt:null}}function jm(t){return`${t} Note${t===1?"":"s"}`}function zs(t){return t.replaceAll("_"," ")}function Na(t){if(!t)return null;const s=t.trim().toLowerCase(),i=aw[s];return i||s.split(/[_\-\s]+/).filter(Boolean).map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(" ")}function rw(t,s){const i=Na(s);return i?t==="trigger_report"?`This note is pinned to the ${i.toLowerCase()} of the report, so it stays attached to that part of the reflective chain.`:`This note is pinned to the "${i}" section of the ${zs(t)} instead of only the whole entity.`:null}function Xs(t,s){switch(t){case"goal":return`/goals/${s}`;case"project":return`/projects/${s}`;case"task":return`/tasks/${s}`;case"strategy":return`/strategies/${s}`;case"psyche_value":return`/psyche/values?focus=${s}#values-atlas`;case"behavior_pattern":return`/psyche/patterns?focus=${s}#pattern-lanes`;case"behavior":return`/psyche/behaviors?focus=${s}#behavior-columns`;case"belief_entry":return`/psyche/schemas-beliefs?focus=${s}`;case"mode_profile":return`/psyche/modes?focus=${s}`;case"trigger_report":return`/psyche/reports/${s}`;default:return null}}function Nm(t,s){switch(t){case"goal":case"project":case"task":case"strategy":case"trigger_report":{const i=Xs(t,s);return i?`${i}#notes`:null}default:return`/notes?entityType=${encodeURIComponent(t)}&entityId=${encodeURIComponent(s)}`}}function _d(t){return t.links.find(s=>Xs(s.entityType,s.entityId)!==null)??t.links[0]??null}function Ua(t,s){const i=[],a=/(!?\[\[([^\]]+)\]\]|\[([^\]]+)\]\(([^)]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|\*([^*]+)\*)/g;let n=0,r=null,l=0;for(;(r=a.exec(t))!==null;){if(r.index>n&&(i.push(e.jsx(d.Fragment,{children:t.slice(n,r.index)},`${s}-text-${l}`)),l+=1),r[1]&&r[2]){const o=r[2].trim(),c=r[1].startsWith("!"),x=o.indexOf("|"),v=x>=0?o.slice(0,x).trim():o,u=x>=0?o.slice(x+1).trim():v;if(v.toLowerCase().startsWith("forge:")){const[,f,h]=v.split(":"),m=f&&h?Xs(f,h):null,b=m?ui(m):null;i.push(b?e.jsxs("a",{href:b,className:"inline-flex items-center gap-1 rounded-full bg-amber-400/10 px-2 py-0.5 text-[0.9em] text-amber-100 transition hover:bg-amber-400/18",children:[e.jsx("span",{className:"text-[0.72em] uppercase tracking-[0.14em] text-amber-200/72",children:"Forge"}),e.jsx("span",{children:u})]},`${s}-forge-${l}`):e.jsx("span",{className:"inline-flex items-center gap-1 rounded-full bg-white/[0.06] px-2 py-0.5 text-[0.9em] text-white/66",children:u},`${s}-forge-${l}`))}else{const f=ui(`/wiki/page/${encodeURIComponent(v)}`);i.push(e.jsxs("a",{href:f,className:re("inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[0.9em] transition",c?"bg-cyan-400/14 text-cyan-50 hover:bg-cyan-400/22":"bg-white/[0.06] text-[var(--secondary)] hover:bg-white/[0.1]"),children:[c?e.jsx("span",{className:"text-[0.72em] uppercase tracking-[0.14em] text-cyan-100/68",children:"Embed"}):null,e.jsx("span",{children:u})]},`${s}-wiki-${l}`))}}else if(r[3]&&r[4]){const o=r[4].trim(),c=/^https?:\/\//i.test(o);i.push(e.jsx("a",{href:o,className:"text-[var(--secondary)] underline decoration-[rgba(125,211,252,0.4)] underline-offset-4 transition hover:text-white",target:c?"_blank":void 0,rel:c?"noreferrer":void 0,children:r[3]},`${s}-link-${l}`))}else r[5]?i.push(e.jsx("code",{className:"rounded bg-white/[0.08] px-1.5 py-0.5 text-[0.92em] text-white/90",children:r[5]},`${s}-code-${l}`)):r[6]?i.push(e.jsx("strong",{className:"font-semibold text-white",children:r[6]},`${s}-strong-${l}`)):r[7]&&i.push(e.jsx("em",{className:"italic text-white/88",children:r[7]},`${s}-em-${l}`));n=a.lastIndex,l+=1}return n<t.length&&i.push(e.jsx(d.Fragment,{children:t.slice(n)},`${s}-tail-${l}`)),i}function lw(t){const s=t.replace(/\r/g,"").split(`
|
|
2
|
-
`),i=[];let a=0;for(;a<s.length;){const n=s[a]??"",r=n.trim();if(!r){a+=1;continue}if(r.startsWith("```")){const c=[];for(a+=1;a<s.length&&!(s[a]??"").trim().startsWith("```");)c.push(s[a]??""),a+=1;a+=1,i.push(e.jsx("pre",{className:"overflow-x-auto rounded-[18px] bg-[rgba(6,10,18,0.88)] px-4 py-3 text-xs leading-6 text-white/86",children:e.jsx("code",{children:c.join(`
|
|
3
|
-
`)})},`code-${a}`));continue}const l=n.match(/^(#{1,6})\s+(.*)$/);if(l){const c=l[1].length,x=c===1?"text-xl":c===2?"text-lg":c===3?"text-base":"text-sm";i.push(e.jsx("div",{className:re("font-semibold text-white",x),children:Ua(l[2],`heading-${a}`)},`heading-${a}`)),a+=1;continue}if(/^>\s?/.test(n)){const c=[];for(;a<s.length&&/^>\s?/.test(s[a]??"");)c.push((s[a]??"").replace(/^>\s?/,"")),a+=1;i.push(e.jsx("blockquote",{className:"border-l-2 border-[var(--secondary)]/50 pl-4 text-sm leading-7 text-white/72",children:Ua(c.join(" "),`quote-${a}`)},`quote-${a}`));continue}if(/^[-*+]\s+/.test(n)||/^\d+\.\s+/.test(n)){const c=/^\d+\.\s+/.test(n),x=[];for(;a<s.length&&(/^[-*+]\s+/.test(s[a]??"")||/^\d+\.\s+/.test(s[a]??""));)x.push((s[a]??"").replace(/^[-*+]\s+/,"").replace(/^\d+\.\s+/,"")),a+=1;const v=c?"ol":"ul";i.push(e.jsx(v,{className:re("space-y-1 pl-5 text-sm leading-7 text-white/74",c?"list-decimal":"list-disc"),children:x.map((u,f)=>e.jsx("li",{children:Ua(u,`list-${a}-${f}`)},`item-${a}-${f}`))},`list-${a}`));continue}const o=[];for(;a<s.length;){const c=s[a]??"";if(!c.trim()||c.trim().startsWith("```")||/^#{1,6}\s+/.test(c)||/^>\s?/.test(c)||/^[-*+]\s+/.test(c)||/^\d+\.\s+/.test(c))break;o.push(c.trim()),a+=1}i.push(e.jsx("p",{className:"text-sm leading-7 text-white/72",children:Ua(o.join(" "),`paragraph-${a}`)},`paragraph-${a}`))}return i}function ms({markdown:t,className:s}){return e.jsx("div",{className:re("grid gap-3",s),children:lw(t)})}const Rd=[{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 Ut(t){const s=new Set;return t.map(i=>i.trim()).filter(Boolean).filter(i=>{const a=i.toLowerCase();return s.has(a)?!1:(s.add(a),!0)})}function Pn(t){const s=t.trim();if(!s)return null;const i=new Date(s);return Number.isNaN(i.getTime())?null:i.toISOString()}function km(t){if(!t)return"";const s=new Date(t);if(Number.isNaN(s.getTime()))return"";const i=s.getFullYear(),a=String(s.getMonth()+1).padStart(2,"0"),n=String(s.getDate()).padStart(2,"0"),r=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${i}-${a}-${n}T${r}:${l}`}function Sm(t,s){const i=Number(t);if(!Number.isFinite(i)||i<=0)return null;const a=s==="hours"?3600*1e3:1440*60*1e3;return new Date(Date.now()+i*a).toISOString()}function ow(t){const s=new Set(Rd.map(n=>n.value.toLowerCase())),i=Rd.map(n=>({value:n.value,label:n.label,description:n.description,searchText:`${n.label} ${n.description}`,badge:e.jsx(L,{className:"bg-cyan-400/10 text-cyan-50",children:n.label}),menuBadge:e.jsx(L,{className:"bg-cyan-400/10 text-cyan-50",children:n.label})})),a=Ut(t).filter(n=>!s.has(n.toLowerCase())).map(n=>({value:n,label:n,description:"Custom note tag",searchText:n,badge:e.jsx(L,{className:"bg-white/[0.08] text-white/78",children:n}),menuBadge:e.jsx(L,{className:"bg-white/[0.08] text-white/78",children:n})}));return[...i,...a]}function ci({value:t,onChange:s,availableTags:i=[],placeholder:a="Add a memory tag or create a custom tag"}){const n=ow([...i,...t]);return e.jsx(et,{options:n,selectedValues:Ut(t),onChange:r=>s(Ut(r)),placeholder:a,emptyMessage:"No note tags yet.",createLabel:"Add custom tag",onCreate:async r=>{const l=r.trim();return{value:l,label:l,description:"Custom note tag",searchText:l,badge:e.jsx(L,{className:"bg-white/[0.08] text-white/78",children:l}),menuBadge:e.jsx(L,{className:"bg-white/[0.08] text-white/78",children:l})}}})}function dw(t,s,i){return t.links.filter(a=>!(a.entityType===s&&a.entityId===i))}function cw(t,s){return t.entityType===s.entityType&&t.entityId===s.entityId&&(t.anchorKey??null)===(s.anchorKey??null)}function wr(t){const s=new Set;return t.filter(i=>{const a=`${i.entityType}:${i.entityId}:${i.anchorKey??""}`;return s.has(a)?!1:(s.add(a),!0)})}function zd(t,s,i){return Pn(t)??Sm(s,i)}function Zn({entityType:t,entityId:s,anchorKey:i,includeAnchorlessWhenAnchored:a=!1,title:n="Notes",description:r="Markdown notes linked to this entity stay searchable, editable, and visible alongside the work.",invalidateQueryKeys:l=[],compact:o=!1}){var yt,wt,kt,Qt,oe,ke,$e,Ye;const c=Je(),x=We(),[v,u]=d.useState(""),[f,h]=d.useState(!1),[m,b]=d.useState(""),[w,M]=d.useState(!1),[E,D]=d.useState({entityType:"goal",entityId:""}),[j,S]=d.useState([]),[p,A]=d.useState([]),[T,k]=d.useState(""),[$,g]=d.useState(""),[C,F]=d.useState("days"),[z,J]=d.useState(null),[O,_]=d.useState(""),[B,K]=d.useState(!1),[Z,U]=d.useState([]),[I,G]=d.useState({entityType:"goal",entityId:""}),[W,ne]=d.useState([]),[de,we]=d.useState(""),[Ne,H]=d.useState(""),[me,y]=d.useState("days"),P=Na(i),q=rw(t,i),pe=fe({queryKey:["notes",t,s],queryFn:()=>Oh({linkedEntityType:t,linkedEntityId:s,limit:100})}),ee=fe({queryKey:["forge-psyche-values"],queryFn:ps}),Y=fe({queryKey:["forge-psyche-patterns"],queryFn:Vs}),R=fe({queryKey:["forge-psyche-behaviors"],queryFn:xs}),X=fe({queryKey:["forge-psyche-beliefs"],queryFn:As}),be=fe({queryKey:["forge-psyche-modes"],queryFn:Es}),Ie=fe({queryKey:["forge-psyche-reports"],queryFn:bi}),te=d.useMemo(()=>{var Pe,ve,Ee,Oe,tt,Qe,St;return{goal:c.snapshot.goals.map(Le=>({id:Le.id,label:st(Le.title,Le.user)})),project:c.snapshot.dashboard.projects.map(Le=>({id:Le.id,label:st(Le.title,Le.user)})),task:c.snapshot.tasks.map(Le=>({id:Le.id,label:st(Le.title,Le.user)})),strategy:c.snapshot.strategies.map(Le=>({id:Le.id,label:st(Le.title,Le.user)})),habit:c.snapshot.habits.map(Le=>({id:Le.id,label:st(Le.title,Le.user)})),tag:c.snapshot.tags.map(Le=>({id:Le.id,label:st(Le.name,Le.user)})),note:(((Pe=pe.data)==null?void 0:Pe.notes)??[]).map(Le=>({id:Le.id,label:Le.contentPlain||Le.contentMarkdown})),insight:[],psyche_value:(((ve=ee.data)==null?void 0:ve.values)??[]).map(Le=>({id:Le.id,label:st(Le.title,Le.user)})),behavior_pattern:(((Ee=Y.data)==null?void 0:Ee.patterns)??[]).map(Le=>({id:Le.id,label:st(Le.title,Le.user)})),behavior:(((Oe=R.data)==null?void 0:Oe.behaviors)??[]).map(Le=>({id:Le.id,label:st(Le.title,Le.user)})),belief_entry:(((tt=X.data)==null?void 0:tt.beliefs)??[]).map(Le=>({id:Le.id,label:st(Le.statement,Le.user)})),mode_profile:(((Qe=be.data)==null?void 0:Qe.modes)??[]).map(Le=>({id:Le.id,label:st(Le.title,Le.user)})),mode_guide_session:[],event_type:[],emotion_definition:[],trigger_report:(((St=Ie.data)==null?void 0:St.reports)??[]).map(Le=>({id:Le.id,label:st(Le.title,Le.user)})),calendar_event:[],work_block_template:[],task_timebox:[]}},[(yt=R.data)==null?void 0:yt.behaviors,(wt=X.data)==null?void 0:wt.beliefs,(kt=be.data)==null?void 0:kt.modes,(Qt=pe.data)==null?void 0:Qt.notes,(oe=Y.data)==null?void 0:oe.patterns,(ke=Ie.data)==null?void 0:ke.reports,c.snapshot.dashboard.projects,c.snapshot.goals,c.snapshot.habits,c.snapshot.strategies,c.snapshot.tags,c.snapshot.tasks,($e=ee.data)==null?void 0:$e.values]),ce=async()=>{await Promise.all([x.invalidateQueries({queryKey:["notes",t,s]}),x.invalidateQueries({queryKey:["forge-snapshot"]}),...l.map(Pe=>x.invalidateQueries({queryKey:Pe}))])},Se=xe({mutationFn:async Pe=>$a({contentMarkdown:Pe,tags:Ut(p),destroyAt:zd(T,$,C),links:wr([{entityType:t,entityId:s,anchorKey:i??null},...j])}),onSuccess:async()=>{b(""),M(!1),S([]),D({entityType:"goal",entityId:""}),A([]),k(""),g(""),F("days"),await ce()}}),he=xe({mutationFn:async({noteId:Pe,contentMarkdown:ve,links:Ee,tags:Oe,destroyAt:tt})=>Ta(Pe,{contentMarkdown:ve,links:Ee,tags:Oe,destroyAt:tt}),onSuccess:async()=>{J(null),_(""),K(!1),U([]),G({entityType:"goal",entityId:""}),ne([]),we(""),H(""),y("days"),await ce()}}),Ge=xe({mutationFn:async Pe=>Bl(Pe),onSuccess:ce}),De=d.useMemo(()=>{var ve;return(((ve=pe.data)==null?void 0:ve.notes)??[]).filter(Ee=>i===void 0?!0:Ee.links.some(Oe=>Oe.entityType===t&&Oe.entityId===s&&((Oe.anchorKey??null)===i||a&&(Oe.anchorKey??null)===null))).filter(Ee=>{const Oe=v.trim().toLowerCase();return Oe?`${Ee.contentPlain} ${Ee.author??""} ${(Ee.tags??[]).join(" ")}`.toLowerCase().includes(Oe):!0})},[i,s,t,a,(Ye=pe.data)==null?void 0:Ye.notes,v]),ue=(Pe,ve,Ee)=>{const Oe=Pe.entityId.trim();return Oe?(ve(wr([...Ee,{entityType:Pe.entityType,entityId:Oe,anchorKey:null}])),!0):!1},Fe=Pe=>{var Ee,Oe;const ve=(Ee=te[Pe.entityType])==null?void 0:Ee.find(tt=>tt.id===Pe.entityId);return(Oe=ve==null?void 0:ve.label)!=null&&Oe.trim()?ve.label.trim():`Deleted ${zs(Pe.entityType)}`},dt=(Pe,ve,Ee,Oe,tt)=>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(L,{className:"bg-white/[0.08] text-white/68",children:[Pe.length," linked"]})]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:Pe.map(Qe=>{const St=Pe.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:[zs(Qe.entityType)," · ",Fe(Qe)]}),Qe.anchorKey?e.jsx("span",{className:"rounded-full bg-white/[0.08] px-2 py-0.5 text-[11px] text-white/54",children:Na(Qe.anchorKey)}):null,e.jsx("button",{type:"button",disabled:!St,className:"text-white/44 transition hover:text-white disabled:cursor-not-allowed disabled:opacity-30",onClick:()=>ve(Pe.filter(Le=>!cw(Le,Qe))),"aria-label":`Remove ${zs(Qe.entityType)} link to ${Fe(Qe)}`,children:e.jsx(ct,{className:"size-3.5"})})]},`${tt}-${Qe.entityType}-${Qe.entityId}-${Qe.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:Ee.entityType,onChange:Qe=>Oe({...Ee,entityType:Qe.target.value,entityId:""}),children:["goal","project","task","strategy","habit","tag","note","psyche_value","behavior_pattern","behavior","belief_entry","mode_profile","mode_guide_session","event_type","emotion_definition","trigger_report"].map(Qe=>e.jsx("option",{value:Qe,children:zs(Qe)},Qe))}),e.jsxs("select",{className:"min-w-0 rounded-[14px] bg-white/[0.06] px-3 py-3 text-white",value:Ee.entityId,onChange:Qe=>Oe({...Ee,entityId:Qe.target.value}),children:[e.jsx("option",{value:"",children:(te[Ee.entityType]??[]).length>0?"Choose linked item":"No linked items available"}),(te[Ee.entityType]??[]).map(Qe=>e.jsx("option",{value:Qe.id,children:Qe.label},Qe.id))]}),e.jsx(Q,{variant:"secondary",disabled:!Ee.entityId,onClick:()=>{ue(Ee,ve,Pe)&&Oe({...Ee,entityId:""})},children:"Add link"})]})]});return e.jsx(ae,{id:"notes",className:o?"min-w-0 overflow-hidden p-0":"min-w-0 overflow-hidden",children:e.jsxs("div",{className:o?"p-4":void 0,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:n}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:r}),P?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 ",P]}),q?e.jsx(it,{content:q,label:`Explain ${P}`}):null]}):null]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:jm(De.length)}),f?null:e.jsxs(Q,{type:"button",size:"sm",onClick:()=>h(!0),children:[e.jsx(zt,{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(bt,{className:"size-4 text-white/34"}),e.jsx(le,{value:v,onChange:Pe=>u(Pe.target.value),placeholder:"Search notes by content, author, or note tag",className:"border-0 bg-transparent px-0 py-0"})]}),f?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(zt,{className:"size-4 text-[var(--secondary)]"}),"Add note"]}),e.jsxs(Q,{type:"button",variant:"secondary",size:"sm",className:"gap-2",onClick:()=>M(Pe=>!Pe),children:[e.jsx(Bo,{className:"size-4"}),w?"Back to editor":"Preview"]})]}),e.jsx("div",{className:"mt-3",children:w?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:m.trim()?e.jsx(ms,{markdown:m}):e.jsx("div",{className:"text-sm leading-6 text-white/42",children:"Markdown preview appears here once you have note content."})})]}):e.jsx(Me,{value:m,onChange:Pe=>b(Pe.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:dt(wr([{entityType:t,entityId:s,anchorKey:i??null},...j]),Pe=>S(Pe.filter(ve=>!(ve.entityType===t&&ve.entityId===s&&(ve.anchorKey??null)===(i??null)))),E,D,"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(ci,{value:p,onChange:A}),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(le,{type:"datetime-local",value:T,onChange:Pe=>k(Pe.target.value)}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_10rem]",children:[e.jsx(le,{type:"number",min:"1",value:$,onChange:Pe=>g(Pe.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:C,onChange:Pe=>F(Pe.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(Q,{type:"button",variant:"secondary",onClick:()=>{h(!1),M(!1),b(""),S([]),D({entityType:"goal",entityId:""}),A([]),k(""),g(""),F("days")},children:"Cancel"}),e.jsx(Q,{pending:Se.isPending,pendingLabel:"Saving",disabled:m.trim().length===0,onClick:async()=>{await Se.mutateAsync(m.trim()),h(!1)},children:"Save note"})]})]}):null,e.jsxs("div",{className:"mt-4 grid gap-3",children:[pe.isLoading?e.jsx("div",{className:"rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/56",children:"Loading notes…"}):null,!pe.isLoading&&De.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,De.map(Pe=>{const ve=z===Pe.id,Ee=dw(Pe,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:[(Pe.author??"Unknown author").toString()," •"," ",new Date(Pe.updatedAt).toLocaleString()]}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[Ee.map(Oe=>e.jsxs(L,{className:"bg-white/[0.08] text-white/68",wrap:!0,children:[zs(Oe.entityType)," ·"," ",Fe(Oe),Oe.anchorKey?` · ${Na(Oe.anchorKey)}`:""]},`${Pe.id}-${Oe.entityType}-${Oe.entityId}-${Oe.anchorKey??""}`)),(Pe.tags??[]).map(Oe=>e.jsx(L,{className:"bg-cyan-400/10 text-cyan-50",wrap:!0,children:Oe},`${Pe.id}-tag-${Oe}`)),Pe.destroyAt?e.jsxs(L,{className:"bg-amber-400/10 text-amber-100",wrap:!0,children:["Ephemeral · deletes"," ",new Date(Pe.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:()=>{J(Pe.id),_(Pe.contentMarkdown),K(!1),U(Pe.links),G({entityType:"goal",entityId:""}),ne(Ut(Pe.tags??[])),we(km(Pe.destroyAt??null)),H(""),y("days")},children:e.jsx(mi,{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:()=>{Ge.mutateAsync(Pe.id)},children:e.jsx(ct,{className:"size-4"})})]})]}),ve?e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"flex flex-wrap items-center justify-end gap-2",children:e.jsxs(Q,{type:"button",variant:"secondary",size:"sm",className:"gap-2",onClick:()=>K(Oe=>!Oe),children:[e.jsx(Bo,{className:"size-4"}),B?"Back to editor":"Preview"]})}),e.jsx("div",{className:"mt-3",children:B?e.jsxs("div",{className:"rounded-[20px] bg-[rgba(9,14,25,0.78)] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Preview"}),e.jsx("div",{className:"mt-3",children:O.trim()?e.jsx(ms,{markdown:O}):e.jsx("div",{className:"text-sm text-white/42",children:"No content yet."})})]}):e.jsx(Me,{value:O,onChange:Oe=>_(Oe.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(ci,{value:W,onChange:ne}),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(le,{type:"datetime-local",value:de,onChange:Oe=>we(Oe.target.value)}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_10rem]",children:[e.jsx(le,{type:"number",min:"1",value:Ne,onChange:Oe=>H(Oe.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:me,onChange:Oe=>y(Oe.target.value),children:[e.jsx("option",{value:"hours",children:"Hours"}),e.jsx("option",{value:"days",children:"Days"})]})]})]})]}),e.jsx("div",{className:"mt-3",children:dt(Z,U,I,G,`edit-note-links-${Pe.id}`)}),e.jsxs("div",{className:"mt-3 flex flex-wrap justify-end gap-2",children:[e.jsx(Q,{variant:"secondary",onClick:()=>{J(null),K(!1),ne([]),we(""),H(""),y("days")},children:"Cancel"}),e.jsx(Q,{pending:he.isPending,pendingLabel:"Saving",disabled:O.trim().length===0||Z.length===0,onClick:async()=>{await he.mutateAsync({noteId:Pe.id,contentMarkdown:O.trim(),links:Z,tags:Ut(W),destroyAt:zd(de,Ne,me)})},children:"Save changes"})]})]}):e.jsx("div",{className:"mt-4",children:e.jsx(ms,{markdown:Pe.contentMarkdown})})]},Pe.id)})]})]})})}function er({userId:t,domain:s,entityType:i,entityId:a,label:n,description:r,tags:l,size:o="sm"}){const c=ut(),x=We(),v=xe({mutationFn:async()=>{if(!t)throw new Error("Select a single owner before sending entities to Preferences.");return Vr({userId:t,domain:s,entityType:i,entityId:a,label:n,description:r,tags:l})},onSuccess:async({item:u})=>{await x.invalidateQueries({queryKey:["forge-preferences"]}),c(`/preferences?userId=${encodeURIComponent(t??"")}&domain=${encodeURIComponent(s)}&focusItem=${encodeURIComponent(u.id)}`)}});return e.jsxs(Q,{variant:"secondary",size:o,disabled:!t,pending:v.isPending,pendingLabel:"Sending to Preferences",onClick:()=>void v.mutateAsync(),title:t?"Add this entity to the Preferences compare queue.":"Select a single user scope before sending entities to Preferences.",children:[e.jsx(xh,{className:"size-4"}),"Send to Preferences"]})}const qd={active:"Active",paused:"Suspended",completed:"Finished",all:"All"};function Zl({value:t,counts:s,onChange:i,className:a}){return e.jsx("div",{className:re("flex flex-wrap gap-2",a),children:Object.keys(qd).map(n=>{const r=n===t;return e.jsxs("button",{type:"button",onClick:()=>i(n),className:re("inline-flex min-h-10 items-center gap-2 rounded-full border px-4 py-2 text-sm transition",r?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.16)] text-white shadow-[0_16px_36px_rgba(8,12,24,0.18)]":"border-white/8 bg-white/[0.04] text-white/62 hover:bg-white/[0.08] hover:text-white"),children:[e.jsx("span",{children:qd[n]}),e.jsx("span",{className:re("rounded-full px-2 py-0.5 text-[11px]",r?"bg-white/12 text-white/88":"bg-white/8 text-white/54"),children:s[n]})]},n)})})}function us({value:t,className:s,tone:i="primary"}){const a=`${Math.max(4,Math.min(100,t))}%`,n=i==="secondary"?"from-[var(--secondary)] to-[rgba(78,222,163,0.45)]":i==="tertiary"?"from-[var(--tertiary)] to-[rgba(255,185,95,0.45)]":"from-[var(--primary)] to-[rgba(192,193,255,0.45)]";return e.jsx("div",{className:re("h-1.5 rounded-full bg-white/[0.08]",s),children:e.jsx("div",{className:re("h-full rounded-full bg-gradient-to-r",n),style:{width:a}})})}function Cm(t){const s=`${t.title} ${t.description} ${t.source??""}`.toLowerCase();return s.includes("playwright")||s.includes("operator console")||s.includes("retroactive work logging")}function tr(t){return Cm(t)?"Work log added":t.title}function sr(t){return Cm(t)?"This entry was added later so the work history stays complete and accurate.":t.description}function eo(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 to(t,s){return s==="all"?t:t.filter(i=>i.status===s)}function hw(){const{t}=lt(),s=Je(),i=es(),a=ut(),n=We(),[r,l]=d.useState(!1),[o,c]=d.useState(!1),[x,v]=d.useState("active"),u=Mt(s.selectedUserIds),[f,h]=d.useState(null),m=xe({mutationFn:()=>Cb(i.goalId),onSuccess:async()=>{await Promise.all([n.invalidateQueries({queryKey:["forge-snapshot"]}),n.invalidateQueries({queryKey:["project-board"]}),n.invalidateQueries({queryKey:["task-context"]})]),a("/goals")}}),b=s.snapshot.dashboard.goals.find(g=>g.id===i.goalId)??null,w=d.useMemo(()=>s.snapshot.dashboard.projects.filter(g=>g.goalId===i.goalId),[i.goalId,s.snapshot.dashboard.projects]),M=d.useMemo(()=>eo(w),[w]),E=d.useMemo(()=>to(w,x),[w,x]),D=new Set(w.map(g=>g.id)),j=new Set(s.snapshot.tasks.filter(g=>D.has(g.projectId??"")).map(g=>g.id)),S=s.snapshot.activity.filter(g=>g.entityId===i.goalId||D.has(g.entityId)||j.has(g.entityId)||g.entityType==="task_run"&&typeof g.metadata.taskId=="string"&&j.has(g.metadata.taskId));if(!b)return e.jsx(gt,{eyebrow:t("common.goalDetail.eyebrow"),title:t("common.goalDetail.missingTitle"),description:t("common.goalDetail.missingDescription"),action:e.jsx(Ae,{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 p=E.find(g=>g.nextTaskTitle)??E[0]??null,A=s.snapshot.overview.neglectedGoals.find(g=>g.goalId===b.id)??null,T=S[0]??null,k=async g=>{h(g);try{await s.patchProject(g,{status:"active"})}finally{h(null)}},$=async()=>{window.confirm(t("common.goalDetail.deleteGoalConfirm",{title:b.title}))&&await m.mutateAsync()};return e.jsxs("div",{className:"grid min-w-0 gap-5",children:[e.jsx(qe,{entityKind:"goal",title:e.jsx(Xe,{kind:"goal",label:b.title,variant:"heading",size:"lg"}),titleText:b.title,description:b.description?e.jsx(ms,{markdown:b.description,className:"[&>p]:text-[13px] [&>p]:leading-6 [&>blockquote]:text-[13px] [&>ul]:text-[13px] [&>ol]:text-[13px]"}):"No strategic description yet.",badge:t(E.length===1?"common.goalDetail.heroBadgeOne":"common.goalDetail.heroBadgeOther",{count:E.length}),actions:e.jsx(er,{userId:u,domain:"projects",entityType:"goal",entityId:b.id,label:b.title,description:b.description})}),b.user?e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-white/62",children:[e.jsx("span",{className:"text-white/42",children:"Owned by"}),e.jsx(Ue,{user:b.user})]}):null,e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(Q,{onClick:()=>l(!0),children:t("common.goalDetail.edit")}),e.jsx(Q,{variant:"secondary",onClick:()=>c(!0),children:t("common.goalDetail.addProject")}),e.jsx(Q,{variant:"ghost",className:"text-rose-200 hover:bg-rose-500/10",pending:m.isPending,pendingLabel:t("common.goalDetail.deleting"),onClick:()=>void $(),children:t("common.goalDetail.deleteGoal")})]}),e.jsxs("section",{className:"grid min-w-0 gap-5 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]",children:[e.jsxs(ae,{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(Zl,{value:x,counts:M,onChange:v,className:"justify-end"})]}),E.length===0?e.jsx("div",{className:"mt-4 rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/58",children:x==="active"?t("common.goalDetail.noProjects"):"No projects match this lifecycle filter yet. Switch filters or restart one to make it active again."}):e.jsx("div",{className:"mt-4 grid gap-4 lg:grid-cols-2",children:E.map(g=>e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-5 transition hover:bg-white/[0.08]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Te,{kind:"project",compact:!0,gradient:!1}),g.user?e.jsx(Ue,{user:g.user,compact:!0}):null]}),e.jsx(L,{children:g.status})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Ae,{to:`/projects/${g.id}`,className:"transition hover:opacity-90",children:e.jsx(Xe,{kind:"project",label:g.title,variant:"heading",size:"lg"})})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:g.description}),e.jsx("div",{className:"mt-4",children:e.jsx(us,{value:g.progress})}),e.jsx("div",{className:"mt-4 text-[11px] uppercase tracking-[0.16em] text-white/40",children:g.nextTaskTitle?t("common.goalDetail.nextMove",{value:g.nextTaskTitle}):t("common.goalDetail.addNextTask")}),e.jsxs("div",{className:"mt-4 flex flex-wrap justify-between gap-3",children:[e.jsx(Ae,{to:`/projects/${g.id}`,children:e.jsx(Q,{variant:"ghost",children:"Open project"})}),x!=="active"&&g.status!=="active"?e.jsx(Q,{variant:"secondary",size:"sm",pending:f===g.id,pendingLabel:"Restarting…",onClick:()=>void k(g.id),children:"Restart"}):null]})]},g.id))})]}),e.jsx("div",{className:"grid min-w-0 gap-5",children:e.jsxs(ae,{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(Te,{kind:"goal",compact:!0,gradient:!1}),e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:t("common.goalDetail.progressTitle",{progress:b.progress,count:b.completedTasks})}),e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:t("common.goalDetail.progressDetail",{xp:b.earnedPoints})}),e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:t(E.length===1?"common.goalDetail.heroBadgeOne":"common.goalDetail.heroBadgeOther",{count:E.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:[b.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:b.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:b.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")}),p?e.jsx(Te,{kind:"project",compact:!0,gradient:!1}):null]}),e.jsx("div",{className:"mt-2 font-medium text-white",children:(p==null?void 0:p.title)??t("common.goalDetail.noProject")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:p!=null&&p.nextTaskTitle?t("common.goalDetail.nextMove",{value:p.nextTaskTitle}):(p==null?void 0:p.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:(A==null?void 0:A.title)??t("common.goalDetail.noRisk")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(A==null?void 0:A.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:(T==null?void 0:T.title)??t("common.goalDetail.noEvidence")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(T==null?void 0:T.description)||t("common.goalDetail.noEvidenceDetail")})]})]})]})]})})]}),e.jsx(Zn,{entityType:"goal",entityId:b.id,title:"Goal notes",description:"Use notes to capture strategy changes, meaning shifts, and progress context that belongs at the goal level."}),e.jsxs(ae,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.goalDetail.sectionEvidence")}),S.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:S.slice(0,6).map(g=>e.jsxs(Ae,{to:Gs(g)??`/activity?eventId=${g.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:tr(g)}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:sr(g)})]},g.id))})]}),e.jsx(Gl,{open:r,editingGoal:b,tags:s.snapshot.tags,users:s.snapshot.users,defaultUserId:b.userId??u,onOpenChange:l,onSubmit:async(g,C)=>{C&&await s.patchGoal(C,g)}}),e.jsx(Xl,{open:o,goals:s.snapshot.goals,users:s.snapshot.users,editingProject:null,initialGoalId:b.id,defaultUserId:b.userId??u,onOpenChange:c,onSubmit:async g=>{await s.createProject(g)}})]})}function Vt({entityType:t,entityId:s,count:i,className:a=""}){const n=ut(),r=Nm(t,s);return r?e.jsxs("span",{role:"link",tabIndex:0,className:`inline-flex min-h-10 items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-3 py-2 text-xs text-white/72 transition hover:bg-white/[0.09] hover:text-white ${a}`,onClick:l=>{l.stopPropagation(),n(r)},onKeyDown:l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),l.stopPropagation(),n(r))},children:[e.jsx(Ki,{className:"size-3.5"}),jm(i)]}):null}function mw({goals:t,tags:s,users:i,defaultUserId:a=null,pending:n=!1,onCreate:r,onUpdate:l}){const[o,c]=d.useState(!1),[x,v]=d.useState(null),u=t.find(f=>f.id===x)??null;return e.jsxs(e.Fragment,{children:[e.jsxs(ae,{children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Goal arcs"}),e.jsx("h3",{className:"mt-2 font-display text-3xl text-white",children:"Strategic arcs before tickets"}),e.jsx("p",{className:"mt-3 max-w-3xl text-sm leading-7 text-white/60",children:"This is the long-horizon map. Each arc shows why it matters, how much ground has been covered, and which project should move next."})]}),e.jsx(Q,{onClick:()=>{v(null),c(!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(f=>{const h=`${Math.max(6,Math.min(100,f.progress))}%`;return e.jsxs(Ae,{to:`/goals/${f.id}`,className:"rounded-[24px] border border-white/6 bg-[linear-gradient(180deg,rgba(255,255,255,0.06),rgba(255,255,255,0.03))] p-4 transition hover:bg-[linear-gradient(180deg,rgba(255,255,255,0.09),rgba(255,255,255,0.04))]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx(Te,{kind:"goal",compact:!0,gradient:!1}),e.jsx("div",{className:"mt-2",children:e.jsx(Xe,{kind:"goal",label:f.title,variant:"heading",size:"lg",showKind:!1,lines:2})}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/58",children:f.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(),v(f.id),c(!0)},children:e.jsx(Ns,{className:"size-4"})})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(L,{className:"bg-white/[0.08] text-white/70",children:f.horizon}),e.jsx(L,{className:f.status==="active"?"text-emerald-300":f.status==="paused"?"text-amber-300":"text-[var(--tertiary)]",children:f.status}),e.jsxs(L,{className:"bg-white/[0.08] text-white/70",children:[f.earnedPoints," / ",f.targetPoints," xp"]}),e.jsxs(L,{className:"bg-white/[0.08] text-white/70",children:[f.totalTasks," tasks"]})]}),e.jsx("div",{className:"mt-4 h-1.5 rounded-full bg-white/[0.08]",children:e.jsx("div",{className:"h-full rounded-full bg-[linear-gradient(90deg,var(--primary)_0%,var(--secondary)_100%)]",style:{width:h}})}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:f.tags.map(m=>e.jsx(L,{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",{className:"min-w-0 flex-1 truncate",children:f.momentumLabel}),e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-2",style:{color:f.themeColor},children:["Open arc",e.jsx(Gt,{className:"size-3.5"})]})]})]},f.id)})]})]}),e.jsx(Gl,{open:o,pending:n,editingGoal:u,tags:s,users:i,defaultUserId:a,onOpenChange:f=>{c(f),f||v(null)},onSubmit:async(f,h)=>{if(h){await l(h,f);return}await r(f)}})]})}function uw(){const t=Je(),[s,i]=d.useState("active"),[a,n]=d.useState(null),r=t.snapshot.dashboard.goals.length>0,l=eo(t.snapshot.dashboard.projects),o=to(t.snapshot.dashboard.projects,s),c=Mt(t.selectedUserIds),x=new Map(t.snapshot.dashboard.goals.map(u=>[u.id,o.filter(f=>f.goalId===u.id)])),v=async u=>{n(u);try{await t.patchProject(u,{status:"active"})}finally{n(null)}};return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{entityKind:"goal",title:e.jsx(Xe,{kind:"goal",label:"Life Goals",variant:"heading",size:"lg"}),titleText:"Life Goals",description:"Life goals are the destinations you care about over the long run. Each one can hold several projects, and those projects turn direction into real work.",badge:`${t.snapshot.dashboard.goals.length} active goals`,actions:r?e.jsxs("div",{className:"inline-flex min-h-10 items-center rounded-full border border-white/8 bg-white/[0.04] px-4 py-2 text-sm whitespace-nowrap text-white/68",children:[t.snapshot.dashboard.projects.length," live project",t.snapshot.dashboard.projects.length===1?"":"s"," ","attached"]}):null}),e.jsx(mw,{goals:t.snapshot.dashboard.goals,tags:t.snapshot.tags,users:t.snapshot.users,defaultUserId:c,onCreate:t.createGoal,onUpdate:t.patchGoal}),r?e.jsx(Zl,{value:s,counts:l,onChange:i}):null,r?null:e.jsx(gt,{eyebrow:"Life goals",title:"No life goals yet",description:"Define the first long-horizon direction above so Forge can attach projects, tasks, momentum, and evidence to something meaningful."}),r?e.jsx("div",{className:"grid gap-4",children:t.snapshot.dashboard.goals.map(u=>{const f=x.get(u.id)??[],h=is(t.snapshot.dashboard.notesSummaryByEntity,"goal",u.id);return e.jsx(Ae,{to:`/goals/${u.id}`,className:"min-w-0 overflow-hidden rounded-[28px] border border-white/6 bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.03))] p-4 transition hover:bg-[linear-gradient(180deg,rgba(255,255,255,0.08),rgba(255,255,255,0.04))] sm:p-5",children:e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)] xl:gap-5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[u.tags.slice(0,3).map(m=>e.jsx(L,{className:"bg-white/[0.08]",style:{color:m.color},children:m.name},m.id)),e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:u.horizon}),e.jsx(Ue,{user:u.user,compact:!0})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Xe,{kind:"goal",label:u.title,variant:"heading",size:"xl",lines:2})}),e.jsx("p",{className:"mt-3 max-w-2xl text-sm leading-7 text-white/58",children:u.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:[u.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:[u.completedTasks,"/",Math.max(u.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:u.earnedPoints})]})]}),e.jsx("div",{className:"mt-4",children:e.jsx(us,{value:u.progress})}),e.jsx("div",{className:"mt-4",children:e.jsx(Vt,{entityType:"goal",entityId:u.id,count:h.count})})]}),e.jsxs("div",{className:"min-w-0 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:"min-w-0 flex-1 text-sm font-medium text-white sm:text-base",children:"Projects carrying this direction"}),e.jsx("div",{className:"shrink-0 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(m=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.05] px-4 py-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(Te,{kind:"project",compact:!0,gradient:!1}),e.jsx(Xe,{kind:"project",label:m.title,className:"min-w-0",showIcon:!1,lines:2})]}),e.jsx(L,{className:"shrink-0",children:m.status})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:m.description}),e.jsxs("div",{className:"mt-3 text-sm text-white/42",children:["Next move:"," ",m.nextTaskTitle??"Define the first attached task"]}),s!=="active"&&m.status!=="active"?e.jsx("div",{className:"mt-4 flex justify-end",children:e.jsx(Q,{variant:"secondary",size:"sm",pending:a===m.id,pendingLabel:"Restarting…",onClick:b=>{b.preventDefault(),b.stopPropagation(),v(m.id)},children:"Restart"})}):null]},m.id))})]})]})},u.id)})}):e.jsx(ae,{children:e.jsx("div",{className:"rounded-[20px] bg-white/[0.04] p-4 text-sm text-white/58",children:"Goal cards will appear here once the first long-horizon direction is created."})})]})}function pw(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function ta(t){d.useEffect(()=>{if(!t||typeof document>"u")return;const s=window.requestAnimationFrame(()=>{const i=document.querySelector(`[data-psyche-focus-id="${pw(t)}"]`);i&&i.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"})});return()=>window.cancelAnimationFrame(s)},[t])}function sa(t){return t?"border-[rgba(125,211,252,0.28)] bg-[linear-gradient(180deg,rgba(125,211,252,0.14),rgba(255,255,255,0.06))] shadow-[0_24px_60px_rgba(56,189,248,0.14)]":""}const yr={title:"",description:"",status:"active",userId:null,polarity:"positive",frequency:"daily",targetCount:1,weekDays:[],linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],linkedValueIds:[],linkedPatternIds:[],linkedBehaviorIds:[],linkedBeliefIds:[],linkedModeIds:[],linkedReportIds:[],linkedBehaviorId:"",rewardXp:12,penaltyXp:8,generatedHealthEventTemplate:{enabled:!1,workoutType:"workout",title:"",durationMinutes:45,xpReward:0,tags:[],links:[],notesTemplate:""}},xw=[{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 gw(t){return{title:t.title,description:t.description,status:t.status,userId:t.userId??null,polarity:t.polarity,frequency:t.frequency,targetCount:t.targetCount,weekDays:t.weekDays,linkedGoalIds:t.linkedGoalIds,linkedProjectIds:t.linkedProjectIds,linkedTaskIds:t.linkedTaskIds,linkedValueIds:t.linkedValueIds,linkedPatternIds:t.linkedPatternIds,linkedBehaviorIds:t.linkedBehaviorIds,linkedBeliefIds:t.linkedBeliefIds,linkedModeIds:t.linkedModeIds,linkedReportIds:t.linkedReportIds,linkedBehaviorId:t.linkedBehaviorId??"",rewardXp:t.rewardXp,penaltyXp:t.penaltyXp,generatedHealthEventTemplate:t.generatedHealthEventTemplate}}function fw({open:t,pending:s=!1,editingHabit:i,values:a,patterns:n,behaviors:r,beliefs:l,modes:o,reports:c,goals:x,projects:v,tasks:u,users:f,defaultUserId:h=null,onOpenChange:m,onSubmit:b}){const[w,M]=d.useState(yr),[E,D]=d.useState(null),[j,S]=d.useState({});d.useEffect(()=>{t&&(M(i?gw(i):{...yr,userId:h}),D(null),S({}))},[h,i,t]);const p=f.find(g=>g.id===h)??null,A=d.useMemo(()=>r.slice().sort((g,C)=>g.title.localeCompare(C.title)),[r]),T=g=>({linkedBehaviorIds:g,linkedBehaviorId:g[0]??""}),k=(g,C)=>g.includes(C)?g.filter(F=>F!==C):[...g,C],$=[{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:(g,C)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Title",error:j.title??null,children:e.jsx(le,{value:g.title,onChange:F=>C({title:F.target.value}),placeholder:"Train lower body"})}),e.jsx(se,{label:"Description",children:e.jsx(Me,{value:g.description,onChange:F=>C({description:F.target.value}),placeholder:"Write the habit description in Markdown. Define what counts, edge cases, and examples."})}),e.jsx(ss,{value:g.userId,users:f,onChange:F=>C({userId:F}),label:"Owner user",defaultLabel:ts(p),help:"Habits can be owned by humans or bots. When one scoped user is active, Forge uses that as the default."})]})},{id:"shape",eyebrow:"Shape",title:"Set direction and cadence",description:"Forge uses polarity to decide whether doing the habit is good or bad, and cadence to know when it should show up.",render:(g,C)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Polarity",children:e.jsx(Ze,{value:g.polarity,onChange:F=>C({polarity:F}),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(se,{label:"Frequency",children:e.jsx(Ze,{value:g.frequency,onChange:F=>C({frequency:F}),options:[{value:"daily",label:"Daily",description:"Track against each day."},{value:"weekly",label:"Weekly",description:"Track only on the selected weekdays."}],columns:2})}),g.frequency==="weekly"?e.jsx(se,{label:"Weekdays",error:j.weekDays??null,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:xw.map(F=>{const z=g.weekDays.includes(F.value);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${z?"bg-white/16 text-white":"bg-white/6 text-white/58 hover:bg-white/10 hover:text-white"}`,onClick:()=>C({weekDays:z?g.weekDays.filter(J=>J!==F.value):[...g.weekDays,F.value].sort()}),children:F.label},F.value)})})}):null,e.jsx(se,{label:"Status",children:e.jsx(Ze,{value:g.status,onChange:F=>C({status:F}),options:[{value:"active",label:"Active",description:"Show it in the daily operating flow."},{value:"paused",label:"Paused",description:"Keep it visible but not currently due."},{value:"archived",label:"Archived",description:"Keep the record but retire it from active work."}]})})]})},{id:"generation",eyebrow:"Generation",title:"Decide whether this habit should create a workout record",description:"Use this when a completed habit should generate a structured sports or recovery session in Forge, then reconcile with HealthKit later if the same session gets imported.",render:(g,C)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Generate workout record",children:e.jsx(Ze,{value:g.generatedHealthEventTemplate.enabled?"enabled":"disabled",onChange:F=>C({generatedHealthEventTemplate:{...g.generatedHealthEventTemplate,enabled:F==="enabled"}}),options:[{value:"disabled",label:"Disabled",description:"This habit only affects the habit ledger."},{value:"enabled",label:"Enabled",description:"A completed check-in creates a workout or recovery session."}],columns:2})}),g.generatedHealthEventTemplate.enabled?e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Workout type",children:e.jsx(le,{value:g.generatedHealthEventTemplate.workoutType,onChange:F=>C({generatedHealthEventTemplate:{...g.generatedHealthEventTemplate,workoutType:F.target.value}}),placeholder:"mobility, walk, strength, recovery"})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(se,{label:"Duration (minutes)",children:e.jsx(le,{type:"number",min:1,max:1440,value:g.generatedHealthEventTemplate.durationMinutes,onChange:F=>C({generatedHealthEventTemplate:{...g.generatedHealthEventTemplate,durationMinutes:Number(F.target.value)||45}})})}),e.jsx(se,{label:"Workout XP",children:e.jsx(le,{type:"number",min:0,max:500,value:g.generatedHealthEventTemplate.xpReward,onChange:F=>C({generatedHealthEventTemplate:{...g.generatedHealthEventTemplate,xpReward:Number(F.target.value)||0}})})})]}),e.jsx(se,{label:"Generated session note",children:e.jsx(Me,{value:g.generatedHealthEventTemplate.notesTemplate,onChange:F=>C({generatedHealthEventTemplate:{...g.generatedHealthEventTemplate,notesTemplate:F.target.value}}),placeholder:"Morning routine session generated from habit completion."})})]}):null]})},{id:"links",eyebrow:"Links",title:"Connect the habit to real Forge work",description:"Link habits to the goals, projects, and tasks they support so they stay anchored in the same operating graph as everything else.",render:(g,C)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Goals",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:x.map(F=>{const z=g.linkedGoalIds.includes(F.id);return e.jsx("button",{type:"button",onClick:()=>C({linkedGoalIds:k(g.linkedGoalIds,F.id)}),children:e.jsx(Te,{kind:"goal",label:F.title,gradient:z,className:z?"":"opacity-75"})},F.id)})})}),e.jsx(se,{label:"Projects",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:v.map(F=>{const z=g.linkedProjectIds.includes(F.id);return e.jsx("button",{type:"button",onClick:()=>C({linkedProjectIds:k(g.linkedProjectIds,F.id)}),children:e.jsx(Te,{kind:"project",label:F.title,gradient:z,className:z?"":"opacity-75"})},F.id)})})}),e.jsx(se,{label:"Tasks",children:e.jsx("div",{className:"flex max-h-48 flex-wrap gap-2 overflow-y-auto",children:u.map(F=>{const z=g.linkedTaskIds.includes(F.id);return e.jsx("button",{type:"button",onClick:()=>C({linkedTaskIds:k(g.linkedTaskIds,F.id)}),children:e.jsx(Te,{kind:"task",label:F.title,gradient:z,className:z?"":"opacity-75",wrap:!0})},F.id)})})}),e.jsx(se,{label:"Values",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map(F=>{const z=g.linkedValueIds.includes(F.id);return e.jsx("button",{type:"button",onClick:()=>C({linkedValueIds:k(g.linkedValueIds,F.id)}),children:e.jsx(Te,{kind:"value",label:F.title,gradient:z,className:z?"":"opacity-75"})},F.id)})})}),e.jsx(se,{label:"Patterns",children:e.jsx("div",{className:"flex max-h-44 flex-wrap gap-2 overflow-y-auto",children:n.map(F=>{const z=g.linkedPatternIds.includes(F.id);return e.jsx("button",{type:"button",onClick:()=>C({linkedPatternIds:k(g.linkedPatternIds,F.id)}),children:e.jsx(Te,{kind:"pattern",label:F.title,gradient:z,className:z?"":"opacity-75",wrap:!0})},F.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:(g,C)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Linked behavior",children:e.jsx("div",{className:"flex max-h-44 flex-wrap gap-2 overflow-y-auto",children:A.map(F=>{const z=g.linkedBehaviorIds.includes(F.id);return e.jsx("button",{type:"button",onClick:()=>C(T(k(g.linkedBehaviorIds,F.id))),children:e.jsx(Te,{kind:"behavior",label:F.title,gradient:z,className:z?"":"opacity-75",wrap:!0})},F.id)})})}),e.jsx(se,{label:"Beliefs",children:e.jsx("div",{className:"flex max-h-44 flex-wrap gap-2 overflow-y-auto",children:l.map(F=>{const z=g.linkedBeliefIds.includes(F.id);return e.jsx("button",{type:"button",onClick:()=>C({linkedBeliefIds:k(g.linkedBeliefIds,F.id)}),children:e.jsx(Te,{kind:"belief",label:F.statement,gradient:z,className:z?"":"opacity-75",wrap:!0})},F.id)})})}),e.jsx(se,{label:"Modes",children:e.jsx("div",{className:"flex max-h-44 flex-wrap gap-2 overflow-y-auto",children:o.map(F=>{const z=g.linkedModeIds.includes(F.id);return e.jsx("button",{type:"button",onClick:()=>C({linkedModeIds:k(g.linkedModeIds,F.id)}),children:e.jsx(Te,{kind:"mode",label:F.title,gradient:z,className:z?"":"opacity-75",wrap:!0})},F.id)})})}),e.jsx(se,{label:"Reports",children:e.jsx("div",{className:"flex max-h-44 flex-wrap gap-2 overflow-y-auto",children:c.map(F=>{const z=g.linkedReportIds.includes(F.id);return e.jsx("button",{type:"button",onClick:()=>C({linkedReportIds:k(g.linkedReportIds,F.id)}),children:e.jsx(Te,{kind:"report",label:F.title,gradient:z,className:z?"":"opacity-75",wrap:!0})},F.id)})})}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[e.jsx(se,{label:"Target count",error:j.targetCount??null,children:e.jsx(le,{type:"number",value:g.targetCount,onChange:F=>C({targetCount:Number(F.target.value)||1})})}),e.jsx(se,{label:"Reward XP",error:j.rewardXp??null,children:e.jsx(le,{type:"number",value:g.rewardXp,onChange:F=>C({rewardXp:Number(F.target.value)||1})})}),e.jsx(se,{label:"Penalty XP",error:j.penaltyXp??null,children:e.jsx(le,{type:"number",value:g.penaltyXp,onChange:F=>C({penaltyXp:Number(F.target.value)||1})})})]})]})}];return e.jsx(rt,{open:t,onOpenChange:m,eyebrow:"Habit",title:i?"Edit habit":"Create habit",description:"Habits are recurring commitments or recurring slips with explicit XP consequences.",value:w,onChange:M,steps:$,pending:s,pendingLabel:i?"Save habit":"Create habit",submitLabel:i?"Save habit":"Create habit",error:E,onSubmit:async()=>{D(null);const g=iv.safeParse(w);if(!g.success){S(Object.fromEntries(Object.entries(g.error.flatten().fieldErrors).map(([C,F])=>[C,F==null?void 0:F[0]]))),D("Some habit fields still need attention.");return}S({});try{await b(g.data,i==null?void 0:i.id),M(yr),m(!1)}catch(C){D(C instanceof Error?C.message:"Habit update failed.")}}})}const bw=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],vw=["S","M","T","W","T","F","S"];function ww(t){return t.frequency==="daily"?`${t.targetCount}x daily`:`${t.targetCount}x weekly · ${t.weekDays.map(s=>bw[s]).join(", ")}`}function ba(t){return t.toISOString().slice(0,10)}function Im(t){const[s,i,a]=t.split("-").map(Number);return new Date(Date.UTC(s,i-1,a))}function Tm(t){return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()))}function Qa(t,s){const i=new Date(t);return i.setUTCDate(i.getUTCDate()+s),i}function Bd(t){const s=Tm(t),i=(s.getUTCDay()+6)%7;return s.setUTCDate(s.getUTCDate()-i),s}function oa(t){const s=typeof t=="string"?Im(t):t;return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",timeZone:"UTC"}).format(s)}function il(t,s){return t.polarity==="positive"&&s==="done"||t.polarity==="negative"&&s==="missed"}function al(t,s){return t.polarity==="positive"?s==="done"?"Done":"Missed":s==="done"?"Performed":"Resisted"}function Pm(t){const s=ba(new Date),i=t.checkIns.find(a=>a.dateKey===s)??null;return t.dueToday?{tone:"pending",label:t.frequency==="daily"?"Waiting for today":"Awaiting this week's check-in",cardClass:"border-amber-300/24 shadow-[0_0_0_1px_rgba(251,191,36,0.12)]",overlayClass:"bg-[radial-gradient(circle_at_top_right,rgba(251,191,36,0.18),transparent_44%)]",pillClass:"border border-amber-300/16 bg-amber-300/12 text-amber-100"}:i?il(t,i.status)?{tone:"aligned",label:`${al(t,i.status)} today`,cardClass:"border-emerald-300/20 shadow-[0_0_0_1px_rgba(52,211,153,0.08)]",overlayClass:"bg-[radial-gradient(circle_at_top_right,rgba(52,211,153,0.16),transparent_44%)]",pillClass:"border border-emerald-300/16 bg-emerald-300/12 text-emerald-100"}:{tone:"unaligned",label:`${al(t,i.status)} today`,cardClass:"border-rose-300/20 shadow-[0_0_0_1px_rgba(251,113,133,0.08)]",overlayClass:"bg-[radial-gradient(circle_at_top_right,rgba(251,113,133,0.16),transparent_44%)]",pillClass:"border border-rose-300/16 bg-rose-300/12 text-rose-100"}:t.polarity==="positive"?{tone:"neutral",label:"No update due right now",cardClass:"",overlayClass:"bg-[radial-gradient(circle_at_top_right,rgba(52,211,153,0.09),transparent_40%)]",pillClass:"border border-white/10 bg-white/[0.06] text-white/62"}:{tone:"neutral",label:"No update due right now",cardClass:"",overlayClass:"bg-[radial-gradient(circle_at_top_right,rgba(251,113,133,0.09),transparent_40%)]",pillClass:"border border-white/10 bg-white/[0.06] text-white/62"}}function yw(t){return t>=10?{Icon:hp,className:"border border-amber-300/20 bg-amber-300/10 text-amber-100 shadow-[0_16px_32px_rgba(251,191,36,0.14)]",iconClass:"text-amber-200",valueClass:"text-amber-50",label:"Celebration pace"}:t>=5?{Icon:mp,className:"border border-emerald-300/20 bg-emerald-300/10 text-emerald-100 shadow-[0_16px_32px_rgba(52,211,153,0.12)]",iconClass:"text-emerald-200",valueClass:"text-emerald-50",label:"Locked in"}:t>=1?{Icon:up,className:"border border-sky-300/18 bg-sky-300/10 text-sky-100 shadow-[0_16px_32px_rgba(125,211,252,0.1)]",iconClass:"text-sky-200",valueClass:"text-sky-50",label:"Building rhythm"}:{Icon:pp,className:"border border-white/10 bg-white/[0.04] text-white/72 shadow-[0_16px_32px_rgba(15,23,42,0.16)]",iconClass:"text-white/55",valueClass:"text-white",label:"Cold start"}}function jw(t){return t>=80?"bg-emerald-400/12 text-emerald-100":t>=50?"bg-amber-300/12 text-amber-100":"bg-rose-400/12 text-rose-100"}function Nw(t){var r;const s=new Date;if(t.frequency==="daily"){const l=Tm(s),o=[];for(let c=-6;c<=0;c+=1){const x=Qa(l,c),v=ba(x),u=t.checkIns.find(m=>m.dateKey===v)??null,f=vw[x.getUTCDay()],h=c===0;o.push({id:v,label:f,current:h,actionDateKey:v,actionLabel:oa(x),state:u?il(t,u.status)?"aligned":"unaligned":"unknown",title:`${oa(x)} · ${u?al(t,u.status):"Not informed"}`})}return{caption:"7-day rhythm",rangeLabel:"Past 7 days",showLabels:!0,startLabel:"",endLabel:"",cells:o}}const i=Bd(s),a=new Map;for(const l of t.checkIns){const o=ba(Bd(Im(l.dateKey))),c=a.get(o)??[];c.push(l),a.set(o,c)}const n=[];for(let l=-6;l<=0;l+=1){const o=Qa(i,l*7),c=ba(o),x=a.get(c)??[],v=t.weekDays.length>0?[...t.weekDays].sort((b,w)=>w-b)[0]:0,u=ba(Qa(o,v)),f=((r=x[0])==null?void 0:r.dateKey)??u,h=x.filter(b=>il(t,b.status)).length,m=x.length-h;n.push({id:c,label:"",current:l===0,actionDateKey:f,actionLabel:`Week of ${oa(o)}`,state:x.length===0?"unknown":h>=m?"aligned":"unaligned",title:`${oa(o)} week · ${x.length===0?"Not informed":h>=m?"Mostly aligned":"Mostly off track"}`})}return{caption:"7-week rhythm",rangeLabel:"Past 7 weeks",showLabels:!1,startLabel:oa(Qa(i,-42)),endLabel:"This week",cells:n}}function kw(t,s){return re("h-8 w-full rounded-[10px] border transition",t==="aligned"&&"border-emerald-300/20 bg-emerald-300/75 shadow-[0_8px_18px_rgba(52,211,153,0.18)]",t==="unaligned"&&"border-rose-300/20 bg-rose-300/75 shadow-[0_8px_18px_rgba(251,113,133,0.18)]",t==="unknown"&&"border-white/8 bg-white/[0.08]",s&&"shadow-[0_0_0_1px_rgba(255,255,255,0.16)]")}function Sw({habit:t,onSelectCell:s}){const i=Nw(t),a=Pm(t);return e.jsxs("div",{className:"w-full rounded-[18px] border border-white/8 bg-black/10 px-3 py-2.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"shrink-0",children:[e.jsx("div",{className:"font-label text-[10px] uppercase tracking-[0.16em] text-white/34",children:i.caption}),e.jsx("div",{className:"text-[11px] text-white/46",children:i.rangeLabel})]}),e.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:i.cells.map(n=>e.jsxs("button",{type:"button",className:"group flex min-w-0 flex-1 items-center gap-1 rounded-[10px] transition hover:bg-white/[0.04]",onClick:()=>s(t,n),title:`Log check-in for ${n.actionLabel}`,"aria-label":`Log check-in for ${n.actionLabel}`,children:[e.jsx("div",{className:re(kw(n.state,n.current),"h-6 min-w-0 flex-1 rounded-[8px] transition duration-150 group-hover:-translate-y-0.5 group-hover:shadow-[0_10px_22px_rgba(15,23,42,0.22)]")}),i.showLabels?e.jsx("span",{className:"hidden text-[9px] uppercase tracking-[0.14em] text-white/26 transition group-hover:text-white/48 sm:inline",children:n.label}):null]},n.id))}),e.jsx("div",{className:re("shrink-0 rounded-full px-2.5 py-1 text-[10px] font-medium",a.pillClass),children:a.label})]}),i.showLabels?null:e.jsxs("div",{className:"mt-1 text-right text-[10px] uppercase tracking-[0.14em] text-white/26",children:[i.startLabel," - ",i.endLabel]})]})}function Cw(t){return t.polarity==="positive"?{alignedLabel:"Done",alignedDescription:"Log that the intended habit happened.",unalignedLabel:"Missed",unalignedDescription:"Log that the habit did not happen."}:{alignedLabel:"Resisted",alignedDescription:"Log that the unwanted behavior was resisted.",unalignedLabel:"Performed",unalignedDescription:"Log that the unwanted behavior happened."}}function Iw(){var B,K,Z,U,I,G;const t=Je(),s=We(),[i,a]=Pt(),[n,r]=d.useState(null),[l,o]=d.useState(null),[c,x]=d.useState(null),[v,u]=d.useState(""),[f,h]=d.useState(!1),[m,b]=d.useState(null),[w,M]=d.useState(null),E=i.get("focus"),D=Zh(t.selectedUserIds),j=Mt(D),S=["forge-habits",...D];ta(E);const p=fe({queryKey:S,queryFn:async()=>(await cf({userIds:D})).habits}),A=fe({queryKey:["forge-psyche-overview",...D],queryFn:async()=>(await Wn(D)).overview});d.useEffect(()=>{i.get("create")==="1"&&(r(null),h(!0),a(W=>{const ne=new URLSearchParams(W);return ne.delete("create"),ne},{replace:!0}))},[i,a]);const T=async()=>{await s.invalidateQueries({queryKey:["forge-habits"]}),await t.refresh()},k=xe({mutationFn:async({input:W,habitId:ne})=>ne?(await mf(ne,W)).habit:(await hf(W)).habit,onSuccess:async()=>{M(null),await T()},onError:W=>{M(W instanceof Error?W.message:"Habit save failed.")}}),$=xe({mutationFn:async({habitId:W,status:ne,dateKey:de,note:we})=>pf(W,{status:ne,dateKey:de,note:we}),onSuccess:async()=>{M(null),await T()},onError:W=>{M(W instanceof Error?W.message:"Habit check-in failed.")}}),g=xe({mutationFn:async W=>uf(W),onMutate:async W=>{await s.cancelQueries({queryKey:S});const ne=s.getQueryData(S);return s.setQueryData(S,de=>(de==null?void 0:de.filter(we=>we.id!==W))??[]),{previousHabits:ne}},onSuccess:async()=>{M(null),b(null),await T()},onError:(W,ne,de)=>{de!=null&&de.previousHabits&&s.setQueryData(S,de.previousHabits),M(W instanceof Error?W.message:"Habit delete failed.")}}),C=d.useMemo(()=>(p.data??[]).filter(W=>W.status!=="archived"),[p.data]),F=d.useMemo(()=>C.filter(W=>W.dueToday),[C]),z=d.useMemo(()=>[...C].sort((W,ne)=>W.dueToday!==ne.dueToday?Number(ne.dueToday)-Number(W.dueToday):W.dueToday&&ne.dueToday?new Date(W.lastCheckInAt??0).getTime()-new Date(ne.lastCheckInAt??0).getTime():W.title.localeCompare(ne.title)),[C]),J=d.useMemo(()=>l?l.habit.checkIns.find(W=>W.dateKey===l.cell.actionDateKey)??null:null,[l]);if(d.useEffect(()=>{if(!l){x(null),u("");return}x((J==null?void 0:J.status)??null),u((J==null?void 0:J.note)??"")},[l,J]),p.error)throw p.error;const O=l?Cw(l.habit):null,_=c==="done"||c==="missed"||J!==null;return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{entityKind:"habit",title:e.jsx(Xe,{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:`${C.length} habits`,actions:e.jsxs(Q,{onClick:()=>{r(null),h(!0)},children:[e.jsx(Tt,{className:"size-4"}),"New habit"]})}),w?e.jsx(ae,{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(gh,{className:"mt-0.5 size-4 shrink-0"}),e.jsx("div",{children:w})]})}):null,e.jsxs("section",{className:"grid gap-4 lg:grid-cols-3",children:[e.jsxs(ae,{className:"border-amber-300/16 shadow-[0_0_0_1px_rgba(251,191,36,0.08)]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Due today"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-[var(--primary)]",children:F.length}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Habits that still need a check-in today."})]}),e.jsxs(ae,{className:"border-emerald-300/16 shadow-[0_0_0_1px_rgba(52,211,153,0.08)]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Best streak"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-emerald-50",children:Math.max(0,...C.map(W=>W.streakCount))}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Longest current aligned streak across active habits."})]}),e.jsxs(ae,{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:[C.length>0?Math.round(C.reduce((W,ne)=>W+ne.completionRate,0)/C.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(ae,{children:"Loading habits..."}):C.length===0?e.jsx(gt,{eyebrow:"Habits",title:"No recurring habits yet",description:"Create the recurring commitments or recurring slips you want Forge to track explicitly. Positive habits pay out when completed. Negative habits invert that logic.",action:e.jsx(Q,{onClick:()=>{r(null),h(!0)},children:"Create habit"})}):e.jsx("div",{className:"grid gap-4 xl:grid-cols-2",children:z.map(W=>{const ne=Pm(W),de=yw(W.streakCount),we=de.Icon,Ne=is(t.snapshot.dashboard.notesSummaryByEntity,"habit",W.id).count,H=W.polarity==="positive"?{label:"Done",status:"done",Icon:Ia,className:"border-emerald-300/18 bg-emerald-300/14 text-emerald-50 shadow-[0_14px_28px_rgba(52,211,153,0.14)] hover:bg-emerald-300/20"}:{label:"Resisted",status:"missed",Icon:ya,className:"border-emerald-300/18 bg-emerald-300/14 text-emerald-50 shadow-[0_14px_28px_rgba(52,211,153,0.14)] hover:bg-emerald-300/20"},me=W.polarity==="positive"?{label:"Missed",status:"missed",Icon:Ko,className:"border-rose-300/18 bg-rose-300/14 text-rose-50 shadow-[0_14px_28px_rgba(251,113,133,0.14)] hover:bg-rose-300/20"}:{label:"Performed",status:"done",Icon:Il,className:"border-rose-300/18 bg-rose-300/14 text-rose-50 shadow-[0_14px_28px_rgba(251,113,133,0.14)] hover:bg-rose-300/20"};return e.jsxs(ae,{className:re("relative flex h-full flex-col overflow-hidden",ne.cardClass,sa(E===W.id)),"data-psyche-focus-id":W.id,children:[e.jsx("div",{className:re("pointer-events-none absolute inset-0 opacity-100",ne.overlayClass)}),e.jsxs("div",{className:"relative z-10 flex h-full flex-col",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Xe,{kind:"habit",label:W.title,variant:"heading",size:"sm"}),e.jsx(Ue,{user:W.user,compact:!0}),e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:W.status}),e.jsxs(L,{className:"bg-white/[0.08] text-white/72",children:[e.jsx(Xt,{className:"mr-1 size-3.5"}),ww(W)]}),e.jsx(L,{className:W.polarity==="positive"?"bg-emerald-400/12 text-emerald-200":"bg-rose-400/12 text-rose-200",children:W.polarity==="positive"?"Positive":"Negative"}),W.dueToday?e.jsx(L,{className:"bg-amber-300/12 text-amber-100",children:"Needs check-in"}):null,W.linkedGoalIds.slice(0,1).map(y=>{const P=t.snapshot.goals.find(q=>q.id===y);return P?e.jsxs(L,{className:"bg-amber-400/12 text-amber-100",children:["Goal · ",P.title]},P.id):null}),W.linkedProjectIds.slice(0,1).map(y=>{const P=t.snapshot.dashboard.projects.find(q=>q.id===y);return P?e.jsxs(L,{className:"bg-sky-400/12 text-sky-100",children:["Project · ",P.title]},P.id):null}),W.linkedTaskIds.slice(0,1).map(y=>{const P=t.snapshot.tasks.find(q=>q.id===y);return P?e.jsxs(L,{className:"bg-indigo-400/12 text-indigo-100",children:["Task · ",P.title]},P.id):null})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:W.description?e.jsx(ms,{markdown:W.description,className:"[&>p]:text-sm [&>p]:leading-6 [&>blockquote]:text-sm [&>ul]:text-sm [&>ol]:text-sm"}):"No extra notes yet."})]}),e.jsxs("div",{className:"ml-auto inline-flex shrink-0 flex-col items-end gap-2 self-start text-right",children:[e.jsxs("div",{className:re("inline-flex flex-col self-end rounded-[20px] px-3 py-2.5 text-right",de.className),children:[e.jsxs("div",{className:"flex items-center justify-end gap-1.5 text-[10px] uppercase tracking-[0.16em]",children:[e.jsx("span",{children:"Streak"}),e.jsx(we,{className:re("size-3.5 shrink-0",de.iconClass)})]}),e.jsx("div",{className:re("mt-1.5 font-display text-[2.75rem] leading-none",de.valueClass),children:W.streakCount}),e.jsx("div",{className:"mt-1 text-[11px] leading-tight text-white/68",children:de.label})]}),e.jsxs("div",{className:"ml-auto grid grid-cols-2 gap-1.5",children:[e.jsx(Q,{variant:"ghost",size:"sm",className:"h-7 min-w-0 rounded-[11px] border border-white/8 bg-white/[0.04] px-3 text-white/72 hover:bg-white/[0.08] hover:text-white",disabled:k.isPending,onClick:()=>{r(W),h(!0)},"aria-label":`Edit ${W.title}`,title:"Edit habit",children:e.jsx(mi,{className:"size-4"})}),e.jsx(Q,{variant:"ghost",size:"sm",className:"h-7 min-w-0 rounded-[11px] border border-white/8 bg-white/[0.04] px-3 text-white/72 hover:bg-white/[0.08] hover:text-white",disabled:g.isPending,onClick:()=>b(W),"aria-label":`Delete ${W.title}`,title:"Delete habit",children:e.jsx(ct,{className:"size-4"})})]})]})]}),e.jsxs("div",{className:"mt-auto grid gap-4 pt-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(L,{className:re("border-0",jw(W.completionRate)),children:["Alignment ",W.completionRate,"%"]}),e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:W.polarity==="positive"?`+${W.rewardXp} XP done`:`+${W.rewardXp} XP resisted`}),e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:W.polarity==="positive"?`-${W.penaltyXp} XP missed`:`-${W.penaltyXp} XP performed`}),e.jsx(Vt,{entityType:"habit",entityId:W.id,count:Ne,className:"min-h-8 rounded-full border-white/8 bg-white/[0.04] px-3 py-1.5 text-[12px] text-white/68 hover:bg-white/[0.07]"}),W.linkedBehaviorTitles.slice(0,2).map(y=>e.jsxs(L,{className:"bg-orange-400/12 text-orange-100",children:[e.jsx(ya,{className:"mr-1 size-3.5"}),y]},y)),W.linkedProjectIds.slice(1,2).map(y=>{const P=t.snapshot.dashboard.projects.find(q=>q.id===y);return P?e.jsxs(L,{className:"bg-sky-400/12 text-sky-100",children:["Project · ",P.title]},P.id):null}),W.linkedTaskIds.slice(1,2).map(y=>{const P=t.snapshot.tasks.find(q=>q.id===y);return P?e.jsxs(L,{className:"bg-indigo-400/12 text-indigo-100",children:["Task · ",P.title]},P.id):null}),W.linkedValueIds.slice(0,2).map(y=>{var q;const P=(q=A.data)==null?void 0:q.values.find(pe=>pe.id===y);return P?e.jsxs(L,{className:"bg-emerald-400/12 text-emerald-100",children:["Value · ",P.title]},P.id):null}),W.linkedPatternIds.slice(0,2).map(y=>{var q;const P=(q=A.data)==null?void 0:q.patterns.find(pe=>pe.id===y);return P?e.jsxs(L,{className:"bg-cyan-400/12 text-cyan-100",children:["Pattern · ",P.title]},P.id):null}),W.linkedBeliefIds.slice(0,2).map(y=>{var q;const P=(q=A.data)==null?void 0:q.beliefs.find(pe=>pe.id===y);return P?e.jsxs(L,{className:"bg-rose-400/12 text-rose-100",children:["Belief · ",P.statement]},P.id):null}),W.linkedModeIds.slice(0,2).map(y=>{var q;const P=(q=A.data)==null?void 0:q.modes.find(pe=>pe.id===y);return P?e.jsxs(L,{className:"bg-violet-400/12 text-violet-100",children:["Mode · ",P.title]},P.id):null}),W.linkedReportIds.slice(0,2).map(y=>{var q;const P=(q=A.data)==null?void 0:q.reports.find(pe=>pe.id===y);return P?e.jsxs(L,{className:"bg-fuchsia-400/12 text-fuchsia-100",children:["Report · ",P.title]},P.id):null})]}),e.jsx("div",{className:"grid gap-4",children:e.jsx(Sw,{habit:W,onSelectCell:(y,P)=>{o({habit:y,cell:P}),M(null)}})}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs(Q,{variant:"secondary",className:re("h-11 rounded-[16px] border",H.className),disabled:$.isPending,onClick:()=>void $.mutateAsync({habitId:W.id,status:H.status}),children:[e.jsx(H.Icon,{className:"size-4"}),H.label]}),e.jsxs(Q,{variant:"secondary",className:re("h-11 rounded-[16px] border",me.className),disabled:$.isPending,onClick:()=>void $.mutateAsync({habitId:W.id,status:me.status}),children:[e.jsx(me.Icon,{className:"size-4"}),me.label]})]})]})]})]},W.id)})}),e.jsx(fw,{open:f,pending:k.isPending,editingHabit:n,values:((B=A.data)==null?void 0:B.values)??[],patterns:((K=A.data)==null?void 0:K.patterns)??[],behaviors:((Z=A.data)==null?void 0:Z.behaviors)??[],beliefs:((U=A.data)==null?void 0:U.beliefs)??[],modes:((I=A.data)==null?void 0:I.modes)??[],reports:((G=A.data)==null?void 0:G.reports)??[],goals:t.snapshot.dashboard.goals,projects:t.snapshot.dashboard.projects,tasks:t.snapshot.tasks,users:t.snapshot.users,defaultUserId:(n==null?void 0:n.userId)??j,onOpenChange:h,onSubmit:async(W,ne)=>{try{await k.mutateAsync({input:W,habitId:ne})}catch(de){throw de instanceof Ea,de}}}),e.jsx(Et,{open:m!==null,onOpenChange:W=>{!W&&!g.isPending&&b(null)},children:e.jsxs(Lt,{children:[e.jsx(Dt,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.72)] backdrop-blur-xl"}),e.jsxs($t,{className:"fixed inset-x-4 top-1/2 z-50 mx-auto w-[min(30rem,calc(100vw-2rem))] max-w-[30rem] -translate-y-1/2 overflow-hidden rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(20,28,42,0.98),rgba(12,17,30,0.98))] shadow-[0_32px_90px_rgba(3,8,18,0.45)]",children:[e.jsx("div",{className:"border-b border-white/8 px-5 py-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Delete habit"}),e.jsx(Ot,{className:"mt-2 text-lg font-semibold text-white",children:(m==null?void 0:m.title)??"Delete this habit?"}),e.jsx(qt,{className:"mt-3 text-sm text-white/56",children:"Remove this habit from Forge. The habit card disappears immediately after delete succeeds."})]}),e.jsx(Ft,{asChild:!0,children:e.jsx(Q,{variant:"ghost",size:"sm",className:"h-10 w-10 rounded-[14px] border border-white/8 bg-white/[0.04] px-0 text-white/72 hover:bg-white/[0.08] hover:text-white","aria-label":"Close delete habit modal",title:"Close",disabled:g.isPending,children:e.jsx(mt,{className:"size-4"})})})]})}),e.jsxs("div",{className:"grid gap-4 p-5",children:[e.jsx("div",{className:"rounded-[20px] border border-rose-400/16 bg-rose-400/8 px-4 py-3 text-sm leading-6 text-rose-100/90",children:"This removes the habit and its check-in history from the habits page."}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-3",children:[e.jsx(Q,{variant:"secondary",onClick:()=>b(null),disabled:g.isPending,children:"Cancel"}),e.jsx(Q,{className:"border border-rose-300/18 bg-rose-300/14 text-rose-50 hover:bg-rose-300/20",pending:g.isPending,pendingLabel:"Deleting",onClick:()=>{m&&g.mutateAsync(m.id)},children:"Delete habit"})]})]})]})]})}),e.jsx(Et,{open:l!==null,onOpenChange:W=>{W||o(null)},children:e.jsxs(Lt,{children:[e.jsx(Dt,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.72)] backdrop-blur-xl"}),e.jsxs($t,{className:"fixed inset-x-4 top-1/2 z-50 mx-auto w-[min(42rem,calc(100vw-2rem))] max-w-[42rem] -translate-y-1/2 overflow-hidden rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(20,28,42,0.98),rgba(12,17,30,0.98))] shadow-[0_32px_90px_rgba(3,8,18,0.45)]",children:[e.jsx(Ot,{className:"sr-only",children:"Habit history"}),e.jsx(qt,{className:"sr-only",children:"Log or revise a habit check-in for a selected history point."}),l&&O?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-b border-white/8 px-5 py-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Habit history"}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"text-lg font-semibold text-white",children:l.habit.title}),e.jsx(L,{className:"bg-white/[0.08] text-white/76",children:l.cell.actionLabel})]}),e.jsx("div",{className:"mt-3 text-sm text-white/56",children:l.habit.frequency==="daily"?"Log or revise the check-in for this specific day.":"Log or revise the representative check-in for this week."})]}),e.jsx(Ft,{asChild:!0,children:e.jsx(Q,{variant:"ghost",size:"sm",className:"h-10 w-10 rounded-[14px] border border-white/8 bg-white/[0.04] px-0 text-white/72 hover:bg-white/[0.08] hover:text-white","aria-label":"Close history modal",title:"Close",children:e.jsx(mt,{className:"size-4"})})})]})}),e.jsxs("div",{className:"grid gap-4 p-5",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("button",{type:"button","aria-pressed":c==="done",className:re("rounded-[22px] border px-4 py-4 text-left transition",c==="done"?"border-emerald-300/24 bg-emerald-300/14 text-white shadow-[0_16px_36px_rgba(52,211,153,0.14)]":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"),onClick:()=>x(W=>W==="done"?null:"done"),children:[e.jsxs("div",{className:"flex items-center gap-2 text-base font-medium",children:[e.jsx(Ia,{className:"size-4"}),O.alignedLabel]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:O.alignedDescription})]}),e.jsxs("button",{type:"button","aria-pressed":c==="missed",className:re("rounded-[22px] border px-4 py-4 text-left transition",c==="missed"?"border-rose-300/24 bg-rose-300/14 text-white shadow-[0_16px_36px_rgba(251,113,133,0.14)]":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"),onClick:()=>x(W=>W==="missed"?null:"missed"),children:[e.jsxs("div",{className:"flex items-center gap-2 text-base font-medium",children:[e.jsx(Ko,{className:"size-4"}),O.unalignedLabel]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:O.unalignedDescription})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-white",children:"Optional note"}),e.jsx(Me,{value:v,onChange:W=>u(W.target.value),placeholder:"Add context for what happened on this day or week.",className:"min-h-24"})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-3",children:[e.jsx(Q,{variant:"secondary",onClick:()=>o(null),disabled:$.isPending,children:"Cancel"}),e.jsx(Q,{disabled:$.isPending||!_,pending:$.isPending,pendingLabel:"Saving",onClick:async()=>{_&&(c===null?(await xf(l.habit.id,l.cell.actionDateKey),await T()):await $.mutateAsync({habitId:l.habit.id,status:c,dateKey:l.cell.actionDateKey,note:v.trim()||void 0}),o(null))},children:"Save check-in"})]})]})]}):null]})]})})]})}const Tw={title:"",description:"",owner:"Albert",userId:null,goalId:"",projectId:"",priority:"medium",status:"focus",effort:"deep",energy:"steady",dueDate:"",points:60,tagIds:[],notes:[]},Pw={goalId:"",title:"",description:"",status:"active",userId:null,targetPoints:240,themeColor:"#c0c1ff",notes:[]},Mw={title:"",description:"",horizon:"year",status:"active",userId:null,targetPoints:400,themeColor:"#c8a46b",tagIds:[],notes:[]},Aw=["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 Ew(t){return t!==null&&Aw.includes(t)}function so(t,s,i=96){const a=t.trim()||s.trim();return a.length<=i?a:`${a.slice(0,i-1).trimEnd()}…`}function Lw(t){return[t.summary.trim(),t.rationale.trim()?`Why it matters: ${t.rationale.trim()}`:""].filter(Boolean).join(`
|
|
4
|
-
|
|
5
|
-
`)}function io(t){return!Ew(t.entityType)||!t.entityId?null:{entityType:t.entityType,entityId:t.entityId,anchorKey:null}}function Mm(t,s,i){var a,n;return t.entityType==="goal"&&t.entityId?t.entityId:t.entityType==="project"&&t.entityId?((a=s.find(r=>r.id===t.entityId))==null?void 0:a.goalId)??"":t.entityType==="task"&&t.entityId?((n=i.find(r=>r.id===t.entityId))==null?void 0:n.goalId)??"":""}function Dw(t,s){var i;return t.entityType==="project"&&t.entityId?t.entityId:t.entityType==="task"&&t.entityId?((i=s.find(a=>a.id===t.entityId))==null?void 0:i.projectId)??"":""}function Am(t,s,i){const a=[];return i.length>0&&a.push("task"),s.length>0&&a.push("project"),a.push("goal"),io(t)&&a.push("note"),a}function $w(t,s,i){const a=Am(t,s,i);return a.includes("task")&&(t.entityType==="task"||t.entityType==="project")?"task":a.includes("project")&&t.entityType==="goal"?"project":a[0]??"goal"}function Ow(t,s,i){var o,c,x;const a=Mm(t,s,i),r=Dw(t,i)||(a?((o=s.find(v=>v.goalId===a))==null?void 0:o.id)??"":"")||((c=s[0])==null?void 0:c.id)||"",l=r?((x=s.find(v=>v.id===r))==null?void 0:x.goalId)??a:a;return{...Tw,title:so(t.recommendation,t.title),description:Lw(t),goalId:l,projectId:r}}function Fw(t,s,i,a){var l;const r=Mm(t,i,a)||((l=s[0])==null?void 0:l.id)||"";return{...Pw,goalId:r,title:so(t.title,t.recommendation),description:`${t.summary.trim()}
|
|
6
|
-
|
|
7
|
-
Recommendation: ${t.recommendation.trim()}`.trim()}}function _w(t){return{...Mw,title:so(t.title,t.recommendation),description:`${t.summary.trim()}
|
|
8
|
-
|
|
9
|
-
Recommendation: ${t.recommendation.trim()}`.trim()}}function Rw(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 Kd(t,s,i,a){return{kind:$w(t,s,i),task:Ow(t,i,a),project:Fw(t,s,i,a),goal:_w(t),noteMarkdown:Rw(t)}}function zw(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 qw({open:t,onOpenChange:s,insight:i,goals:a,projects:n,tasks:r,tags:l,pending:o=!1,onSubmit:c}){const x=d.useMemo(()=>Am(i,a,n),[a,i,n]),v=d.useMemo(()=>io(i),[i]),[u,f]=d.useState(()=>Kd(i,a,n,r)),[h,m]=d.useState(null),[b,w]=d.useState({});d.useEffect(()=>{t&&(f(Kd(i,a,n,r)),m(null),w({}))},[a,i,t,n,r]);const M=u.task.projectId?n.find(S=>S.id===u.task.projectId)??null:null;d.useEffect(()=>{M&&u.task.goalId!==M.goalId&&f(S=>({...S,task:{...S.task,goalId:M.goalId}}))},[u.task.goalId,M]);const E=u.project.goalId?a.find(S=>S.id===u.project.goalId)??null:null,D=d.useMemo(()=>{var S,p,A;if(!v)return null;switch(v.entityType){case"goal":return((S=a.find(T=>T.id===v.entityId))==null?void 0:S.title)??"Linked goal";case"project":return((p=n.find(T=>T.id===v.entityId))==null?void 0:p.title)??"Linked project";case"task":return((A=r.find(T=>T.id===v.entityId))==null?void 0:A.title)??"Linked task";default:return`${v.entityType.replaceAll("_"," ")}`}},[a,n,v,r]),j=[{id:"kind",eyebrow:"Apply",title:"Choose what this insight should become",description:"Accept means you agree with the recommendation. Apply means you turn it into a real record right now.",render:(S,p)=>e.jsx(se,{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(Ze,{value:S.kind,onChange:A=>p({kind:A}),options:x.map(A=>({value:A,...zw(A)})),columns:x.length>=3?3:2})})},{id:"details",eyebrow:"Details",title:"Review the record Forge will create",description:"The fields are prefilled from the insight, but you can tighten them before saving.",render:(S,p)=>S.kind==="task"?e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Task title",error:b.title??null,children:e.jsx(le,{value:S.task.title,onChange:A=>p({task:{...S.task,title:A.target.value}}),placeholder:"Turn the recommendation into a task"})}),e.jsx(se,{label:"Description",children:e.jsx(Me,{value:S.task.description,onChange:A=>p({task:{...S.task,description:A.target.value}}),placeholder:"Add the operational context for this task."})}),e.jsx(se,{label:"Project",error:b.projectId??null,children:e.jsx("div",{className:"grid gap-3",children:n.map(A=>{const T=A.id===S.task.projectId;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:()=>p({task:{...S.task,projectId:A.id,goalId:A.goalId}}),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"font-medium",children:A.title}),e.jsx(Te,{kind:"goal",label:A.goalTitle,compact:!0,gradient:!1})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:A.description||"No project note attached yet."})]},A.id)})})}),e.jsx(se,{label:"Owner",error:b.owner??null,children:e.jsx(le,{value:S.task.owner,onChange:A=>p({task:{...S.task,owner:A.target.value}}),placeholder:"Albert"})}),e.jsx(se,{label:"Tags",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:l.map(A=>{const T=S.task.tagIds.includes(A.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:()=>p({task:{...S.task,tagIds:T?S.task.tagIds.filter(k=>k!==A.id):[...S.task.tagIds,A.id]}}),children:A.name},A.id)})})})]}):S.kind==="project"?e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Project title",error:b.title??null,children:e.jsx(le,{value:S.project.title,onChange:A=>p({project:{...S.project,title:A.target.value}}),placeholder:"Turn the insight into a project"})}),e.jsx(se,{label:"Description",children:e.jsx(Me,{value:S.project.description,onChange:A=>p({project:{...S.project,description:A.target.value}}),placeholder:"Describe the initiative this insight points to."})}),e.jsx(se,{label:"Goal",error:b.goalId??null,children:e.jsx("div",{className:"grid gap-3",children:a.map(A=>{const T=A.id===S.project.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:()=>p({project:{...S.project,goalId:A.id}}),children:[e.jsx("div",{className:"font-medium",children:A.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:A.description||"No strategic note attached yet."})]},A.id)})})}),E?e.jsxs(Hs,{children:["This project will sit under the “",E.title,"” goal."]}):null]}):S.kind==="goal"?e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Goal title",error:b.title??null,children:e.jsx(le,{value:S.goal.title,onChange:A=>p({goal:{...S.goal,title:A.target.value}}),placeholder:"Turn the insight into a life goal"})}),e.jsx(se,{label:"Description",children:e.jsx(Me,{value:S.goal.description,onChange:A=>p({goal:{...S.goal,description:A.target.value}}),placeholder:"Describe the strategic direction this insight suggests."})}),e.jsx(se,{label:"Tags",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:l.map(A=>{const T=S.goal.tagIds.includes(A.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:()=>p({goal:{...S.goal,tagIds:T?S.goal.tagIds.filter(k=>k!==A.id):[...S.goal.tagIds,A.id]}}),children:A.name},A.id)})})})]}):e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Linked note",description:"This stores the insight as durable Markdown evidence on the linked entity instead of creating a new work item.",hint:D?`This note will attach to ${D}.`:void 0,children:e.jsx(Me,{value:S.noteMarkdown,onChange:A=>p({noteMarkdown:A.target.value}),placeholder:"Write the applied note content in Markdown",className:"min-h-64"})}),D?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:D})]}):null]})}];return e.jsx(rt,{open:t,onOpenChange:s,eyebrow:"Apply insight",title:"Turn this insight into a real record",description:"Apply should create something concrete inside Forge, not just change the status label.",value:u,onChange:f,steps:j,submitLabel:"Apply insight",pending:o,error:h,onSubmit:async()=>{m(null),w({});try{if(u.kind==="task"){const S=rm.safeParse(u.task);if(!S.success){w(Object.fromEntries(Object.entries(S.error.flatten().fieldErrors).map(([p,A])=>[p,A==null?void 0:A[0]]))),m("This applied task still needs a valid title, project, and owner.");return}await c({kind:"task",input:S.data}),s(!1);return}if(u.kind==="project"){const S=nm.safeParse(u.project);if(!S.success){w(Object.fromEntries(Object.entries(S.error.flatten().fieldErrors).map(([p,A])=>[p,A==null?void 0:A[0]]))),m("This applied project still needs a valid title and goal.");return}await c({kind:"project",input:S.data}),s(!1);return}if(u.kind==="goal"){const S=am.safeParse(u.goal);if(!S.success){w(Object.fromEntries(Object.entries(S.error.flatten().fieldErrors).map(([p,A])=>[p,A==null?void 0:A[0]]))),m("This applied goal still needs a valid title and target.");return}await c({kind:"goal",input:S.data}),s(!1);return}if(!u.noteMarkdown.trim()){m("The linked note needs Markdown content before it can be saved.");return}if(!v){m("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:u.noteMarkdown.trim()}}),s(!1)}catch(S){m(S instanceof Error?S.message:"Unable to apply this insight right now.")}}})}function Ud(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 Em({open:t,onOpenChange:s,title:i="Store insight",description:a="Capture a clear observation, its recommendation, and where it belongs without dropping into a raw admin form.",eyebrow:n="Insight",pending:r=!1,submitLabel:l="Store insight",initialValue:o,lockedEntity:c,entityCandidates:x=[],onSubmit:v}){const[u,f]=d.useState(()=>Ud(o,c)),[h,m]=d.useState(null);d.useEffect(()=>{t&&(f(Ud(o,c)),m(null))},[o,c,t]);const b=d.useMemo(()=>{const E=new Set(["general"]);return x.forEach(D=>E.add(D.entityType)),c&&E.add(c.entityType),Array.from(E)},[x,c]),w=x.filter(E=>E.entityType===u.targetKind),M=[{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:(E,D)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{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(le,{value:E.title,onChange:j=>D({title:j.target.value}),placeholder:"Weekly review needs a tighter end ritual"})}),e.jsx(se,{label:"Timeframe",description:"Keep the horizon short and readable.",children:e.jsx(le,{value:E.timeframeLabel,onChange:j=>D({timeframeLabel:j.target.value}),placeholder:"This week"})}),e.jsx(se,{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(Te,{kind:c.kind,label:c.label}),c.description?e.jsx(Hs,{className:"mt-2",children:c.description}):null]}):e.jsxs(e.Fragment,{children:[e.jsx(Ze,{value:E.targetKind,onChange:j=>D({targetKind:j,entityType:j==="general"?"":j,entityId:""}),options:b.map(j=>({value:j,label:j==="general"?"General insight":j==="trigger_report"?"Report":j.charAt(0).toUpperCase()+j.slice(1),description:j==="general"?"Store it in the broader insight feed.":`Attach it to a specific ${j==="trigger_report"?"report":j}.`})),columns:b.length>=3?3:2}),E.targetKind!=="general"?w.length>0?e.jsx("div",{className:"mt-4 grid gap-3 md:grid-cols-2",children:w.map(j=>{const S=E.entityType===j.entityType&&E.entityId===j.entityId;return e.jsxs("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${S?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.14)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"}`,onClick:()=>D({entityType:j.entityType,entityId:j.entityId}),children:[e.jsx(Te,{kind:j.kind,label:j.label,compact:!0}),j.description?e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:j.description}):null]},`${j.entityType}:${j.entityId}`)})}):e.jsxs(Hs,{className:"mt-4",children:["No ",E.targetKind==="trigger_report"?"reports":`${E.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:(E,D)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{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(Me,{value:E.summary,onChange:j=>D({summary:j.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(se,{label:"Why this matters",description:"Optional context that helps explain the recommendation.",children:e.jsx(Me,{value:E.rationale,onChange:j=>D({rationale:j.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:(E,D)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{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(Me,{value:E.recommendation,onChange:j=>D({recommendation:j.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(se,{label:"Confidence",description:"Choose how strongly this recommendation holds up right now.",children:e.jsx(Ze,{value:String(E.confidence),onChange:j=>D({confidence:Number(j)}),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(rt,{open:t,onOpenChange:s,eyebrow:n,title:i,description:a,value:u,onChange:f,steps:M,submitLabel:l,pending:r,error:h,onSubmit:async()=>{m(null);const E=sv.safeParse({originType:u.originType,originAgentId:u.originAgentId,originLabel:u.originLabel,entityType:u.targetKind==="general"?"":u.entityType,entityId:u.targetKind==="general"?"":u.entityId,timeframeLabel:u.timeframeLabel,title:u.title,summary:u.summary,recommendation:u.recommendation,rationale:u.rationale,confidence:u.confidence,ctaLabel:u.ctaLabel});if(!E.success){m("This insight still needs a title, a summary, and a recommendation before it can be stored.");return}try{await v(E.data),s(!1)}catch(D){m(D instanceof Error?D.message:"Unable to store this insight right now.")}}})}function Bw(){var j,S,p,A;const t=We(),s=ut(),i=Je(),a=Array.isArray(i.selectedUserIds)?i.selectedUserIds:[],{snapshot:n}=i,[r,l]=d.useState(!1),[o,c]=d.useState(null),x=fe({queryKey:["forge-insights",...a],queryFn:()=>sg(a)}),v=xe({mutationFn:zh,onSuccess:async()=>{await t.invalidateQueries({queryKey:["forge-insights"]})}}),u=xe({mutationFn:({insightId:T,feedbackType:k})=>td(T,k),onSuccess:async()=>{await t.invalidateQueries({queryKey:["forge-insights"]})}}),f=xe({mutationFn:({insightId:T})=>zg(T),onMutate:async({insightId:T})=>{await t.cancelQueries({queryKey:["forge-insights"]});const k=t.getQueryData(["forge-insights"]);if(k){const $=k.insights.feed.find(g=>g.id===T);t.setQueryData(["forge-insights"],{insights:{...k.insights,feed:k.insights.feed.filter(g=>g.id!==T),openCount:($==null?void 0:$.status)==="open"?Math.max(0,k.insights.openCount-1):k.insights.openCount}})}return{previous:k}},onError:(T,k,$)=>{$!=null&&$.previous&&t.setQueryData(["forge-insights"],$.previous)},onSettled:async()=>{await t.invalidateQueries({queryKey:["forge-insights"]})}}),h=xe({mutationFn:async({insight:T,submission:k})=>{let $=null,g="Applied the insight.";if(k.kind==="task"){const C=await Sn(k.input);$=`/tasks/${C.task.id}`,g=`Created task: ${C.task.title}`}else if(k.kind==="project"){const C=await Wh(k.input);$=`/projects/${C.project.id}`,g=`Created project: ${C.project.title}`}else if(k.kind==="goal"){const C=await Qh(k.input);$=`/goals/${C.goal.id}`,g=`Created goal: ${C.goal.title}`}else{const C=io(T);if(!C)throw new Error("This insight is not linked to a concrete entity yet, so Forge cannot attach a linked note to it.");await $a({contentMarkdown:k.input.contentMarkdown,links:[C]}),$=Nm(C.entityType,C.entityId),g="Created a linked note from the insight."}return await td(T.id,"applied",g),{href:$}},onSuccess:async({href:T})=>{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"]})]),c(null),T&&s(T)}}),m=(j=x.data)==null?void 0:j.insights,b=d.useMemo(()=>[...n.goals.slice(0,8).map(T=>({entityType:"goal",entityId:T.id,kind:"goal",label:T.title,description:T.description})),...n.projects.slice(0,8).map(T=>({entityType:"project",entityId:T.id,kind:"project",label:T.title,description:T.goalTitle})),...n.tasks.slice(0,10).map(T=>({entityType:"task",entityId:T.id,kind:"task",label:T.title,description:T.status.replaceAll("_"," ")}))],[n.goals,n.projects,n.tasks]),w=u.isPending?((S=u.variables)==null?void 0:S.insightId)??null:null,M=f.isPending?((p=f.variables)==null?void 0:p.insightId)??null:null,E=h.isPending?((A=h.variables)==null?void 0:A.insight.id)??null:null,D=n.metrics.topGoalId?n.goals.find(T=>T.id===n.metrics.topGoalId)??null:null;return x.isLoading?e.jsx(nt,{eyebrow:"Insights",title:"Loading the insight feed",description:"Pulling coaching, momentum analysis, and stored recommendations."}):x.isError||!m?e.jsx(ze,{eyebrow:"Insights",error:x.error,onRetry:()=>void t.invalidateQueries({queryKey:["forge-insights"]})}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{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(Q,{onClick:()=>l(!0),children:"Store insight"})}),e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ae,{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(T=>e.jsxs("div",{className:"rounded-[16px] bg-white/[0.04] p-3",children:[e.jsx("div",{className:"h-12 rounded-[12px]",style:{background:T.intensity>=4?"rgba(192,193,255,0.95)":T.intensity===3?"rgba(192,193,255,0.7)":T.intensity===2?"rgba(192,193,255,0.45)":T.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:T.label})]},T.id))})]}),e.jsxs(ae,{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(it,{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(Kn,{width:"100%",height:"100%",minWidth:280,minHeight:288,children:e.jsxs(kh,{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(Un,{dataKey:"label",tick:{fill:"rgba(255,255,255,0.42)",fontSize:11}}),e.jsx(Qn,{hide:!0}),e.jsx(Gr,{dataKey:"xp",stroke:"#c0c1ff",fill:"url(#insight-xp)",strokeWidth:2}),e.jsx(Gr,{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(it,{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(it,{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(ae,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(L,{className:"bg-white/[0.08] text-white/60",children:"Deterministic coaching"}),e.jsx(it,{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}),D?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:D.title})]}),e.jsx(Q,{variant:"secondary",size:"sm",onClick:()=>s(`/goals/${D.id}`),children:"Open goal"})]}):null]})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ae,{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(Q,{onClick:()=>l(!0),children:"Store insight"})})]})]}),e.jsxs(ae,{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(T=>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:T.title}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:T.summary}),T.user?e.jsx("div",{className:"mt-3",children:e.jsx(Ue,{user:T.user,compact:!0})}):null]}),e.jsx(L,{className:"text-white/70",children:T.status})]}),e.jsx("div",{className:"mt-3 text-sm text-white/58",children:T.recommendation}),e.jsxs("div",{className:"mt-3 text-xs uppercase tracking-[0.16em] text-white/38",children:[T.originLabel??T.originType," · confidence ",Math.round(T.confidence*100),"%"]}),T.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:T.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:[T.status!=="accepted"?e.jsx(Q,{variant:"secondary",pending:w===T.id,onClick:()=>void u.mutateAsync({insightId:T.id,feedbackType:"accepted"}),children:"Accept"}):null,e.jsx(Q,{pending:E===T.id,onClick:()=>c(T),children:"Apply"}),e.jsx(Q,{variant:"ghost",pending:M===T.id,onClick:()=>void f.mutateAsync({insightId:T.id}),children:"Dismiss"})]})]})]},T.id))})]})]})]}),e.jsx(Em,{open:r,onOpenChange:l,entityCandidates:b,pending:v.isPending,onSubmit:async T=>{await v.mutateAsync(T)}}),o?e.jsx(qw,{open:!!o,onOpenChange:T=>{T||c(null)},insight:o,goals:n.goals,projects:n.projects,tasks:n.tasks,tags:n.tags,pending:h.isPending,onSubmit:async T=>{await h.mutateAsync({insight:o,submission:T})}}):null]})}const ks=["backlog","focus","in_progress","blocked","done"];function Lm(t){return t.startsWith("lane:")||t.includes(":lane:")}function Kw(t){var s,i;return((i=(s=t.data)==null?void 0:s.current)==null?void 0:i.type)==="lane"||Lm(String(t.id))}function Uw(t){var s,i;return((i=(s=t.data)==null?void 0:s.current)==null?void 0:i.type)==="trash"}function Qw(t,s){const i=Math.max(0,Math.min(t.right,s.right)-Math.max(t.left,s.left)),a=Math.max(0,Math.min(t.bottom,s.bottom)-Math.max(t.top,s.top));return i*a}const Ww=t=>{const s=px(t),i=s.find(l=>{const o=t.droppableContainers.find(c=>c.id===l.id);return o?Uw(o):!1});if(i)return[i];const a=s.find(l=>Lm(String(l.id)));if(a)return[a];const r=t.droppableContainers.filter(l=>Kw(l)).map(l=>{const o=t.droppableRects.get(l.id);if(!o)return null;const c=Qw(t.collisionRect,o);return c<=0?null:{id:l.id,data:{droppableContainer:l,value:c}}}).filter(Boolean).sort((l,o)=>{var c,x;return(((c=o==null?void 0:o.data)==null?void 0:c.value)??0)-(((x=l==null?void 0:l.data)==null?void 0:x.value)??0)});return r.length>0?r:s.length>0?s:xx(t)};function Dm({task:t,goal:s,tags:i,isSelected:a,isDragging:n=!1,isOverlay:r=!1,style:l,setNodeRef:o,dragAttributes:c,dragListeners:x,isMobile:v=!1,onSelect:u,onStartTask:f,onQuickReopen:h,onStepTask:m,onOpenTask:b,onEditTask:w,notesSummaryByEntity:M}){const{t:E,formatDate:D}=lt(),j=ks[ks.indexOf(t.status)-1]??null,S=ks[ks.indexOf(t.status)+1]??null,p=is(M,"task",t.id).count;return e.jsxs("article",{ref:o,style:l,className:re("w-full max-w-full min-w-0 overflow-hidden rounded-[18px] p-3 shadow-[inset_0_0_0_1px_rgba(255,255,255,0.04)] transition cursor-grab active:cursor-grabbing",v&&"touch-none select-none",r&&"rotate-[0.5deg] bg-[linear-gradient(180deg,rgba(192,193,255,0.24),rgba(192,193,255,0.1))] shadow-[0_28px_80px_rgba(8,12,24,0.42),inset_0_0_0_1px_rgba(192,193,255,0.26)]",n&&!r&&"opacity-35 shadow-[inset_0_0_0_1px_rgba(255,255,255,0.02)]",a?"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":n?"true":"false","data-testid":`task-card-${t.id}`,onClick:()=>u(t.id),...c,...x,children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx(L,{className:"shrink-0 text-[11px] text-[var(--tertiary)]",children:t.priority}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[w?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:A=>{A.preventDefault(),A.stopPropagation(),w(t.id)},children:e.jsx(mi,{className:"size-3.5"})}):null,b?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:A=>{A.preventDefault(),A.stopPropagation(),b(t.id)},children:e.jsx(Ms,{className:"size-3.5"})}):null,v?e.jsxs("div",{className:"flex items-center gap-1",onClick:A=>A.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:!j,onClick:()=>{j&&(m==null||m(t.id,"previous"))},children:e.jsx(Bn,{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:!S,onClick:()=>{S&&(m==null||m(t.id,"next"))},children:e.jsx(Ji,{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:A=>{A.preventDefault(),A.stopPropagation(),f==null||f(t.id)},children:e.jsx(Cs,{className:"size-4 fill-current"})}):null,e.jsxs("span",{className:"text-[11px] text-white/44",children:[t.points," xp"]})]})]}),e.jsx(Xe,{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||E("common.executionBoard.noExecutionNote")}),e.jsxs("div",{className:"mt-2.5 flex min-w-0 flex-wrap gap-1.5",children:[s?e.jsx(Te,{kind:"goal",label:s.title,compact:!0,wrap:!0,className:"min-w-0 max-w-full"}):null,e.jsx(Ue,{user:t.user,compact:!0}),e.jsx(Vt,{entityType:"task",entityId:t.id,count:p}),t.time.totalCreditedSeconds>0?e.jsxs(L,{className:"bg-white/8 text-white/72",children:[Math.floor(t.time.totalCreditedSeconds/60)," min"]}):null,t.time.activeRunCount>0?e.jsxs(L,{className:"bg-emerald-500/12 text-emerald-200",children:[t.time.activeRunCount," live"]}):null,i.slice(0,2).map(A=>e.jsx(L,{className:"bg-white/8",style:{color:A.color},children:A.name},A.id))]}),e.jsxs("div",{className:"mt-2.5 flex min-w-0 items-center justify-between gap-2 text-[11px] text-white/45",children:[e.jsxs("span",{className:"min-w-0 truncate",children:[t.effort," / ",t.energy]}),e.jsxs("div",{className:"flex min-w-0 shrink-0 items-center gap-2 text-right",children:[t.status==="done"&&h?e.jsx("button",{type:"button",className:"rounded-full bg-white/8 px-3 py-1 text-[10px] tracking-[0.16em] text-white transition hover:bg-white/12",onClick:A=>{A.preventDefault(),A.stopPropagation(),h(t.id)},children:E("common.executionBoard.reopen")}):null,e.jsx("span",{children:D(t.dueDate)})]})]})]})}function Qd(t){const{task:s,sortableId:i}=t,{attributes:a,listeners:n,setNodeRef:r,transform:l,transition:o,isDragging:c}=Dl({id:i,data:{type:"task",taskId:s.id,status:s.status}});return e.jsx(Dm,{...t,setNodeRef:r,dragAttributes:a,dragListeners:n,isDragging:c,isMobile:t.isMobile,onStartTask:t.onStartTask,onStepTask:t.onStepTask,notesSummaryByEntity:t.notesSummaryByEntity,style:{transform:$l.Transform.toString(l),transition:o}})}function Wd({droppableId:t,status:s,title:i,detail:a,count:n,dragging:r,children:l}){const{setNodeRef:o,isOver:c}=Ch({id:t,data:{type:"lane",status:s}});return e.jsx("div",{ref:o,className:re("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(ae,{className:re("h-full w-full max-w-full min-w-0 overflow-hidden p-3 transition-[background-color,box-shadow,border-color,transform]",r&&"border border-white/8",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:a}),e.jsx("h3",{className:"mt-1 break-words text-[1.45rem] leading-[1] text-white",children:i})]}),e.jsx("div",{className:"shrink-0 font-display text-[1.45rem] text-[var(--primary)]",children:n})]}),e.jsx("div",{className:re("grid w-full max-w-full min-w-0 min-h-48 content-start gap-2 rounded-[18px] p-2 transition",c?"bg-[rgba(125,211,252,0.08)]":"bg-white/[0.02]"),children:l})]})})}function Hw({droppableId:t,title:s,detail:i}){const{setNodeRef:a,isOver:n}=Ch({id:t,data:{type:"trash"}});return e.jsx("div",{ref:a,className:re("pointer-events-auto fixed right-4 top-4 z-50 w-[min(18rem,calc(100vw-2rem))] rounded-[28px] border px-5 py-4 shadow-[0_24px_80px_rgba(6,10,20,0.48)] backdrop-blur-2xl transition lg:right-6 lg:top-6",n?"border-rose-300/38 bg-[linear-gradient(180deg,rgba(244,63,94,0.28),rgba(120,24,42,0.46))] text-white scale-[1.02]":"border-white/10 bg-[linear-gradient(180deg,rgba(18,24,38,0.96),rgba(10,14,24,0.94))] text-white/84"),"data-testid":"kanban-trash-dropzone","data-trash-hover":n?"true":"false",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:re("flex size-12 items-center justify-center rounded-full border transition",n?"border-white/28 bg-white/12":"border-white/12 bg-white/6"),children:e.jsx(ct,{className:"size-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/55",children:"Bin"}),e.jsx("div",{className:"mt-1 text-base font-medium text-white",children:s}),e.jsx("div",{className:"mt-1 text-sm leading-5 text-white/62",children:i})]})]})})}function $m({tasks:t,goals:s,tags:i,selectedTaskId:a,onMove:n,onSelectTask:r,onStartTask:l,onQuickReopenTask:o,onDeleteTask:c,onOpenTask:x,onEditTask:v,notesSummaryByEntity:u}){const{t:f}=lt(),h=d.useId(),m=`${h}:trash`,[b,w]=d.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(max-width: 1023px)").matches),M=Ml(Al(El,{activationConstraint:{distance:6}})),[E,D]=d.useState(null),[j,S]=d.useState(null),[p,A]=d.useState(null),[T,k]=d.useState(()=>typeof window>"u"?!1:window.localStorage.getItem("forge.kanban-skip-delete-confirmation")==="true"),[$,g]=d.useState(!1),[C,F]=d.useState({}),z={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")}},J=d.useMemo(()=>t.map(W=>{const ne=C[W.id];return ne?{...W,status:ne}:W}),[C,t]),O=E?J.find(W=>W.id===E)??null:null,_=O?s.find(W=>W.id===O.goalId):void 0,B=O?O.tagIds.map(W=>i.find(ne=>ne.id===W)).filter(Boolean):[];d.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const W=window.matchMedia("(max-width: 1023px)"),ne=de=>{w(de?de.matches:W.matches)};return ne(),typeof W.addEventListener=="function"?(W.addEventListener("change",ne),()=>W.removeEventListener("change",ne)):(W.addListener(ne),()=>W.removeListener(ne))},[]),d.useEffect(()=>{if(!E){document.body.style.cursor="";return}return document.body.style.cursor="grabbing",()=>{document.body.style.cursor=""}},[E]),d.useEffect(()=>{F(W=>{const ne=new Set(t.map(Ne=>Ne.id));let de=!1;const we={};for(const[Ne,H]of Object.entries(W)){const me=t.find(y=>y.id===Ne);if(!ne.has(Ne)||!me||me.status===H){de=!0;continue}we[Ne]=H}return de?we:W})},[t]);function K(W){var de;const ne=(de=W.active.data.current)==null?void 0:de.taskId;typeof ne=="string"&&D(ne)}const Z=W=>{k(W),typeof window<"u"&&window.localStorage.setItem("forge.kanban-skip-delete-confirmation","true")},U=async(W,ne)=>{if(c){A(W.id);try{ne&&Z(!0),await c(W.id),S(null),g(!1),F(de=>{const we={...de};return delete we[W.id],we})}finally{A(null)}}};async function I(W){var P,q,pe,ee,Y;const{active:ne,over:de}=W;if(D(null),!de||ne.id===de.id)return;const we=typeof((P=ne.data.current)==null?void 0:P.taskId)=="string"?ne.data.current.taskId:String(ne.id),Ne=J.find(R=>R.id===we);if(!Ne)return;if(((q=de.data.current)==null?void 0:q.type)==="trash"){if(!c)return;if(T){await U(Ne,!1);return}g(!1),S(Ne);return}const H=typeof((pe=de.data.current)==null?void 0:pe.status)=="string"?de.data.current.status:null,me=typeof((ee=de.data.current)==null?void 0:ee.taskId)=="string"?de.data.current.taskId:String(de.id),y=H??((Y=J.find(R=>R.id===me))==null?void 0:Y.status)??Ne.status;if(y!==Ne.status&&ks.includes(y)){F(R=>({...R,[Ne.id]:y}));try{await n(Ne.id,y)}catch(R){throw F(X=>{const be={...X};return delete be[Ne.id],be}),R}}}async function G(W,ne){const de=J.find(me=>me.id===W);if(!de)return;const we=ks.indexOf(de.status),Ne=ne==="previous"?we-1:we+1,H=ks[Ne]??null;if(!(!H||H===de.status)){F(me=>({...me,[de.id]:H}));try{await n(de.id,H)}catch(me){throw F(y=>{const P={...y};return delete P[de.id],P}),me}}}return e.jsxs(Ll,{sensors:M,collisionDetection:Ww,onDragStart:K,onDragCancel:()=>D(null),onDragEnd:W=>void I(W),children:[O&&c?e.jsx(Hw,{droppableId:m,title:f("common.executionBoard.deleteDropTitle"),detail:f("common.executionBoard.deleteDropDetail")}):null,e.jsx("div",{className:"w-full max-w-full min-w-0 pb-2",children:b?e.jsx("div",{className:"grid w-full max-w-full min-w-0 gap-2",children:ks.map(W=>{const ne=J.filter(de=>de.status===W);return e.jsx(yn,{items:ne.map(de=>`${h}:task:${de.id}`),strategy:jn,children:e.jsxs(Wd,{droppableId:`${h}:lane:${W}`,status:W,title:z[W].title,detail:z[W].detail,count:ne.length,dragging:E!==null,children:[ne.map(de=>e.jsx(Qd,{sortableId:`${h}:task:${de.id}`,task:de,goal:s.find(we=>we.id===de.goalId),tags:de.tagIds.map(we=>i.find(Ne=>Ne.id===we)).filter(Boolean),isSelected:a===de.id,isMobile:!0,onSelect:r,onStartTask:l,onQuickReopen:o,onStepTask:G,onOpenTask:x,onEditTask:v,notesSummaryByEntity:u},de.id)),ne.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]})},W)})}):e.jsx("div",{className:"grid w-full min-w-0 gap-0.5 xl:grid-cols-[repeat(5,minmax(0,1fr))]",children:ks.map(W=>{const ne=J.filter(de=>de.status===W);return e.jsx(yn,{items:ne.map(de=>`${h}:task:${de.id}`),strategy:jn,children:e.jsxs(Wd,{droppableId:`${h}:lane:${W}`,status:W,title:z[W].title,detail:z[W].detail,count:ne.length,dragging:E!==null,children:[ne.map(de=>e.jsx(Qd,{sortableId:`${h}:task:${de.id}`,task:de,goal:s.find(we=>we.id===de.goalId),tags:de.tagIds.map(we=>i.find(Ne=>Ne.id===we)).filter(Boolean),isSelected:a===de.id,onSelect:r,onStartTask:l,onQuickReopen:o,onStepTask:G,onOpenTask:x,onEditTask:v,notesSummaryByEntity:u},de.id)),ne.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]})},W)})})}),e.jsx(ux,{adjustScale:!1,dropAnimation:null,children:O?e.jsx("div",{className:"w-[20rem] max-w-[calc(100vw-2rem)]",children:e.jsx(Dm,{task:O,goal:_,tags:B,isSelected:a===O.id,isDragging:!0,isOverlay:!0,isMobile:b,onSelect:()=>{},onStartTask:l,notesSummaryByEntity:u})}):null}),j?e.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-[rgba(5,8,18,0.74)] p-4 backdrop-blur-xl",children:e.jsxs(ae,{className:"w-full max-w-md border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,36,0.96),rgba(9,13,22,0.98))] shadow-[0_32px_90px_rgba(5,8,18,0.58)]",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-1 flex size-11 shrink-0 items-center justify-center rounded-full bg-rose-500/14 text-rose-100",children:e.jsx(ct,{className:"size-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-display text-[1.35rem] leading-tight text-white",children:f("common.executionBoard.deleteConfirmTitle")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/64",children:f("common.executionBoard.deleteConfirmDescription",{title:j.title})})]})]}),e.jsxs("label",{className:"mt-5 flex items-center gap-3 rounded-[18px] bg-white/[0.05] px-4 py-3 text-sm text-white/76",children:[e.jsx("input",{type:"checkbox",checked:$,onChange:W=>g(W.target.checked),className:"size-4 rounded border-white/20 bg-transparent text-[var(--primary)]"}),e.jsx("span",{children:f("common.executionBoard.deleteConfirmCheckbox")})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap justify-end gap-3",children:[e.jsx(Q,{variant:"secondary",onClick:()=>{S(null),g(!1)},children:f("common.executionBoard.deleteConfirmCancel")}),e.jsx(Q,{className:"bg-[linear-gradient(135deg,rgba(251,113,133,0.3),rgba(190,24,93,0.26))] text-white shadow-[0_16px_36px_rgba(190,24,93,0.18)]",pending:p===j.id,pendingLabel:f("common.executionBoard.deletingTask"),onClick:()=>void U(j,$),children:f("common.executionBoard.deleteConfirmSubmit")})]})]})}):null]})}const Gw=hh(t=>({selectedUserId:null,selectedGoalId:null,selectedTagIds:[],setUserId:s=>t({selectedUserId:s}),setGoal:s=>t({selectedGoalId:s}),toggleTag:s=>t(i=>({selectedTagIds:i.selectedTagIds.includes(s)?i.selectedTagIds.filter(a=>a!==s):[...i.selectedTagIds,s]})),reset:()=>t({selectedUserId:null,selectedGoalId:null,selectedTagIds:[]})}));function Xw(){var $;const{t}=lt(),s=Je(),i=ut(),a=We(),[n,r]=d.useState((($=s.snapshot.tasks[0])==null?void 0:$.id)??null),[l,o]=d.useState(null),{selectedGoalId:c,selectedUserId:x,selectedTagIds:v,setGoal:u,setUserId:f,toggleTag:h,reset:m}=Gw(),b=s.snapshot.tasks.filter(g=>!(c&&g.goalId!==c||x&&g.userId!==x||v.length>0&&!v.every(C=>g.tagIds.includes(C)))),w=b.find(g=>g.id===n)??s.snapshot.tasks.find(g=>g.id===n)??null,M=l?s.snapshot.tasks.find(g=>g.id===l)??null:null,E=b.filter(g=>g.status==="blocked").length,D=b.filter(g=>g.status==="done").length,j=b.filter(g=>g.status==="focus"||g.status==="in_progress").length,S=s.snapshot.activeTaskRuns.length,p=Mt(s.selectedUserIds),A=async()=>{await Promise.all([a.invalidateQueries({queryKey:["forge-snapshot"]}),a.invalidateQueries({queryKey:["project-board"]}),a.invalidateQueries({queryKey:["task-context"]})])},T=xe({mutationFn:({taskId:g,patch:C})=>Oa(g,C),onSuccess:A}),k=xe({mutationFn:g=>Ul(g),onSuccess:A});return s.snapshot.tasks.length===0?e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-5",children:[e.jsx(qe,{title:"Kanban",description:"Move tasks across the board, start work quickly, and keep your next step visible.",badge:"0 visible tasks",actions:e.jsx(Q,{size:"lg",onClick:()=>s.openStartWork(),children:"Start work"})}),e.jsx(gt,{eyebrow:t("common.kanban.heroEyebrow"),title:t("common.kanban.emptyTitle"),description:t("common.kanban.emptyDescription"),action:e.jsx(Ae,{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(qe,{title:"Kanban",description:"Move tasks between states, start work directly from the board, or open a task when you need to edit it.",badge:`${b.length} visible tasks`,actions:e.jsx(Q,{size:"lg",onClick:()=>s.openStartWork(w?{taskId:w.id}:void 0),children:"Start work"})}),e.jsx(ae,{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(L,{className:"bg-white/[0.08] text-white/72",children:[j," ready or active"]}),e.jsxs(L,{className:"bg-white/[0.08] text-white/72",children:[E," blocked"]}),e.jsxs(L,{className:"bg-white/[0.08] text-white/72",children:[D," done"]}),e.jsxs(L,{className:"bg-white/[0.08] text-white/72",children:[S," live timer",S===1?"":"s"]})]})]})}),e.jsxs(ae,{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(L,{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:()=>u(null),children:"All goals"}),s.snapshot.goals.map(g=>e.jsx("button",{className:`interactive-tap min-w-0 max-w-full rounded-full px-4 py-2 text-sm ${c===g.id?"bg-white/[0.12] text-white":"bg-white/[0.04] text-white/58"}`,onClick:()=>u(c===g.id?null:g.id),children:e.jsx(Xe,{kind:"goal",label:g.title,className:"max-w-full min-w-0",lines:2,labelClassName:"whitespace-normal text-left"})},g.id))]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(L,{tone:"meta",className:"bg-white/[0.08] text-white/60",children:"Owner"}),e.jsx("button",{className:`interactive-tap max-w-full rounded-full px-4 py-2 text-sm ${x===null?"bg-white/[0.12] text-white":"bg-white/[0.04] text-white/58"}`,onClick:()=>f(null),children:"Everyone"}),s.snapshot.users.map(g=>e.jsx("button",{className:`interactive-tap max-w-full rounded-full px-4 py-2 text-sm ${x===g.id?"bg-white/[0.12] text-white":"bg-white/[0.04] text-white/58"}`,onClick:()=>f(x===g.id?null:g.id),children:g.displayName},g.id))]}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[s.snapshot.tags.map(g=>e.jsx("button",{className:`interactive-tap max-w-full rounded-full px-4 py-2 text-sm ${v.includes(g.id)?"bg-white/[0.12] text-white":"bg-white/[0.04] text-white/58"}`,onClick:()=>h(g.id),children:g.name},g.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:m,children:"Reset"})]})]}),b.length===0?e.jsx(gt,{eyebrow:t("common.kanban.heroEyebrow"),title:t("common.kanban.noTasksMatch"),description:"No tasks match the current filters. Reset the filters to bring the full board back.",action:e.jsx(Q,{variant:"secondary",onClick:m,children:"Reset"})}):e.jsx($m,{tasks:b,goals:s.snapshot.goals,tags:s.snapshot.tags,notesSummaryByEntity:s.snapshot.dashboard.notesSummaryByEntity,selectedTaskId:n,onMove:async(g,C)=>{await s.patchTaskStatus(g,C)},onQuickReopenTask:async g=>{await Ql(g),await A()},onDeleteTask:async g=>{await k.mutateAsync(g),r(C=>{var F;return C!==g?C:((F=b.find(z=>z.id!==g))==null?void 0:F.id)??null}),o(C=>C===g?null:C)},onStartTask:async g=>{await s.startTaskNow(g),r(g),await a.invalidateQueries({queryKey:["task-context",g]})},onSelectTask:g=>{r(g)},onOpenTask:g=>{i(`/tasks/${g}`)},onEditTask:g=>{o(g)}}),e.jsx(Jn,{open:M!==null,goals:s.snapshot.goals,projects:s.snapshot.dashboard.projects,tags:s.snapshot.tags,users:s.snapshot.users,editingTask:M,defaultUserId:(M==null?void 0:M.userId)??p,onOpenChange:g=>{g||o(null)},onSubmit:async(g,C)=>{C&&(await T.mutateAsync({taskId:C,patch:g}),o(null))}})]})}function Vw(t){return t.trim().toLowerCase()}function Fa({title:t,description:s,query:i,onQueryChange:a,options:n,selectedOptionIds:r,onSelectedOptionIdsChange:l,resultSummary:o,clearLabel:c="Clear filters",placeholder:x="Search title, alias, domain, source, or filter chip",emptyStateMessage:v="Keep typing to search the library or pick one of the suggested filter chips."}){const[u,f]=d.useState(!1),[h,m]=d.useState(0),b=d.useMemo(()=>r.map(j=>n.find(S=>S.id===j)).filter(Boolean),[n,r]),w=d.useMemo(()=>{const j=Vw(i),S=n.filter(p=>!r.includes(p.id));return j?S.filter(p=>`${p.label} ${p.description??""} ${p.searchText??""}`.toLowerCase().includes(j)).slice(0,12):S.slice(0,12)},[n,i,r]),M=j=>{r.includes(j)||(l([...r,j]),a(""),f(!1),m(0))},E=j=>{l(r.filter(S=>S!==j))},D=()=>{a(""),l([]),m(0),f(!1)};return e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(135deg,rgba(19,30,42,0.92),rgba(9,15,24,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:[t.trim().length>0?e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:t}):null,s.trim().length>0?e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/62",children:s}):null]}),r.length>0||i.trim().length>0?e.jsx("button",{type:"button",onClick:D,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:c}):null]}),e.jsxs("div",{className:"mt-4 rounded-[24px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[b.length>0?e.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:b.map(j=>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:[j.badge??e.jsx("span",{className:"text-sm text-white/78",children:j.label}),e.jsx("button",{type:"button",className:"rounded-full text-white/52 transition hover:text-white",onClick:()=>E(j.id),"aria-label":`Remove ${j.label}`,children:e.jsx(mt,{className:"size-3.5"})})]},j.id))}):null,e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(bt,{className:"size-4 text-white/36"}),e.jsx("input",{value:i,onChange:j=>{a(j.target.value),f(!0),m(0)},onFocus:()=>f(!0),onBlur:()=>window.setTimeout(()=>f(!1),120),onKeyDown:j=>{if(j.key==="Backspace"&&!i&&r.length>0){E(r[r.length-1]);return}if(j.key==="ArrowDown"){j.preventDefault(),f(!0),m(S=>w.length===0?0:Math.min(w.length-1,S+1));return}if(j.key==="ArrowUp"){j.preventDefault(),m(S=>Math.max(0,S-1));return}if(j.key==="Escape"){f(!1);return}j.key==="Enter"&&w[h]&&(j.preventDefault(),M(w[h].id))},placeholder:x,className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]}),u?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:w.length>0?w.map((j,S)=>e.jsx("button",{type:"button",className:re("flex w-full items-start justify-between gap-3 rounded-[18px] px-3 py-2.5 text-left transition",S===h?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>m(S),onMouseDown:p=>p.preventDefault(),onClick:()=>M(j.id),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:j.badge??j.label}),j.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/46",children:j.description}):null]})},j.id)):e.jsx("div",{className:"px-3 py-2.5 text-sm text-white/42",children:v})}):null]})]}),e.jsx("div",{className:"mt-3 text-sm text-white/52",children:o})]})}const Hd=24,Qs=64,nl=360*60,Om=5,Wa=Qs*Om,un=1,Jw=32;function Fm(t){return t.trim().toLowerCase()}function Mn(t){return t>=86400?`${Math.round(t/3600)}h`:t>=3600?`${(t/3600).toFixed(1)}h`:`${Math.max(1,Math.round(t/60))}m`}function Gd(t){return new Intl.DateTimeFormat(void 0,{day:"2-digit",month:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(t))}function pn(t){return new Intl.DateTimeFormat(void 0,{day:"2-digit",month:"2-digit",year:"2-digit"}).format(new Date(t))}function xn(t){return new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:!1}).format(t)}function Xd(t){const s=new Date(t);if(Number.isNaN(s.getTime()))return"";const i=s.getFullYear(),a=String(s.getMonth()+1).padStart(2,"0"),n=String(s.getDate()).padStart(2,"0"),r=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${i}-${a}-${n}T${r}:${l}`}function Vd(t){if(!t.trim())return null;const s=new Date(t);return Number.isNaN(s.getTime())?null:s.toISOString()}function _m(t){return t>=1e3?`${(t/1e3).toFixed(1)} km`:`${Math.round(t)} m`}function li(t){return new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1}).format(new Date(t))}function Jd(t,s){return`${t.toFixed(3)}, ${s.toFixed(3)}`}function xi(t,s,i){const a=s==="start"?t.trip.points[0]??null:t.trip.points[t.trip.points.length-1]??null,n=s==="start"?t.trip.startPlace:t.trip.endPlace,r=(i==null?void 0:i.includeCoordinates)??!0,l=i!=null&&i.useHistoryAnchorFallback&&s==="start"?"Beginning of history":null;return{label:(n==null?void 0:n.label)??l??(r&&a?Jd(a.latitude,a.longitude):s==="start"?"Unknown origin":"Unknown destination"),detail:r&&a&&!n?Jd(a.latitude,a.longitude):li(s==="start"?t.startedAt:t.endedAt)}}function Yw(t){const s=t.trim().toLowerCase();return s==="travel"||s==="trip"||s==="move"}function An(t){if(t.kind==="trip"&&Yw(t.title)){const s=xi(t,"start").label,i=xi(t,"end").label;return`${s} → ${i}`}return t.title}function Yd(t){return t==="left"?24:t==="right"?76:50}function ao(t,s){const i=Math.min(t,nl)/3600,a=s==="stay"?132:124,n=s==="stay"?404:328,r=a+i*44;return Math.max(a,Math.min(n,r))}function Zd(t){return Math.max(250,ao(t.durationSeconds,t.kind)+130)}function jr(t){var s;return{label:t.kind==="stay"?t.stay.label||t.title:t.trip.label||t.title,placeLabel:t.kind==="stay"?((s=t.stay.place)==null?void 0:s.label)??t.placeLabel??"":"",tagsInput:t.tags.join(", "),startedAtInput:Xd(t.startedAt),endedAtInput:Xd(t.endedAt)}}function Rm(t){const s=new Date(t).getHours();return s<6?"night":s<12?"morning":s<18?"afternoon":"evening"}function En(t){return new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"}).format(new Date(t))}function Zw(t){var s,i,a;return Fm([t.kind,An(t),t.subtitle,t.placeLabel??"",...t.tags,En(t.startedAt),En(t.endedAt),Rm(t.startedAt),t.kind==="stay"?((s=t.stay.place)==null?void 0:s.label)??t.stay.label:[t.trip.label,t.trip.activityType,t.trip.travelMode,(i=t.trip.startPlace)==null?void 0:i.label,(a=t.trip.endPlace)==null?void 0:a.label].filter(Boolean).join(" ")].join(" "))}function ey(t){const s=new Map;s.set("kind:stay",{id:"kind:stay",label:"Stay",description:"Stationary spans and place anchors."}),s.set("kind:trip",{id:"kind:trip",label:"Move",description:"Trips and movement connectors."});for(const i of["night","morning","afternoon","evening"])s.set(`time:${i}`,{id:`time:${i}`,label:i[0].toUpperCase()+i.slice(1),description:"Filter by the segment start time."});for(const i of t){for(const a of i.tags)s.set(`tag:${a}`,{id:`tag:${a}`,label:a,description:"Movement tag"});i.placeLabel&&s.set(`place:${i.placeLabel}`,{id:`place:${i.placeLabel}`,label:i.placeLabel,description:"Matched place"})}return[...s.values()].sort((i,a)=>i.label.localeCompare(a.label))}function ty(t,s){return s.every(i=>i==="kind:stay"||i==="kind:trip"?t.kind===i.slice(5):i.startsWith("time:")?Rm(t.startedAt)===i.slice(5):i.startsWith("tag:")?t.tags.includes(i.slice(4)):i.startsWith("place:")?(t.placeLabel??"")===i.slice(6):!0)}function ec(t,s){return t&&{...t,pages:t.pages.map(i=>({...i,segments:i.segments.filter(a=>a.id!==s)}))}}function sy(t,s){const i=t+(Math.sin((t-.5)*Math.PI)+1)*.5-t,a=t-.5,r=.5+(a*(1-s*.64)+a*a*a*s*2.56);return Math.max(0,Math.min(1,r-(i-t)*s*.08))}function iy(t){const s=new Date(t.endedAt).getTime(),i=new Date(t.startedAt).getTime(),a=Math.max(1,s-i),n=new Map;let r=new Date(i);for(r.setMinutes(0,0,0),r.getTime()<=i&&(r=new Date(r.getTime()+36e5));r.getTime()<s;){const l=r.getTime(),o=Math.min(1,Math.max(0,(l-i)/a));n.set(l,{ratio:o,label:r.getHours()===0?pn(r.toISOString()):xn(r),strong:r.getHours()===0}),r=new Date(l+36e5)}return[...n.entries()].sort((l,o)=>l[0]-o[0]).map(([,l])=>l)}function Nr(t){const s=new Date(t);s.setMinutes(0,0,0);const i=s.getTime();return i<=t?i+36e5:i}function ay(t,s){const i=[];if(t.length===0)return i;const a=t[0],n=new Date(a.segment.startedAt).getTime();for(let r=Nr(n-Om*36e5);r<n;r+=36e5){const l=a.boxTop-(n-r)/36e5*Qs,o=new Date(r);i.push({y:l,label:o.getHours()===0?pn(o.toISOString()):xn(o),strong:o.getHours()===0})}for(let r=0;r<t.length;r+=1){const l=t[r],o=l.segment;Math.max(1,new Date(o.endedAt).getTime()-new Date(o.startedAt).getTime());const c=Math.max(0,1-Math.min(1,nl/Math.max(1,o.durationSeconds)));for(const u of iy(o)){const f=o.durationSeconds>nl?sy(u.ratio,c):u.ratio;i.push({y:l.boxTop+f*l.displayHeight,label:u.label,strong:u.strong})}const x=t[r+1]??null;if(x){const u=new Date(o.endedAt).getTime(),f=new Date(x.segment.startedAt).getTime(),h=f-u;if(h>0)for(let m=Nr(u);m<f;m+=36e5){const b=(m-u)/h,w=l.boxBottom+(x.boxTop-l.boxBottom)*b,M=new Date(m);i.push({y:w,label:M.getHours()===0?pn(M.toISOString()):xn(M),strong:M.getHours()===0})}continue}const v=new Date(o.endedAt).getTime();for(let u=Nr(v);u<=s;u+=36e5){const f=l.boxBottom+(u-v)/36e5*Qs,h=new Date(u);i.push({y:f,label:h.getHours()===0?pn(h.toISOString()):xn(h),strong:h.getHours()===0})}}return i.sort((r,l)=>r.y-l.y)}function ny({rows:t,totalHeight:s,scrollTop:i,viewportHeight:a}){const n=Date.now()+un*36e5,r=ay(t,n),l=Qs*6,o=Math.max(0,i-l),c=Math.min(s,i+Math.max(a,Qs*8)+l),x=r.filter(v=>v.y>=o&&v.y<=c);return e.jsxs("div",{className:"pointer-events-none absolute inset-x-0 top-0 overflow-hidden rounded-[30px]",style:{height:`${s}px`},children:[e.jsx("div",{className:"absolute inset-y-0 left-0 w-18 bg-[linear-gradient(90deg,rgba(7,12,22,0.96),rgba(7,12,22,0.42),transparent)]"}),x.map((v,u)=>e.jsxs("div",{className:"absolute inset-x-0",style:{top:`${v.y}px`},children:[e.jsx("div",{className:re("border-t",v.strong?"border-white/14":"border-white/7")}),e.jsx("div",{className:re("absolute left-3 top-0 -translate-y-1/2 font-label text-[9px] tracking-[0.24em]",v.strong?"text-white/38":"text-white/22"),children:v.label})]},`timeline-grid-${u}`))]})}function ry({fromSide:t,toSide:s,height:i,emphasized:a}){const n=Yd(t),r=Yd(s),l=`M ${n} 16 C ${n} ${Math.max(40,i*.26)}, ${r} ${Math.max(70,i*.72)}, ${r} ${i-18}`;return e.jsxs("svg",{viewBox:`0 0 100 ${i}`,className:"absolute inset-x-0 top-0 h-full w-full overflow-visible",preserveAspectRatio:"none",children:[e.jsx("path",{d:l,fill:"none",stroke:a?"rgba(241,246,255,0.18)":"rgba(241,246,255,0.11)",strokeWidth:a?"1.05":"0.85",strokeDasharray:a?"3 10":"2.5 12",strokeLinecap:"round"}),e.jsx("circle",{cx:n,cy:"16",r:"1.5",fill:"rgba(255,255,255,0.26)"}),e.jsx("circle",{cx:r,cy:i-18,r:"1.5",fill:"rgba(255,255,255,0.26)"})]})}function rl({position:t}){return e.jsx("div",{className:re("absolute left-1/2 z-20 flex -translate-x-1/2 items-center justify-center",t==="top"?"-top-3":"-bottom-3"),children:e.jsx("div",{className:"h-6 w-[3px] rounded-full bg-[rgba(160,224,255,0.92)] shadow-[0_0_14px_rgba(126,229,255,0.36)]"})})}function ly({segment:t}){const s=(t==null?void 0:t.kind)==="stay"?t.placeLabel||t.title||null:t?xi(t,"start",{includeCoordinates:!1,useHistoryAnchorFallback:!0}).label:null,i=s||"Beginning of time";return e.jsx("div",{className:"pointer-events-none flex justify-center px-6 py-4",children:e.jsxs("div",{className:"relative w-[min(18rem,calc(100vw-6rem))] overflow-hidden rounded-[26px] border border-[rgba(152,208,255,0.2)] bg-[linear-gradient(180deg,rgba(98,130,238,0.14),rgba(18,34,79,0.14))] shadow-[0_20px_48px_rgba(3,8,20,0.3)]",children:[e.jsx(rl,{position:"bottom"}),e.jsxs("div",{className:"relative z-10 px-5 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(L,{tone:"signal",className:"bg-white/10 text-white/78",children:"Start"}),e.jsx("div",{className:"font-label text-[10px] uppercase tracking-[0.2em] text-white/28",children:"Beginning of history"})]}),e.jsx("div",{className:"mt-5 font-display text-[1.25rem] tracking-[-0.05em] text-white",children:i}),e.jsx("div",{className:"mt-2 font-label text-[10px] uppercase tracking-[0.22em] text-white/30",children:s?"Oldest loaded known stay":"Earliest known anchor"})]})]})})}function oy({segment:t,onEdit:s}){var i;return e.jsxs(ae,{className:"rounded-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(9,14,26,0.98),rgba(5,9,19,0.95))] p-5 shadow-[0_24px_74px_rgba(0,0,0,0.34)]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/40",children:t.kind==="stay"?"Stay detail":"Move detail"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:An(t)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Q,{onClick:s,variant:"ghost",className:"size-9 rounded-full border border-white/10 bg-white/[0.04] text-white/78 hover:bg-white/[0.08]","aria-label":"Edit movement segment",children:e.jsx(Ns,{className:"size-4"})}),e.jsx(Ms,{className:"size-4 text-white/42"})]})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/34",children:"Started"}),e.jsx("div",{className:"mt-2 text-sm text-white/82",children:Gd(t.startedAt)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/34",children:"Ended"}),e.jsx("div",{className:"mt-2 text-sm text-white/82",children:Gd(t.endedAt)})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(L,{tone:"signal",children:Mn(t.durationSeconds)}),t.kind==="trip"?e.jsxs(e.Fragment,{children:[e.jsx(L,{className:"bg-white/[0.08] text-white/74",children:_m(t.trip.distanceMeters)}),t.trip.stops.length>0?e.jsxs(L,{className:"bg-white/[0.08] text-white/74",children:[t.trip.stops.length," stop",t.trip.stops.length===1?"":"s"]}):null]}):null,t.placeLabel?e.jsx(L,{className:"bg-white/[0.08] text-white/74",children:t.placeLabel}):null]}),e.jsx("div",{className:"mt-5 grid gap-3",children:e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/34",children:"Timeline summary"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/76",children:t.kind==="stay"?`Stay block from ${li(t.startedAt)} to ${li(t.endedAt)}.`:`Connector from ${xi(t,"start").label} to ${xi(t,"end").label}.`})]})}),e.jsx("div",{className:"mt-5 flex flex-wrap items-center gap-2 text-sm text-white/56",children:t.kind==="stay"?e.jsxs(e.Fragment,{children:[e.jsx(Nl,{className:"size-4 text-[var(--primary)]"}),((i=t.stay.place)==null?void 0:i.label)??"No canonical place linked yet"]}):e.jsxs(e.Fragment,{children:[e.jsx(On,{className:"size-4 text-[var(--primary)]"}),t.trip.activityType||t.trip.travelMode]})})]})}function dy({open:t,segment:s,draft:i,saving:a,onDraftChange:n,onSave:r,onOpenChange:l}){return e.jsx(Et,{open:t,onOpenChange:l,children:e.jsxs(Lt,{children:[e.jsx(Dt,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.74)] backdrop-blur-sm"}),e.jsxs($t,{className:"fixed left-1/2 top-[8vh] z-50 w-[min(34rem,calc(100vw-1.25rem))] -translate-x-1/2 rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(8,14,28,0.98),rgba(10,16,30,0.95))] p-5 shadow-[0_32px_90px_rgba(0,0,0,0.45)]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(Ot,{className:"font-display text-[1.3rem] tracking-[-0.05em] text-white",children:"Edit movement segment"}),e.jsx(qt,{className:"mt-2 text-sm leading-6 text-white/62",children:s?`Adjust the canonical ${s.kind} metadata, labels, tags, timing, and place attachment in a dedicated form.`:"No segment selected."})]}),e.jsx(Ft,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/72 transition hover:bg-white/[0.08]",children:e.jsx(Ms,{className:"size-4 rotate-45"})})})]}),s&&i?e.jsxs("div",{className:"mt-5 grid gap-4",children:[e.jsxs("label",{className:"grid gap-2 text-sm text-white/78",children:["Label",e.jsx(le,{value:i.label,onChange:o=>n({...i,label:o.target.value})})]}),s.kind==="stay"?e.jsxs("label",{className:"grid gap-2 text-sm text-white/78",children:["Place",e.jsx(le,{value:i.placeLabel,onChange:o=>n({...i,placeLabel:o.target.value}),placeholder:"Home, Office, Riverside path..."})]}):null,e.jsxs("label",{className:"grid gap-2 text-sm text-white/78",children:["Tags",e.jsx(le,{value:i.tagsInput,onChange:o=>n({...i,tagsInput:o.target.value}),placeholder:"movement, social, errand"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2 text-sm text-white/78",children:["Started",e.jsx(le,{type:"datetime-local",value:i.startedAtInput,onChange:o=>n({...i,startedAtInput:o.target.value})})]}),e.jsxs("label",{className:"grid gap-2 text-sm text-white/78",children:["Ended",e.jsx(le,{type:"datetime-local",value:i.endedAtInput,onChange:o=>n({...i,endedAtInput:o.target.value})})]})]})]}):null,e.jsxs("div",{className:"mt-6 flex items-center justify-end gap-3",children:[e.jsx(Ft,{asChild:!0,children:e.jsx(Q,{type:"button",variant:"ghost",className:"border border-white/10 bg-white/[0.04] text-white hover:bg-white/[0.08]",children:"Cancel"})}),e.jsxs(Q,{onClick:r,disabled:!s||!i||a,children:[e.jsx(Yi,{className:"size-4"}),a?"Saving…":"Save changes"]})]})]})]})})}function tc({side:t,vertical:s,emphasized:i=!1}){return e.jsx("div",{className:re("absolute z-10 h-7 w-8 rounded-[12px] border bg-[linear-gradient(180deg,rgba(10,16,28,0.94),rgba(7,12,24,0.88))] shadow-[0_12px_30px_rgba(0,0,0,0.22)] backdrop-blur-sm",i?"border-[rgba(152,208,255,0.34)]":"border-white/10",t==="left"?"left-[8%]":t==="right"?"right-[8%]":"left-1/2 -translate-x-1/2",s==="top"?"top-0":"bottom-0")})}function cy({segment:t,selected:s,onToggle:i,onEdit:a}){const r=t.laneSide==="right"?"left":"right",l=s?r==="right"?-176:176:0,o=ao(t.durationSeconds,t.kind),c=Math.max(240,o+120),x=t.kind==="stay"?"bg-[linear-gradient(180deg,rgba(98,130,238,0.22),rgba(18,34,79,0.22))] border-[rgba(152,208,255,0.24)]":"",v=t.kind==="trip"?{start:xi(t,"start",{includeCoordinates:!1,useHistoryAnchorFallback:!0}),end:xi(t,"end",{includeCoordinates:!1})}:null;return e.jsxs("div",{className:"relative w-full px-6",children:[e.jsx("div",{className:"absolute inset-y-0 left-1/2 w-px -translate-x-1/2 bg-[linear-gradient(180deg,rgba(255,255,255,0.02),rgba(255,255,255,0.08),rgba(255,255,255,0.02))]"}),e.jsxs("div",{className:"relative",style:{minHeight:`${c}px`},children:[t.kind==="trip"?e.jsxs(Kt.div,{layout:!0,animate:{x:l},transition:{type:"spring",stiffness:240,damping:30},className:"absolute inset-x-0 top-8 h-[calc(100%-2rem)] z-10",children:[v&&s?e.jsxs(e.Fragment,{children:[e.jsx(tc,{side:"center",vertical:"top",emphasized:!0}),e.jsx(tc,{side:"center",vertical:"bottom",emphasized:!0})]}):null,e.jsx(ry,{fromSide:"center",toSide:"center",height:o,emphasized:s}),e.jsxs("button",{type:"button",onClick:i,className:re("group absolute top-1/2 max-w-[min(9rem,calc(100vw-9rem))] -translate-y-1/2 rounded-[18px] border border-white/8 bg-[linear-gradient(180deg,rgba(9,14,24,0.58),rgba(8,12,22,0.42))] px-3 py-2 text-left shadow-[0_12px_24px_rgba(0,0,0,0.14)] backdrop-blur-sm transition hover:border-white/14","left-1/2 -translate-x-1/2",s?"ring-1 ring-[rgba(126,229,255,0.38)]":""),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-label text-[10px] uppercase tracking-[0.18em] text-white/34",children:"Move"}),e.jsx("div",{className:"text-[11px] tracking-[0.18em] text-white/44",children:Mn(t.durationSeconds)})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsx(L,{className:"bg-white/[0.08] text-white/74",children:_m(t.trip.distanceMeters)}),t.trip.stops.length>0?e.jsxs(L,{className:"bg-white/[0.08] text-white/74",children:[t.trip.stops.length," stop",t.trip.stops.length===1?"":"s"]}):null]}),e.jsxs("div",{className:"mt-2 font-label text-[9px] uppercase tracking-[0.22em] text-white/28",children:[li(t.startedAt)," → ",li(t.endedAt)]})]})]}):e.jsx(Kt.div,{layout:!0,animate:{x:l},transition:{type:"spring",stiffness:260,damping:28},className:"absolute top-8 left-1/2 z-10 w-[min(22rem,calc(100vw-5rem))] -translate-x-1/2",children:e.jsxs("button",{type:"button",onClick:i,className:re("group relative w-full overflow-hidden rounded-[30px] border text-left shadow-[0_26px_68px_rgba(3,8,20,0.42)] transition",x,s?"ring-1 ring-[rgba(126,229,255,0.42)]":"hover:border-white/22"),style:{minHeight:`${o}px`},children:[e.jsx(rl,{position:"top"}),e.jsx(rl,{position:"bottom"}),e.jsxs("div",{className:"relative z-10 flex h-full flex-col justify-between p-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(L,{tone:"signal",className:"bg-white/10 text-white/82",children:"Stay"}),e.jsx("div",{className:"text-xs tracking-[0.18em] text-white/46",children:Mn(t.durationSeconds)})]}),e.jsx("div",{className:"mt-auto pt-14",children:e.jsxs("div",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-white/34",children:[li(t.startedAt)," → ",li(t.endedAt)]})})]})]})}),s?e.jsx(Kt.div,{layout:!0,initial:{opacity:0,x:r==="right"?28:-28},animate:{opacity:1,x:0},exit:{opacity:0,x:r==="right"?28:-28},className:re("absolute top-6 w-[min(22rem,calc(100vw-4rem))]",r==="right"?"right-[3%]":"left-[3%]"),children:e.jsx(oy,{segment:t,onEdit:a})}):null]})]})}function hy({userIds:t=[]}){const s=We(),i=d.useRef(null),a=d.useRef(null),n=d.useRef(!1),r=d.useRef(!1),l=d.useRef(null),[o,c]=d.useState(null),[x,v]=d.useState({}),[u,f]=d.useState(null),[h,m]=d.useState(!1),[b,w]=d.useState(!1),[M,E]=d.useState(""),[D,j]=d.useState([]),[S,p]=d.useState(0),[A,T]=d.useState(0),k=()=>{const y=i.current;y&&(p(y.scrollTop),T(y.clientHeight))},$=Wr({queryKey:["forge-movement-life-timeline",...t],initialPageParam:null,queryFn:({pageParam:y})=>sd({before:y??void 0,limit:Hd,userIds:t}).then(P=>P.movement),getNextPageParam:y=>y.nextCursor??void 0,retry:!1,refetchOnWindowFocus:!1}),g=Wr({queryKey:["forge-movement-life-timeline-data",...t],initialPageParam:null,queryFn:({pageParam:y})=>sd({before:y??void 0,includeInvalid:!0,limit:Hd,userIds:t}).then(P=>P.movement),getNextPageParam:y=>y.nextCursor??void 0,retry:!1,refetchOnWindowFocus:!1}),C=d.useMemo(()=>{var y;return((y=$.data)==null?void 0:y.pages.flatMap(P=>P.segments))??[]},[$.data]),F=d.useMemo(()=>{var y;return((y=g.data)==null?void 0:y.pages.flatMap(P=>P.segments))??[]},[g.data]),z=d.useMemo(()=>{var y;return((y=$.data)==null?void 0:y.pages.reduce((P,q)=>Math.max(P,q.invalidSegmentCount??0),0))??0},[$.data]),J=d.useMemo(()=>[...C].reverse(),[C]),O=d.useMemo(()=>[...F].reverse(),[F]),_=d.useMemo(()=>{var pe;const y=(pe=J[J.length-1])==null?void 0:pe.endedAt;if(!y)return Qs*un;const P=Date.now()+un*36e5,q=new Date(y).getTime();return Math.max(Qs*un,(P-q)/36e5*Qs)},[J]),B=d.useMemo(()=>{let y=Wa;return J.map(P=>{const q=ao(P.durationSeconds,P.kind),pe=Zd(P),ee=y,Y=ee+Jw,R=Y+q;return y+=pe,{segment:P,rowStart:ee,rowHeight:pe,displayHeight:q,boxTop:Y,boxBottom:R}})},[J]);d.useEffect(()=>{h&&(!g.hasNextPage||g.isFetchingNextPage||g.fetchNextPage())},[h,g.fetchNextPage,g.hasNextPage,g.isFetchingNextPage]);const K=Qi({count:J.length,getScrollElement:()=>i.current,estimateSize:y=>Zd(J[y]??J[0]),overscan:6,paddingStart:Wa,paddingEnd:_});d.useEffect(()=>{const y=J.at(-1);!r.current&&y&&(r.current=!0,c(y.id))},[J]),d.useEffect(()=>{if(!n.current&&J.length>0){n.current=!0,requestAnimationFrame(()=>{K.scrollToIndex(J.length-1,{align:"center"}),requestAnimationFrame(()=>{k()})});return}if(l.current&&J.length>l.current.count&&i.current){const y=l.current;l.current=null,requestAnimationFrame(()=>{const P=i.current;if(!P)return;const q=K.getTotalSize()-y.size;P.scrollTop+=q,k()})}},[K,J.length]),d.useEffect(()=>{if(!i.current)return;const P=()=>{k()};return P(),window.addEventListener("resize",P),()=>window.removeEventListener("resize",P)},[]),d.useEffect(()=>{if(!o)return;const y=J.find(P=>P.id===o);y&&v(P=>P[o]?P:{...P,[o]:jr(y)})},[J,o]);const Z=xe({mutationFn:async y=>{var Y;const P=x[y.id]??jr(y),q=P.tagsInput.split(",").map(R=>R.trim()).filter(Boolean),pe=Vd(P.startedAtInput)??y.startedAt,ee=Vd(P.endedAtInput)??y.endedAt;if(y.kind==="stay"){let R;const X=P.placeLabel.trim();X&&X!==(((Y=y.stay.place)==null?void 0:Y.label)??y.placeLabel??"")&&(R=(await qh({label:X,latitude:y.stay.centerLatitude,longitude:y.stay.centerLongitude,radiusMeters:y.stay.radiusMeters,categoryTags:q.length>0?q:["movement"]},t)).place.id),await Wf(y.stay.id,{label:P.label.trim(),tags:q,startedAt:pe,endedAt:ee,...R?{placeId:R}:{}})}else await Gf(y.trip.id,{label:P.label.trim(),tags:q,startedAt:pe,endedAt:ee})},onSuccess:async()=>{await Promise.all([s.invalidateQueries({queryKey:["forge-movement-life-timeline"]}),s.invalidateQueries({queryKey:["forge-movement-life-timeline-data"]}),s.invalidateQueries({queryKey:["forge-movement-day"]}),s.invalidateQueries({queryKey:["forge-movement-month"]}),s.invalidateQueries({queryKey:["forge-movement-all-time"]}),s.invalidateQueries({queryKey:["forge-movement-places"]}),s.invalidateQueries({queryKey:["forge-psyche-self-observation-calendar"]})])}}),U=xe({mutationFn:async y=>{if(y.kind==="stay"){await Hf(y.stay.id);return}await Xf(y.trip.id)},onSuccess:async(y,P)=>{c(q=>q===P.id?null:q),f(q=>q===P.id?null:q),s.setQueryData(["forge-movement-life-timeline",...t],q=>ec(q,P.id)),s.setQueryData(["forge-movement-life-timeline-data",...t],q=>ec(q,P.id)),await Promise.all([s.invalidateQueries({queryKey:["forge-movement-life-timeline"]}),s.invalidateQueries({queryKey:["forge-movement-life-timeline-data"]}),s.invalidateQueries({queryKey:["forge-movement-day"]}),s.invalidateQueries({queryKey:["forge-movement-month"]}),s.invalidateQueries({queryKey:["forge-movement-all-time"]}),s.invalidateQueries({queryKey:["forge-movement-selection"]}),s.invalidateQueries({queryKey:["forge-psyche-self-observation-calendar"]})])}}),I=d.useMemo(()=>ey(O),[O]),G=d.useMemo(()=>{const y=Fm(M);return[...O].sort((P,q)=>new Date(q.endedAt).getTime()-new Date(P.endedAt).getTime()).filter(P=>(y.length===0||Zw(P).includes(y))&&ty(P,D))},[O,M,D]),W=d.useMemo(()=>O.length===0?"No movement records loaded yet.":G.length===O.length&&M.trim().length===0&&D.length===0?`${O.length} loaded movement records visible`:`${G.length} of ${O.length} loaded records visible`,[O.length,G.length,M,D.length]),ne=Qi({count:G.length,getScrollElement:()=>a.current,estimateSize:()=>136,overscan:8}),de=()=>{const y=i.current;y&&(p(y.scrollTop),T(y.clientHeight),!(!$.hasNextPage||$.isFetchingNextPage)&&y.scrollTop<=960&&(l.current={count:J.length,size:K.getTotalSize()},$.fetchNextPage()))};if($.isPending)return e.jsx(It,{eyebrow:"Movement",title:"Loading life timeline",description:"Reconstructing the longer road of stays, moves, and places.",columns:1,blocks:6});if($.isError)return e.jsx(ze,{eyebrow:"Movement",error:$.error,onRetry:()=>void $.refetch()});const we=K.getVirtualItems(),Ne=u?J.find(y=>y.id===u)??null:null,H=Ne?x[Ne.id]??jr(Ne):null,me=Math.max(B.length>0?B[B.length-1].rowStart+B[B.length-1].rowHeight+_:Wa+_,A>0?A+260:960,Wa+_);return e.jsxs("section",{className:"grid gap-4",children:[e.jsxs(ae,{className:"overflow-hidden rounded-[34px] border border-white/8 bg-[radial-gradient(circle_at_top,rgba(88,182,255,0.08),transparent_28%),linear-gradient(180deg,rgba(4,8,17,0.99),rgba(5,9,18,0.97))] p-4",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3 px-1",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.22em] text-white/34",children:"Movement"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-8 rounded-full border border-white/10 bg-white/[0.04] px-3 text-white/72 hover:bg-white/[0.08] hover:text-white",onClick:()=>m(!0),children:[e.jsx(ph,{className:"size-3.5"}),"View data"]}),z>0?e.jsxs(L,{className:"bg-amber-500/10 text-amber-100",children:[z," invalid hidden"]}):null,e.jsxs(L,{className:"bg-white/[0.06] text-white/68",children:[J.length," loaded"]})]})]}),e.jsxs("div",{ref:i,onScroll:de,className:"relative h-[82vh] overflow-auto rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(4,7,15,0.98),rgba(6,10,18,0.96))]",children:[e.jsx(ny,{rows:B,totalHeight:me,scrollTop:S,viewportHeight:A}),e.jsxs("div",{className:"relative",style:{height:`${me}px`},children:[e.jsx(ly,{segment:J[0]??null}),we.map(y=>{const P=J[y.index];return P?e.jsx("div",{"data-index":y.index,ref:K.measureElement,className:"absolute left-0 top-0 w-full",style:{transform:`translateY(${y.start}px)`},children:e.jsx(cy,{segment:P,selected:o===P.id,onToggle:()=>c(q=>q===P.id?null:P.id),onEdit:()=>f(P.id)})},P.id):null})]})]})]}),e.jsx(dy,{open:Ne!==null,segment:Ne,draft:H,saving:Z.isPending,onDraftChange:y=>{Ne&&v(P=>({...P,[Ne.id]:y}))},onSave:()=>{Ne&&Z.mutateAsync(Ne,{onSuccess:()=>{f(null),b&&(w(!1),m(!0))}})},onOpenChange:y=>{y||(f(null),b&&(w(!1),m(!0)))}}),e.jsx(bs,{open:h,onOpenChange:y=>{m(y),y||b||(E(""),j([]))},eyebrow:"Movement data",title:"View data",description:"",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsx(Fa,{title:"",description:"",query:M,onQueryChange:E,options:I,selectedOptionIds:D,onSelectedOptionIdsChange:j,resultSummary:W,placeholder:"Search movement labels, places, times, tags, or add time and kind filters",emptyStateMessage:"Keep typing or pick filters to narrow the movement history."}),e.jsxs(ae,{className:"grid gap-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Data records"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(L,{tone:"meta",children:W}),z>0?e.jsxs(L,{className:"bg-amber-500/10 text-amber-100",children:[z," invalid hidden included"]}):null,g.hasNextPage?e.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"h-8 rounded-full border border-white/10 bg-white/[0.04] px-3 text-white/70",pending:g.isFetchingNextPage,pendingLabel:"Loading…",onClick:()=>void g.fetchNextPage(),children:"Load older"}):null]})]}),e.jsx("div",{ref:a,className:"h-[36rem] overflow-y-auto rounded-[24px] border border-white/8 bg-white/[0.03]",children:G.length===0?e.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center text-sm leading-6 text-white/50",children:"No movement record matches the current search. Clear filters or load older timeline history."}):e.jsx("div",{className:"relative w-full",style:{height:`${ne.getTotalSize()}px`},children:ne.getVirtualItems().map(y=>{var q;const P=G[y.index];return e.jsx("div",{ref:ne.measureElement,"data-index":y.index,className:"absolute left-0 top-0 w-full px-3 py-2",style:{transform:`translateY(${y.start}px)`},children:e.jsxs("div",{className:"flex items-start gap-2 rounded-[18px] border border-white/8 bg-white/[0.04] px-3 py-2.5",children:[e.jsx("button",{type:"button",className:"min-w-0 flex-1 text-left transition hover:opacity-100",onClick:()=>{w(!0),m(!1),f(P.id)},children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[P.kind==="stay"?e.jsx(Nl,{className:"size-3.5 shrink-0 text-[var(--primary)]"}):e.jsx(On,{className:"size-3.5 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"truncate text-sm font-medium",children:An(P)})]}),e.jsxs("div",{className:"mt-1 text-xs text-white/56",children:[En(P.startedAt)," →"," ",En(P.endedAt)]})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap justify-end gap-1.5",children:[e.jsx(L,{tone:P.kind==="trip"?"signal":"meta",children:P.kind==="trip"?"Move":"Stay"}),e.jsx(L,{tone:"meta",children:Mn(P.durationSeconds)}),P.isInvalid?e.jsx(L,{className:"bg-amber-500/10 text-amber-100",children:"Invalid"}):null,P.placeLabel?e.jsx(L,{tone:"default",children:P.placeLabel}):null]})]})}),e.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"h-8 shrink-0 rounded-full border border-rose-400/22 bg-rose-500/10 px-2.5 text-rose-100 hover:bg-rose-500/18",pending:U.isPending&&((q=U.variables)==null?void 0:q.id)===P.id,pendingLabel:"",onClick:()=>{window.confirm(`Delete ${An(P)} and keep it deleted across companion sync?`)&&U.mutateAsync(P)},children:e.jsx(ct,{className:"size-3.5"})})]})},P.id)})})})]})]})})]})}function my(t){return new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short"}).format(new Date(t))}function uy(t,s){const i=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"});return`${i.format(new Date(t))} - ${i.format(new Date(s))}`}function Rs(t){return t>=3600?`${(t/3600).toFixed(1)}h`:`${Math.round(t/60)}m`}function ai(t){return t>=1e3?`${(t/1e3).toFixed(1)} km`:`${Math.round(t)} m`}function py(t,s){return t==="distanceMeters"?ai(s):t==="caloriesKcal"?`${Math.round(s)} kcal`:Rs(s)}function zm(t){return t.trim().toLowerCase()}function ir(t){const s=new Date(t).getHours();return s<6?"night":s<12?"morning":s<18?"afternoon":"evening"}function no(t){return new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"}).format(new Date(t))}function xy(t){const s=new Date(t);return Number.isNaN(s.getTime())?"":new Date(s.getTime()-s.getTimezoneOffset()*6e4).toISOString().slice(0,16)}function gy(t){const s=t.trim();if(!s)return null;const i=new Date(s);return Number.isNaN(i.getTime())?null:i.toISOString()}function kr(t){return{recordedAt:xy(t.recordedAt),latitude:String(t.latitude),longitude:String(t.longitude),accuracyMeters:t.accuracyMeters!=null?String(t.accuracyMeters):"",altitudeMeters:t.altitudeMeters!=null?String(t.altitudeMeters):"",speedMps:t.speedMps!=null?String(t.speedMps):"",isStopAnchor:t.isStopAnchor}}function fy(t){return zm([no(t.recordedAt),t.externalUid,t.isStopAnchor?"stop anchor stop":"path trace point",t.accuracyMeters!=null?`${Math.round(t.accuracyMeters)} meters accuracy`:"",ir(t.recordedAt)].join(" "))}function by(t){const s=new Map;return s.set("anchor:stop",{id:"anchor:stop",label:"Stop anchors",description:"Only the canonical pause anchors",badge:e.jsx(L,{tone:"meta",children:"Stop anchors"})}),s.set("anchor:path",{id:"anchor:path",label:"Path points",description:"Non-anchor trace points",badge:e.jsx(L,{tone:"meta",children:"Path points"})}),s.set("accuracy:precise",{id:"accuracy:precise",label:"Precise",description:"GPS accuracy below 20m",badge:e.jsx(L,{tone:"meta",children:"Precise"})}),s.set("accuracy:loose",{id:"accuracy:loose",label:"Loose accuracy",description:"GPS accuracy at or above 20m",badge:e.jsx(L,{tone:"meta",children:"Loose accuracy"})}),t.forEach(i=>{const a=ir(i.recordedAt);s.has(`time:${a}`)||s.set(`time:${a}`,{id:`time:${a}`,label:a,description:"Recorded during this time band",badge:e.jsx(L,{tone:"meta",className:"capitalize",children:a})})}),[...s.values()]}function vy(t,s){return s.every(i=>i==="anchor:stop"?t.isStopAnchor:i==="anchor:path"?!t.isStopAnchor:i==="accuracy:precise"?t.accuracyMeters!=null&&t.accuracyMeters<20:i==="accuracy:loose"?t.accuracyMeters==null||t.accuracyMeters>=20:i.startsWith("time:")?ir(t.recordedAt)===i.slice(5):!0)}function wy(t){if(t.length===0)return[];const s=Math.min(...t.map(o=>o.latitude)),i=Math.max(...t.map(o=>o.latitude)),a=Math.min(...t.map(o=>o.longitude)),n=Math.max(...t.map(o=>o.longitude)),r=Math.max(i-s,1e-4),l=Math.max(n-a,1e-4);return t.map(o=>({x:12+(o.longitude-a)/l*76,y:12+(1-(o.latitude-s)/r)*76}))}function yy({curve:t,startLabel:s,endLabel:i,stopLabels:a}){const n=t.map((r,l)=>`${l===0?"M":"Q"} ${r.x} ${r.y}`).join(" ");return e.jsxs(ae,{className:"overflow-hidden rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top,rgba(114,204,255,0.18),transparent_44%),linear-gradient(180deg,rgba(6,11,26,0.98),rgba(8,14,28,0.92))] p-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Stylized trajectory"}),e.jsx(it,{content:"This graph is a softened trip trace. It emphasizes rhythm, stops, and endpoints instead of raw GPS jitter."})]}),e.jsx("div",{className:"mt-2 text-sm text-white/64",children:"A softened path that prioritizes rhythm, stops, and landmarks over raw map noise."})]}),e.jsxs(L,{tone:"signal",children:[s," → ",i]})]}),e.jsxs("div",{className:"mt-5 rounded-[26px] border border-white/8 bg-[rgba(255,255,255,0.03)] p-4",children:[e.jsxs("svg",{viewBox:"0 0 100 60",className:"h-48 w-full",children:[e.jsx("defs",{children:e.jsxs("filter",{id:"movementGlow",children:[e.jsx("feGaussianBlur",{stdDeviation:"1.8",result:"blur"}),e.jsxs("feMerge",{children:[e.jsx("feMergeNode",{in:"blur"}),e.jsx("feMergeNode",{in:"SourceGraphic"})]})]})}),e.jsx("path",{d:n,fill:"none",stroke:"rgba(255,255,255,0.86)",strokeWidth:"1.5",strokeDasharray:"2.8 2.8",filter:"url(#movementGlow)"}),t.map((r,l)=>e.jsx("g",{children:e.jsx("circle",{cx:r.x,cy:r.y,r:l===0||l===t.length-1?2.6:1.6,fill:l===0||l===t.length-1?"#ffffff":"rgba(170,229,255,0.96)"})},`${r.x}-${r.y}-${l}`))]}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:a.map(r=>e.jsx(L,{tone:"default",className:"bg-white/[0.06] text-white/74",children:r},r))})]})]})}function jy({points:t}){const s=wy(t),i=s.map((a,n)=>`${n===0?"M":"L"} ${a.x} ${a.y}`).join(" ");return e.jsxs(ae,{className:"rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(8,13,25,0.95),rgba(10,17,30,0.88))] p-5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Exact path"}),e.jsx(it,{content:"This keeps the recent raw location points. Use it when you want the literal recorded trace instead of the cleaned movement graph."})]}),e.jsx("div",{className:"mt-2 text-sm text-white/62",children:"Recent raw points preserved by the companion before long-term simplification."}),e.jsx("div",{className:"mt-5 rounded-[24px] border border-white/8 bg-[rgba(255,255,255,0.03)] p-3",children:e.jsxs("svg",{viewBox:"0 0 100 100",className:"h-52 w-full",children:[e.jsx("rect",{x:"0",y:"0",width:"100",height:"100",rx:"18",fill:"rgba(255,255,255,0.02)"}),e.jsx("path",{d:i,fill:"none",stroke:"rgba(92,225,230,0.95)",strokeWidth:"1.6"}),s.map((a,n)=>e.jsx("circle",{cx:a.x,cy:a.y,r:n===0||n===s.length-1?2:1.1,fill:n===0||n===s.length-1?"#ffffff":"rgba(92,225,230,0.9)"},`${a.x}-${a.y}-${n}`))]})})]})}function Ny({point:t,draft:s,saving:i,deleting:a,onDraftChange:n,onSave:r,onDelete:l}){return e.jsxs(ae,{className:"grid gap-4 rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(12,18,32,0.98),rgba(8,13,24,0.98))] p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Datapoint editor"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:no(t.recordedAt)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Editing here changes the canonical trip path in Forge. Deleting the point also tombstones it so the companion will not re-upload it on the next sync."})]}),e.jsx(L,{tone:t.isStopAnchor?"signal":"meta",children:t.isStopAnchor?"Stop anchor":"Path point"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/40",children:"Recorded at"}),e.jsx(le,{type:"datetime-local",value:s.recordedAt,onChange:o=>n({recordedAt:o.target.value})})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/40",children:"Speed (m/s)"}),e.jsx(le,{value:s.speedMps,onChange:o=>n({speedMps:o.target.value}),placeholder:"Optional"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/40",children:"Latitude"}),e.jsx(le,{value:s.latitude,onChange:o=>n({latitude:o.target.value})})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/40",children:"Longitude"}),e.jsx(le,{value:s.longitude,onChange:o=>n({longitude:o.target.value})})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/40",children:"Accuracy (m)"}),e.jsx(le,{value:s.accuracyMeters,onChange:o=>n({accuracyMeters:o.target.value}),placeholder:"Optional"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/40",children:"Altitude (m)"}),e.jsx(le,{value:s.altitudeMeters,onChange:o=>n({altitudeMeters:o.target.value}),placeholder:"Optional"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(Q,{variant:"ghost",className:re("h-10 rounded-full border px-4",s.isStopAnchor?"border-[var(--primary)] bg-[var(--primary)]/16 text-white":"border-white/10 bg-white/[0.04] text-white/64"),onClick:()=>n({isStopAnchor:!s.isStopAnchor}),children:[e.jsx(On,{className:"mr-2 size-4"}),s.isStopAnchor?"Stop anchor":"Path point"]}),e.jsxs("div",{className:"text-sm text-white/50",children:["External id: ",e.jsx("span",{className:"text-white/72",children:t.externalUid})]})]}),e.jsxs("div",{className:"flex flex-wrap justify-between gap-3 border-t border-white/8 pt-4",children:[e.jsxs(Q,{variant:"ghost",className:"h-10 rounded-full border border-[rgba(255,122,122,0.26)] bg-[rgba(255,122,122,0.08)] px-4 text-[rgba(255,198,198,0.94)] hover:bg-[rgba(255,122,122,0.14)]",onClick:l,disabled:a||i,children:[e.jsx(ct,{className:"mr-2 size-4"}),a?"Deleting…":"Delete datapoint"]}),e.jsxs(Q,{onClick:r,disabled:i||a,children:[e.jsx(Yi,{className:"mr-2 size-4"}),i?"Saving…":"Save datapoint"]})]})]})}function ky({open:t,onOpenChange:s,place:i,onSave:a}){const[n,r]=d.useState({label:(i==null?void 0:i.label)??"",latitude:String((i==null?void 0:i.latitude)??""),longitude:String((i==null?void 0:i.longitude)??""),radiusMeters:String((i==null?void 0:i.radiusMeters)??100),categoryTags:((i==null?void 0:i.categoryTags)??[]).join(", ")});return d.useEffect(()=>{r({label:(i==null?void 0:i.label)??"",latitude:String((i==null?void 0:i.latitude)??""),longitude:String((i==null?void 0:i.longitude)??""),radiusMeters:String((i==null?void 0:i.radiusMeters)??100),categoryTags:((i==null?void 0:i.categoryTags)??[]).join(", ")})},[i]),e.jsx(Et,{open:t,onOpenChange:s,children:e.jsxs(Lt,{children:[e.jsx(Dt,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.74)] backdrop-blur-sm"}),e.jsxs($t,{className:"fixed left-1/2 top-[8vh] z-50 w-[min(32rem,calc(100vw-1.25rem))] -translate-x-1/2 rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(8,14,28,0.98),rgba(10,16,30,0.95))] p-5 shadow-[0_32px_90px_rgba(0,0,0,0.45)]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(Ot,{className:"font-display text-[1.3rem] tracking-[-0.05em] text-white",children:i?`Edit ${i.label}`:"New known place"}),e.jsx(qt,{className:"mt-1 text-sm text-white/58",children:"Define life landmarks once so the companion and web views can reason about stays and trips consistently."})]}),e.jsx(Ft,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white",children:e.jsx(mt,{className:"size-4"})})})]}),e.jsxs("div",{className:"mt-5 grid gap-3",children:[e.jsx(le,{value:n.label,onChange:l=>r(o=>({...o,label:l.target.value})),placeholder:"Home, Main Office, Riverside path..."}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(le,{value:n.latitude,onChange:l=>r(o=>({...o,latitude:l.target.value})),placeholder:"Latitude"}),e.jsx(le,{value:n.longitude,onChange:l=>r(o=>({...o,longitude:l.target.value})),placeholder:"Longitude"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[10rem_minmax(0,1fr)]",children:[e.jsx(le,{value:n.radiusMeters,onChange:l=>r(o=>({...o,radiusMeters:l.target.value})),placeholder:"Radius meters"}),e.jsx(le,{value:n.categoryTags,onChange:l=>r(o=>({...o,categoryTags:l.target.value})),placeholder:"home, gym, holiday, parents-house"})]})]}),e.jsxs("div",{className:"mt-5 flex justify-end gap-2",children:[e.jsx(Q,{variant:"ghost",onClick:()=>s(!1),className:"border border-white/10 bg-white/[0.04]",children:"Cancel"}),e.jsx(Q,{onClick:()=>void a({id:i==null?void 0:i.id,label:n.label,latitude:Number(n.latitude),longitude:Number(n.longitude),radiusMeters:Number(n.radiusMeters),categoryTags:n.categoryTags.split(",").map(l=>l.trim()).filter(Boolean)}).then(()=>s(!1)),children:"Save place"})]})]})]})})}function Sy(){var Ie,te,ce,Se,he,Ge,De;const t=Je(),s=We(),i=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],[a,n]=d.useState("life"),[r,l]=d.useState(new Date().toISOString().slice(0,10)),[o,c]=d.useState(new Date().toISOString().slice(0,7)),[x,v]=d.useState(null),[u,f]=d.useState(!1),[h,m]=d.useState(!1),[b,w]=d.useState(""),[M,E]=d.useState([]),[D,j]=d.useState(null),[S,p]=d.useState(null),[A,T]=d.useState({stayIds:[],tripIds:[]}),[k,$]=d.useState(!1),[g,C]=d.useState(null),[F,z]=d.useState(""),[J,O]=d.useState("distanceMeters"),_=d.useRef(null),B=fe({queryKey:["forge-movement-day",r,...i],queryFn:async()=>(await _f({date:r,userIds:i})).movement}),K=fe({queryKey:["forge-movement-month",o,...i],queryFn:async()=>(await Rf({month:o,userIds:i})).movement}),Z=fe({queryKey:["forge-movement-all-time",...i],queryFn:async()=>(await zf(i)).movement}),U=fe({queryKey:["forge-movement-settings",...i],queryFn:async()=>(await qf(i)).settings}),I=fe({queryKey:["forge-movement-places",...i],queryFn:async()=>(await Kf(i)).places}),G=fe({queryKey:["forge-movement-trip",x],queryFn:async()=>x?(await Qf(x)).movement:null,enabled:!!x}),W=fe({queryKey:["forge-movement-selection",r,A.stayIds.join(","),A.tripIds.join(","),...i],queryFn:async()=>(await Yf({...A,userIds:i})).movement,enabled:A.stayIds.length>0||A.tripIds.length>0}),ne=xe({mutationFn:async ue=>Bf({trackingEnabled:ue},i),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-movement-settings"]}),await s.invalidateQueries({queryKey:["forge-movement-day"]})}}),de=xe({mutationFn:async ue=>ue.id?Uf(ue.id,ue):qh(ue,i),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-movement-places"]}),await s.invalidateQueries({queryKey:["forge-movement-day"]}),await s.invalidateQueries({queryKey:["forge-movement-all-time"]})}}),we=xe({mutationFn:async ue=>Vf(ue.tripId,ue.pointId,ue.patch),onSuccess:async(ue,Fe)=>{await s.invalidateQueries({queryKey:["forge-movement-trip",Fe.tripId]}),await s.invalidateQueries({queryKey:["forge-movement-day"]}),await s.invalidateQueries({queryKey:["forge-movement-month"]}),await s.invalidateQueries({queryKey:["forge-movement-all-time"]}),await s.invalidateQueries({queryKey:["forge-movement-selection"]})}}),Ne=xe({mutationFn:async ue=>Jf(ue.tripId,ue.pointId),onSuccess:async(ue,Fe)=>{await s.invalidateQueries({queryKey:["forge-movement-trip",Fe.tripId]}),await s.invalidateQueries({queryKey:["forge-movement-day"]}),await s.invalidateQueries({queryKey:["forge-movement-month"]}),await s.invalidateQueries({queryKey:["forge-movement-all-time"]}),await s.invalidateQueries({queryKey:["forge-movement-selection"]})}}),H=d.useMemo(()=>{const ue=I.data??[],Fe=F.trim().toLowerCase();return Fe?ue.filter(dt=>[dt.label,...dt.aliases,...dt.categoryTags].join(" ").toLowerCase().includes(Fe)):ue},[F,I.data]),me=d.useMemo(()=>{var ue;return by(((ue=G.data)==null?void 0:ue.trip.points)??[])},[(Ie=G.data)==null?void 0:Ie.trip.points]),y=d.useMemo(()=>{var dt;const ue=((dt=G.data)==null?void 0:dt.trip.points)??[],Fe=zm(b);return[...ue].sort((yt,wt)=>new Date(wt.recordedAt).getTime()-new Date(yt.recordedAt).getTime()).filter(yt=>(Fe.length===0||fy(yt).includes(Fe))&&vy(yt,M))},[b,M,(te=G.data)==null?void 0:te.trip.points]),P=d.useMemo(()=>{var Fe;const ue=((Fe=G.data)==null?void 0:Fe.trip.points.length)??0;return ue===0?"No raw datapoints on this trip yet.":y.length===ue&&b.trim().length===0&&M.length===0?`${ue} datapoints visible`:`${y.length} of ${ue} datapoints visible`},[y.length,b,M.length,(ce=G.data)==null?void 0:ce.trip.points.length]),q=Qi({count:y.length,getScrollElement:()=>_.current,estimateSize:()=>96,overscan:8}),pe=y.find(ue=>ue.id===D)??((Se=G.data)==null?void 0:Se.trip.points.find(ue=>ue.id===D))??y[0]??((he=G.data)==null?void 0:he.trip.points[0])??null;if(d.useEffect(()=>{if(h){if(!pe){j(null),p(null);return}j(pe.id),p(kr(pe))}},[pe,h]),d.useEffect(()=>{w(""),E([]),j(null),p(null),m(!1)},[x]),B.isLoading||K.isLoading||Z.isLoading||U.isLoading||I.isLoading)return e.jsx(It,{eyebrow:"Movement",title:"Loading movement workspace",description:"Reconstructing stays, trips, and place intelligence across Forge.",columns:2,blocks:8});if(B.isError||K.isError||Z.isError||U.isError||I.isError||!B.data||!K.data||!Z.data||!U.data)return e.jsx(ze,{eyebrow:"Movement",error:B.error??K.error??Z.error??U.error??I.error??new Error("Movement data unavailable"),onRetry:()=>{B.refetch(),K.refetch(),Z.refetch(),U.refetch(),I.refetch()}});const ee=B.data,Y=K.data,R=Z.data,X=U.data,be=W.data??ee.selectionAggregate;return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{entityKind:"project",title:"Movement",description:"Turn passive place and travel signals into a real Forge domain: day rhythm, travel arcs, known landmarks, linked work, and reflective evidence.",badge:`${ee.summary.tripCount} trips today`,actions:e.jsx("div",{className:"flex flex-wrap gap-2",children:["life","day","month","all_time"].map(ue=>e.jsx(Q,{variant:"ghost",className:re("h-9 rounded-full border px-4 text-sm",a===ue?"border-[var(--primary)] bg-[var(--primary)]/16 text-white":"border-white/10 bg-white/[0.04] text-white/64"),onClick:()=>n(ue),children:ue==="all_time"?"All time":ue==="life"?"Life":ue.charAt(0).toUpperCase()+ue.slice(1)},ue))})}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.65fr)_minmax(20rem,0.95fr)]",children:[e.jsxs(ae,{className:"overflow-hidden rounded-[30px] border border-white/8 bg-[radial-gradient(circle_at_top_left,rgba(107,214,255,0.16),transparent_42%),linear-gradient(180deg,rgba(10,18,35,0.98),rgba(9,15,28,0.92))]",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Movement operating mode"}),e.jsx(it,{content:"This is the passive capture state of the movement system: whether tracking is running, how much is published into Forge, and how aggressive retention is."})]}),e.jsx("div",{className:"mt-2 text-[clamp(1.05rem,1.8vw,1.35rem)] text-white",children:"Background stays and trips as structured life evidence"}),e.jsx("div",{className:"mt-2 max-w-2xl text-sm leading-6 text-white/58",children:"The companion samples quietly while stationary, switches to denser trip capture when you move, and keeps only simplified long-term traces."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(L,{tone:"signal",children:X.trackingEnabled?"Tracking on":"Tracking off"}),e.jsx(L,{tone:"default",className:"bg-white/[0.06] text-white/72",children:X.publishMode.replaceAll("_"," ")}),e.jsx(Q,{variant:"ghost",className:"h-9 rounded-full border border-white/10 bg-white/[0.04] px-4",onClick:()=>ne.mutate(!X.trackingEnabled),children:X.trackingEnabled?"Pause passive capture":"Enable passive capture"})]})]}),e.jsxs("div",{className:"mt-5 grid gap-3 sm:grid-cols-3",children:[e.jsxs(ae,{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/40",children:"Distance today"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:ai(ee.summary.totalDistanceMeters)}),e.jsx("div",{className:"mt-2 text-sm text-white/56",children:"Across trips, stops, and linked place changes."})]}),e.jsxs(ae,{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/40",children:"Idle time"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Rs(ee.summary.totalIdleSeconds)}),e.jsx("div",{className:"mt-2 text-sm text-white/56",children:"Time spent settled enough to count as a real stay."})]}),e.jsxs(ae,{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/40",children:"Known places"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:ee.summary.knownPlaceCount}),e.jsx("div",{className:"mt-2 text-sm text-white/56",children:"Shared between Forge and the iPhone companion."})]})]})]}),e.jsxs(ae,{className:"rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(10,17,31,0.96),rgba(8,13,24,0.92))] p-5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Selection aggregate"}),e.jsx(it,{content:"When you select stays or trips, Forge totals their span, distance, work overlap, notes, and places here."})]}),e.jsx("div",{className:"mt-2 text-sm text-white/56",children:"Select any combination of stays and trips to sum movement, time, and work evidence."}),e.jsxs("div",{className:"mt-5 grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Span"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Rs(be.durationSeconds)})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Distance"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:ai(be.distanceMeters)})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Work overlap"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Rs(be.trackedWorkSeconds)})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Notes"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:be.noteCount})]})]}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:be.placeLabels.map(ue=>e.jsx(L,{tone:"default",className:"bg-white/[0.06] text-white/74",children:ue},ue))})]})]}),a==="life"?e.jsxs("section",{className:"grid gap-3",children:[e.jsx("div",{className:"flex items-center justify-between gap-3 px-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/38",children:"Life graph"}),e.jsx(it,{content:"This graph shows the movement road of your life: stays are blocks, moves connect them, and the hour/day lines live in the background. Click a segment for details, then use edit when you want to correct it."})]})}),e.jsx(hy,{userIds:i})]}):null,a==="day"?e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.55fr)_minmax(22rem,1fr)]",children:[e.jsxs(ae,{className:"rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(10,17,31,0.96),rgba(7,12,22,0.92))] p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Day strip"}),e.jsx(it,{content:"A compressed 24-hour strip. Each segment keeps its true order and duration, but the whole day stays navigable on one line."})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"A single-row timeline from 00:00 to 24:00, always compressed into one navigable strip."})]}),e.jsx(le,{type:"date",value:r,onChange:ue=>l(ue.target.value),className:"w-[11rem]"})]}),e.jsx("div",{className:"mt-6 overflow-x-auto pb-2",children:e.jsxs("div",{className:"min-w-[52rem]",children:[e.jsx("div",{className:"mb-3 flex justify-between text-[11px] uppercase tracking-[0.18em] text-white/36",children:["00:00","06:00","12:00","18:00","24:00"].map(ue=>e.jsx("span",{children:ue},ue))}),e.jsx("div",{className:"flex h-28 items-stretch overflow-hidden rounded-[28px] border border-white/10 bg-[rgba(255,255,255,0.03)] p-2",children:ee.segments.map(ue=>{const Fe=Math.max(9,ue.durationSeconds/86400*100),dt=ue.kind==="stay"?A.stayIds.includes(ue.id):A.tripIds.includes(ue.id);return e.jsxs("button",{type:"button",className:re("relative flex min-w-[5.5rem] flex-col justify-between rounded-[22px] border px-3 py-2 text-left transition",dt?"border-[rgba(171,232,255,0.5)] bg-[rgba(171,232,255,0.16)]":"border-white/6 bg-[linear-gradient(180deg,rgba(255,255,255,0.08),rgba(255,255,255,0.02))] hover:border-white/14 hover:bg-white/[0.08]"),style:{width:`${Fe}%`},onClick:()=>{T(yt=>{const wt=new Set(yt.stayIds),kt=new Set(yt.tripIds);return ue.kind==="stay"?wt.has(ue.id)?wt.delete(ue.id):wt.add(ue.id):kt.has(ue.id)?kt.delete(ue.id):(kt.add(ue.id),v(ue.id)),{stayIds:[...wt],tripIds:[...kt]}})},children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(L,{tone:ue.kind==="trip"?"signal":"default",className:"bg-white/[0.08] text-white/82",children:ue.kind}),e.jsx("span",{className:"text-[11px] text-white/46",children:Rs(ue.durationSeconds)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"line-clamp-2 text-sm font-semibold text-white",children:ue.label}),e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/52",children:ue.subtitle})]})]},ue.id)})})]})}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(L,{tone:"signal",children:my(r)}),e.jsxs(L,{tone:"default",className:"bg-white/[0.06] text-white/72",children:[ee.summary.tripCount," trips"]}),e.jsxs(L,{tone:"default",className:"bg-white/[0.06] text-white/72",children:[ee.summary.stayCount," stays"]})]})]}),e.jsx("div",{className:"grid gap-4",children:G.data?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Selected trip"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsx(Q,{variant:"ghost",className:"h-9 rounded-full border border-white/10 bg-white/[0.04] px-4",onClick:()=>f(ue=>!ue),children:u?"Stylized graph":"Exact path"})})]}),u?e.jsx(jy,{points:G.data.trip.points}):e.jsx(yy,{curve:G.data.stylizedPath.curve,startLabel:G.data.stylizedPath.startLabel,endLabel:G.data.stylizedPath.endLabel,stopLabels:G.data.stylizedPath.stops.map(ue=>ue.label)}),e.jsxs(ae,{className:"rounded-[28px] border border-white/8 bg-white/[0.04] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Trip context"}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(L,{tone:"signal",children:ai(G.data.trip.distanceMeters)}),e.jsx(L,{tone:"default",className:"bg-white/[0.06] text-white/74",children:G.data.trip.activityType||G.data.trip.travelMode}),e.jsx(L,{tone:"default",className:"bg-white/[0.06] text-white/74",children:Rs(G.data.trip.durationSeconds)})]}),e.jsx("div",{className:"mt-4 text-sm leading-6 text-white/58",children:uy(G.data.trip.startedAt,G.data.trip.endedAt)})]})]}):e.jsx(ae,{className:"rounded-[30px] border border-dashed border-white/12 bg-white/[0.03] p-6 text-white/58",children:"Select a trip segment to open the stylized trajectory card and exact path toggle."})})]}):null,a==="month"?e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.4fr)_minmax(18rem,0.85fr)]",children:[e.jsxs(ae,{className:"rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(9,15,28,0.97),rgba(8,13,24,0.92))] p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Month view"}),e.jsx(it,{content:"This chart stays quantitative. Switch the metric to compare daily distance, moving time, idle time, or calories across the month."})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Switch the Y-axis between motion, idle time, and energy without losing the same monthly frame."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(le,{type:"month",value:o,onChange:ue=>c(ue.target.value),className:"w-[10.5rem]"}),["distanceMeters","movingSeconds","idleSeconds","caloriesKcal"].map(ue=>e.jsx(Q,{variant:"ghost",className:re("h-9 rounded-full border px-4 text-sm",J===ue?"border-[var(--primary)] bg-[var(--primary)]/14 text-white":"border-white/10 bg-white/[0.04] text-white/62"),onClick:()=>O(ue),children:ue==="distanceMeters"?"Distance":ue==="movingSeconds"?"Moving":ue==="idleSeconds"?"Idle":"Calories"},ue))]})]}),e.jsx("div",{className:"mt-6 h-[24rem]",children:e.jsx(Kn,{width:"100%",height:"100%",children:e.jsxs(kh,{data:Y.days,children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"movementMonthFill",x1:"0",x2:"0",y1:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgba(110,220,255,0.7)"}),e.jsx("stop",{offset:"100%",stopColor:"rgba(110,220,255,0.05)"})]})}),e.jsx(ox,{stroke:"rgba(255,255,255,0.08)",vertical:!1}),e.jsx(Un,{dataKey:"dateKey",tick:{fill:"rgba(255,255,255,0.46)",fontSize:11},axisLine:!1,tickLine:!1}),e.jsx(Qn,{tick:{fill:"rgba(255,255,255,0.46)",fontSize:11},axisLine:!1,tickLine:!1}),e.jsx(Sh,{contentStyle:{background:"rgba(7,12,24,0.94)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:16},formatter:ue=>py(J,Number(ue))}),e.jsx(Gr,{type:"monotone",dataKey:J,stroke:"rgba(126,233,255,0.95)",fill:"url(#movementMonthFill)",strokeWidth:2.4})]})})})]}),e.jsxs(ae,{className:"rounded-[30px] border border-white/8 bg-white/[0.04] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Month totals"}),e.jsxs("div",{className:"mt-5 grid gap-3",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Distance"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:ai(Y.totals.distanceMeters)})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Moving time"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:Rs(Y.totals.movingSeconds)})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Settled time"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:Rs(Y.totals.idleSeconds)})]})]})]})]}):null,a==="all_time"?e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.35fr)_minmax(20rem,0.95fr)]",children:[e.jsxs(ae,{className:"rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(8,13,25,0.97),rgba(8,13,24,0.92))] p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs(ae,{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Trips"}),e.jsx("div",{className:"mt-2 text-3xl text-white",children:R.summary.tripCount})]}),e.jsxs(ae,{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Known places"}),e.jsx("div",{className:"mt-2 text-3xl text-white",children:R.summary.knownPlaceCount})]}),e.jsxs(ae,{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Distance"}),e.jsx("div",{className:"mt-2 text-3xl text-white",children:ai(R.summary.totalDistanceMeters)})]}),e.jsxs(ae,{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Countries"}),e.jsx("div",{className:"mt-2 text-3xl text-white",children:R.summary.visitedCountries})]})]}),e.jsx("div",{className:"mt-6 grid gap-3 sm:grid-cols-2",children:R.recentTrips.map(ue=>e.jsxs("button",{type:"button",className:"rounded-[24px] border border-white/8 bg-white/[0.03] p-4 text-left transition hover:bg-white/[0.06]",onClick:()=>{n("day"),v(ue.id)},children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/36",children:"Recent travel"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:ue.label||"Untitled trip"}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[ai(ue.distanceMeters)," · ",ue.activityType||"travel"]})]},ue.id))})]}),e.jsxs(ae,{className:"rounded-[30px] border border-white/8 bg-white/[0.04] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Place categories"}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:R.categoryBreakdown.map(ue=>e.jsxs(L,{tone:"default",className:"bg-white/[0.06] text-white/74",children:[ue.tag," · ",ue.count]},ue.tag))})]})]}):null,e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.25fr)_minmax(22rem,0.95fr)]",children:[e.jsxs(ae,{className:"rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(8,14,28,0.96),rgba(9,15,28,0.92))] p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Known places"}),e.jsx(it,{content:"Known places turn raw stationary spans into named contexts like home, work, gym, nature, or any custom place tag you want Forge to remember."})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"These landmarks anchor stays, travel XP, and contextual reasoning in both Forge and the companion. Seeded tags like home, workplace, gym, holiday, grocery, or nature matter for downstream calculations, but place tags stay open-ended."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(le,{value:F,onChange:ue=>z(ue.target.value),placeholder:"Search places",className:"w-[11rem]"}),e.jsx(Q,{onClick:()=>{C(null),$(!0)},children:"Add place"})]})]}),e.jsx("div",{className:"mt-5 grid gap-3",children:H.map(ue=>e.jsxs("button",{type:"button",className:"flex items-start justify-between gap-3 rounded-[24px] border border-white/8 bg-white/[0.03] p-4 text-left transition hover:bg-white/[0.06]",onClick:()=>{C(ue),$(!0)},children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-lg text-white",children:ue.label}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[ue.latitude.toFixed(4),", ",ue.longitude.toFixed(4)," · radius ",Math.round(ue.radiusMeters)," m"]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:ue.categoryTags.map(Fe=>e.jsx(L,{tone:"default",className:"bg-white/[0.06] text-white/74",children:Fe},Fe))})]}),e.jsx(Ns,{className:"mt-1 size-4 text-white/42"})]},ue.id))})]}),e.jsxs(ae,{className:"rounded-[30px] border border-white/8 bg-[linear-gradient(180deg,rgba(10,17,31,0.96),rgba(8,13,24,0.92))] p-5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Movement help"}),e.jsx(it,{content:"Most movement surfaces on this page have help buttons. Use them to understand the graph, the day strip, the month chart, and the place system without keeping a large prose block on screen."})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:"Use the small help icons across this page for graph explanations, timeline semantics, and metric meanings."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(L,{className:"bg-white/[0.06] text-white/74",children:"Life graph"}),e.jsx(L,{className:"bg-white/[0.06] text-white/74",children:"Day strip"}),e.jsx(L,{className:"bg-white/[0.06] text-white/74",children:"Month chart"}),e.jsx(L,{className:"bg-white/[0.06] text-white/74",children:"Known places"}),e.jsx(L,{className:"bg-white/[0.06] text-white/74",children:"Selection aggregate"})]})]})]}),G.data?e.jsx(bs,{open:h,onOpenChange:ue=>{m(ue),ue||(w(""),E([]),j(null),p(null))},eyebrow:"Movement data",title:G.data.trip.label||"Trip datapoints",description:"Inspect the raw datapoints behind this trip, search them with time and quality filters, then edit or tombstone them without letting the companion re-upload the stale version.",children:e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,24rem)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsx(Fa,{title:"Datapoint browser",description:"Search raw points by time band, anchor status, or accuracy before opening the point editor.",query:b,onQueryChange:w,options:me,selectedOptionIds:M,onSelectedOptionIdsChange:E,resultSummary:P,placeholder:"Search timestamps, accuracy, point ids, or filter chips",emptyStateMessage:"Keep typing or pick a time/quality chip to narrow the trip datapoints."}),e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Raw datapoints"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Open a point to correct or delete it."})]}),e.jsx(L,{tone:"meta",children:P})]}),e.jsx("div",{ref:_,className:"h-[34rem] overflow-y-auto rounded-[24px] border border-white/8 bg-white/[0.03]",children:y.length===0?e.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center text-sm leading-6 text-white/50",children:"No datapoint matches the current search. Clear some filters or search by time, anchor type, or accuracy."}):e.jsx("div",{className:"relative w-full",style:{height:`${q.getTotalSize()}px`},children:q.getVirtualItems().map(ue=>{const Fe=y[ue.index];return e.jsx("div",{className:"absolute left-0 top-0 w-full px-3 py-2",style:{transform:`translateY(${ue.start}px)`},children:e.jsxs("button",{type:"button",className:re("grid w-full gap-3 rounded-[20px] border px-4 py-3 text-left transition",D===Fe.id?"border-[rgba(171,232,255,0.34)] bg-[rgba(171,232,255,0.12)]":"border-white/8 bg-white/[0.04] hover:bg-white/[0.07]"),onClick:()=>{j(Fe.id),p(kr(Fe))},children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[e.jsx(gi,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"truncate text-base font-medium",children:no(Fe.recordedAt)})]}),e.jsxs("div",{className:"mt-2 text-sm text-white/56",children:[Fe.latitude.toFixed(5),", ",Fe.longitude.toFixed(5)]})]}),e.jsx(L,{tone:Fe.isStopAnchor?"signal":"meta",children:Fe.isStopAnchor?"Stop anchor":"Path point"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(L,{tone:"meta",className:"capitalize",children:ir(Fe.recordedAt)}),Fe.accuracyMeters!=null?e.jsxs(L,{tone:"meta",children:[Math.round(Fe.accuracyMeters)," m accuracy"]}):null,Fe.speedMps!=null?e.jsxs(L,{tone:"meta",children:[Fe.speedMps.toFixed(1)," m/s"]}):null]})]})},Fe.id)})})})]})]}),pe&&S?e.jsx(Ny,{point:pe,draft:S,saving:we.isPending&&((Ge=we.variables)==null?void 0:Ge.pointId)===pe.id,deleting:Ne.isPending&&((De=Ne.variables)==null?void 0:De.pointId)===pe.id,onDraftChange:ue=>p(Fe=>Fe&&{...Fe,...ue}),onSave:()=>{if(!x||!S)return;const ue=gy(S.recordedAt);ue&&we.mutateAsync({tripId:x,pointId:pe.id,patch:{recordedAt:ue,latitude:Number(S.latitude),longitude:Number(S.longitude),accuracyMeters:S.accuracyMeters.trim().length>0?Number(S.accuracyMeters):null,altitudeMeters:S.altitudeMeters.trim().length>0?Number(S.altitudeMeters):null,speedMps:S.speedMps.trim().length>0?Number(S.speedMps):null,isStopAnchor:S.isStopAnchor}})},onDelete:()=>{var Fe;if(!x)return;const ue=y.find(dt=>dt.id!==pe.id)??((Fe=G.data)==null?void 0:Fe.trip.points.find(dt=>dt.id!==pe.id))??null;j((ue==null?void 0:ue.id)??null),p(ue?kr(ue):null),Ne.mutateAsync({tripId:x,pointId:pe.id})}}):e.jsx(ae,{className:"rounded-[28px] border border-dashed border-white/12 bg-white/[0.03] p-6 text-white/56",children:"Pick a datapoint to edit or delete it. The canonical change will flow back to the companion on the next sync."})]})}):null,e.jsx(ky,{open:k,onOpenChange:$,place:g,onSave:async ue=>{await de.mutateAsync(ue)}})]})}function Cy(t){return t.trim().toLowerCase()}function Iy(t,s){return t.includes(s)?t:[...t,s]}function Ty({entityOptions:t,selectedEntityValues:s,onSelectedEntityValuesChange:i,selectedTextTerms:a,onSelectedTextTermsChange:n,placeholder:r="Filter by linked entity or add free text"}){const[l,o]=d.useState(""),[c,x]=d.useState(!1),[v,u]=d.useState(0),f=Cy(l),h=d.useMemo(()=>s.map(j=>t.find(S=>S.value===j)).filter(Boolean),[t,s]),m=d.useMemo(()=>{const j=t.filter(S=>!s.includes(S.value));return f?j.filter(S=>`${S.label} ${S.description??""} ${S.searchText??""}`.toLowerCase().includes(f)).slice(0,8):j.slice(0,8)},[t,f,s]),b=l.trim().length>0&&!a.includes(l.trim()),w=j=>{i(Iy(s,j)),o(""),u(0),x(!1)},M=(j=l)=>{const S=j.trim();!S||a.includes(S)||(n([...a,S]),o(""),u(0),x(!1))},E=j=>{i(s.filter(S=>S!==j))},D=j=>{n(a.filter(S=>S!==j))};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:()=>M(),disabled:!b,className:"rounded-full border border-white/8 bg-white/[0.04] px-2.5 py-1 text-[10px] tracking-[0.14em] text-white/62 transition hover:bg-white/[0.08] hover:text-white disabled:cursor-not-allowed disabled:opacity-40",children:"Free text"})]}),e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(135deg,rgba(19,28,48,0.88),rgba(10,14,26,0.98))] px-4 py-3 shadow-[0_24px_70px_rgba(3,8,18,0.2)]",children:[h.length>0||a.length>0?e.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[h.map(j=>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:[j.kind?e.jsx(Te,{kind:j.kind,label:j.label,compact:!0,gradient:!1,className:"max-w-[16rem]"}):e.jsx(L,{className:"bg-white/[0.08] text-white/78",children:j.label}),e.jsx("button",{type:"button",className:"rounded-full text-white/50 transition hover:text-white",onClick:()=>E(j.value),"aria-label":`Remove ${j.label}`,children:e.jsx(mt,{className:"size-3.5"})})]},j.value)),a.map(j=>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(Uo,{className:"size-3.5"}),e.jsx("span",{className:"max-w-[16rem] truncate",children:j})]}),e.jsx("button",{type:"button",className:"rounded-full text-cyan-100/70 transition hover:text-white",onClick:()=>D(j),"aria-label":`Remove free-text filter ${j}`,children:e.jsx(mt,{className:"size-3.5"})})]},j))]}):null,a.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(bt,{className:"size-4 text-white/34"}),e.jsx("input",{value:l,onChange:j=>{o(j.target.value),x(!0),u(0)},onFocus:()=>x(!0),onBlur:()=>{window.setTimeout(()=>x(!1),120)},onKeyDown:j=>{if(j.key==="Backspace"&&!l){if(a.length>0){D(a[a.length-1]);return}s.length>0&&E(s[s.length-1]);return}if(j.key==="ArrowDown"){j.preventDefault(),x(!0),u(p=>m.length===0?0:Math.min(m.length-1,p+1));return}if(j.key==="ArrowUp"){j.preventDefault(),u(p=>Math.max(0,p-1));return}if(j.key==="Escape"){x(!1);return}if(j.key!=="Enter")return;j.preventDefault();const S=m[v];if(S){w(S.value);return}M()},placeholder:r,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:[m.map((j,S)=>e.jsx("button",{type:"button",className:re("flex w-full items-start justify-between gap-3 rounded-[18px] px-3 py-2.5 text-left transition",S===v?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>u(S),onMouseDown:p=>p.preventDefault(),onClick:()=>w(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(Te,{kind:j.kind,label:j.label,compact:!0,gradient:!1}):j.label}),j.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/46",children:j.description}):null]})},j.value)),b?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:j=>j.preventDefault(),onClick:()=>M(),children:[e.jsx(Uo,{className:"size-4"}),e.jsxs("span",{className:"truncate",children:['Add free text "',l.trim(),'"']})]}):null,m.length===0&&!b?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 Py=new Set(["goal","project","task","strategy","habit","tag","psyche_value","behavior_pattern","behavior","belief_entry","mode_profile","trigger_report"]),ls={goal:"goal",project:"project",task:"task",strategy:"strategy",habit:"habit",psyche_value:"value",behavior_pattern:"pattern",behavior:"behavior",belief_entry:"belief",mode_profile:"mode",trigger_report:"report"};function qm(t){return Py.has(t)}function Wt(t,s){return`${t}:${s}`}function Ha(t){const s=t.indexOf(":");if(s<=0||s>=t.length-1)return null;const i=t.slice(0,s);return qm(i)?{entityType:i,entityId:t.slice(s+1)}:null}function sc(t){return t!==null}function ic(t){const s=t.getAll("linkedTo"),i=t.get("entityType"),a=t.get("entityId");return i&&a&&qm(i)&&s.unshift(Wt(i,a)),Array.from(new Set(s.map(n=>n.trim()).filter(Boolean)))}function My(t){return Array.from(new Set(t.getAll("textTerms").map(s=>s.trim()).filter(Boolean)))}function Ay(t){return Ut(t.getAll("tags"))}function da(t,s=[]){return{contentMarkdown:(t==null?void 0:t.contentMarkdown)??"",author:(t==null?void 0:t.author)??"",linkedValues:(t==null?void 0:t.links.map(i=>Wt(i.entityType,i.entityId)))??s,tags:Ut((t==null?void 0:t.tags)??[]),destroyAtInput:km((t==null?void 0:t.destroyAt)??null),destroyDelayValue:"",destroyDelayUnit:"days"}}function Ey(t){return[...t].sort((s,i)=>s.label.localeCompare(i.label))}function ac(t){return Pn(t.destroyAtInput)??Sm(t.destroyDelayValue,t.destroyDelayUnit)}function Ly(){var me,y,P,q,pe,ee,Y;const t=ut(),s=We(),i=Je(),[a,n]=Pt(),[r,l]=d.useState(()=>ic(a)),[o,c]=d.useState(()=>Ay(a)),[x,v]=d.useState(()=>My(a)),[u,f]=d.useState(a.get("author")??""),[h,m]=d.useState(a.get("updatedFrom")??""),[b,w]=d.useState(a.get("updatedTo")??""),[M,E]=d.useState(!1),[D,j]=d.useState(()=>da(null,ic(a))),[S,p]=d.useState(null),[A,T]=d.useState(null),[k,$]=d.useState(null),g=fe({queryKey:["forge-psyche-values"],queryFn:ps}),C=fe({queryKey:["forge-psyche-patterns"],queryFn:Vs}),F=fe({queryKey:["forge-psyche-behaviors"],queryFn:xs}),z=fe({queryKey:["forge-psyche-beliefs"],queryFn:As}),J=fe({queryKey:["forge-psyche-modes"],queryFn:Es}),O=fe({queryKey:["forge-psyche-reports"],queryFn:bi});d.useEffect(()=>{const R=new URLSearchParams;for(const X of r)R.append("linkedTo",X);for(const X of o)R.append("tags",X);for(const X of x)R.append("textTerms",X);u.trim()&&R.set("author",u.trim()),h&&R.set("updatedFrom",h),b&&R.set("updatedTo",b),n(R,{replace:!0})},[u,r,o,x,n,h,b]);const _=d.useMemo(()=>{var X,be,Ie,te,ce,Se;const R=[...i.snapshot.goals.map(he=>({value:Wt("goal",he.id),label:he.title,description:Ke(he.description,he.user,"Goal"),searchText:Be([he.title,he.description],he),kind:ls.goal})),...i.snapshot.dashboard.projects.map(he=>({value:Wt("project",he.id),label:he.title,description:Ke(`${he.description}${he.description?" · ":""}${he.goalTitle}`,he.user,he.goalTitle),searchText:Be([he.title,he.description,he.goalTitle],he),kind:ls.project})),...i.snapshot.tasks.map(he=>({value:Wt("task",he.id),label:he.title,description:Ke(`${he.description}${he.description?" · ":""}${he.owner}`,he.user,he.owner),searchText:Be([he.title,he.description,he.owner],he),kind:ls.task})),...i.snapshot.strategies.map(he=>({value:Wt("strategy",he.id),label:he.title,description:Ke(he.overview,he.user,"Strategy"),searchText:Be([he.title,he.overview,he.endStateDescription],he),kind:ls.strategy})),...i.snapshot.habits.map(he=>({value:Wt("habit",he.id),label:he.title,description:Ke(he.description,he.user,"Habit"),searchText:Be([he.title,he.description],he),kind:ls.habit})),...i.snapshot.tags.map(he=>({value:Wt("tag",he.id),label:he.name,description:Ke(he.description,he.user,he.kind),searchText:Be([he.name,he.kind,he.description],he)})),...(((X=g.data)==null?void 0:X.values)??[]).map(he=>({value:Wt("psyche_value",he.id),label:he.title,description:Ke(he.description,he.user,"Psyche value"),searchText:Be([he.title,he.description,he.valuedDirection],he),kind:ls.psyche_value})),...(((be=C.data)==null?void 0:be.patterns)??[]).map(he=>({value:Wt("behavior_pattern",he.id),label:he.title,description:Ke(he.description,he.user,"Behavior pattern"),searchText:Be([he.title,he.description,he.targetBehavior],he),kind:ls.behavior_pattern})),...(((Ie=F.data)==null?void 0:Ie.behaviors)??[]).map(he=>({value:Wt("behavior",he.id),label:he.title,description:Ke(he.description,he.user,"Behavior"),searchText:Be([he.title,he.description,he.kind],he),kind:ls.behavior})),...(((te=z.data)==null?void 0:te.beliefs)??[]).map(he=>({value:Wt("belief_entry",he.id),label:he.statement,description:Ke(he.flexibleAlternative||he.originNote,he.user,"Belief"),searchText:Be([he.statement,he.flexibleAlternative,he.originNote],he),kind:ls.belief_entry})),...(((ce=J.data)==null?void 0:ce.modes)??[]).map(he=>({value:Wt("mode_profile",he.id),label:he.title,description:Ke(he.archetype||he.family,he.user,"Mode"),searchText:Be([he.title,he.archetype,he.family,he.persona],he),kind:ls.mode_profile})),...(((Se=O.data)==null?void 0:Se.reports)??[]).map(he=>({value:Wt("trigger_report",he.id),label:he.title,description:Ke(he.eventSituation,he.user,"Trigger report"),searchText:Be([he.title,he.eventSituation,he.customEventType??""],he),kind:ls.trigger_report}))];return Ey(R)},[(me=F.data)==null?void 0:me.behaviors,(y=z.data)==null?void 0:y.beliefs,(P=J.data)==null?void 0:P.modes,(q=C.data)==null?void 0:q.patterns,(pe=O.data)==null?void 0:pe.reports,i.snapshot.dashboard.projects,i.snapshot.goals,i.snapshot.habits,i.snapshot.strategies,i.snapshot.tags,i.snapshot.tasks,(ee=g.data)==null?void 0:ee.values]),B=d.useMemo(()=>_.map(R=>{const X=Ha(R.value);return{value:R.value,label:R.label,description:R.description,searchText:R.searchText,kind:R.kind,entityType:(X==null?void 0:X.entityType)??"goal",entityId:(X==null?void 0:X.entityId)??""}}),[_]),K=d.useMemo(()=>r.map(R=>Ha(R)).filter(Boolean),[r]),Z=fe({queryKey:["notes-index",r.join("|"),o.join("|"),x.join("|"),u.trim(),h,b],queryFn:()=>Oh({linkedTo:K,tags:o,textTerms:x,author:u.trim()||void 0,updatedFrom:h||void 0,updatedTo:b||void 0,limit:200})}),U=async()=>{await Promise.all([s.invalidateQueries({queryKey:["notes-index"]}),s.invalidateQueries({queryKey:["forge-snapshot"]})])},I=xe({mutationFn:async R=>$a({contentMarkdown:R.contentMarkdown.trim(),author:R.author.trim()||null,tags:Ut(R.tags),destroyAt:ac(R),links:R.linkedValues.map(X=>Ha(X)).filter(sc).map(X=>({entityType:X.entityType,entityId:X.entityId}))}),onSuccess:async()=>{j(da(null,r)),E(!1),await U()}}),G=xe({mutationFn:async({noteId:R,draft:X})=>Ta(R,{contentMarkdown:X.contentMarkdown.trim(),author:X.author.trim()||null,tags:Ut(X.tags),destroyAt:ac(X),links:X.linkedValues.map(be=>Ha(be)).filter(sc).map(be=>({entityType:be.entityType,entityId:be.entityId}))}),onSuccess:async()=>{p(null),T(null),await U()}}),W=xe({mutationFn:R=>Bl(R),onSuccess:U}),ne=((Y=Z.data)==null?void 0:Y.notes)??[],de=k?ne.find(R=>R.id===k.noteId)??null:null,we=de?_d(de):null,Ne=we?Xs(we.entityType,we.entityId):null,H=d.useMemo(()=>de?[{id:"open-linked",label:"Open linked record",description:Ne?"Jump back into the main entity this note is attached to.":"This note has no navigable linked record yet.",icon:Ms,disabled:!Ne,onSelect:()=>{Ne&&t(Ne.includes("#")?Ne:`${Ne}#notes`)}},{id:"edit-note",label:"Edit note",description:"Update the Markdown body, note tags, expiry, or connected entity links.",icon:mi,onSelect:()=>{p(de.id),T(da(de))}},{id:"delete-note",label:"Delete note",description:"Soft-delete this note from the main workspace.",icon:ct,tone:"danger",disabled:W.isPending,onSelect:()=>{W.mutateAsync(de.id)}}]:[],[Ne,de,W,t]);return Z.isError?e.jsx(ze,{eyebrow:"Notes",error:Z.error,onRetry:()=>void Z.refetch()}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{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:`${ne.length} visible`,actions:e.jsxs(Q,{onClick:()=>{j(da(null,r)),E(!0)},children:[e.jsx(zt,{className:"size-4"}),"New note"]})}),e.jsxs(ae,{className:"grid gap-4",children:[e.jsx(Ty,{entityOptions:B,selectedEntityValues:r,onSelectedEntityValuesChange:l,selectedTextTerms:x,onSelectedTextTermsChange:v}),e.jsx(ci,{value:o,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(le,{value:u,onChange:R=>f(R.target.value),placeholder:"Filter by author"}),e.jsx(le,{type:"date",value:h,onChange:R=>m(R.target.value)}),e.jsx(le,{type:"date",value:b,onChange:R=>w(R.target.value)})]})]}),M?e.jsxs(ae,{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(Q,{variant:"ghost",onClick:()=>{E(!1),j(da(null,r))},children:"Cancel"})]}),e.jsx(Me,{value:D.contentMarkdown,onChange:R=>j(X=>({...X,contentMarkdown:R.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(le,{value:D.author,onChange:R=>j(X=>({...X,author:R.target.value})),placeholder:"Optional author"}),e.jsx(et,{options:_,selectedValues:D.linkedValues,onChange:R=>j(X=>({...X,linkedValues:R})),placeholder:"Link this note to strategies, goals, projects, tasks, habits, or human/bot-owned records",emptyMessage:"No matching entities found yet."})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]",children:[e.jsx(ci,{value:D.tags,onChange:R=>j(X=>({...X,tags:R}))}),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(le,{type:"datetime-local",value:D.destroyAtInput,onChange:R=>j(X=>({...X,destroyAtInput:R.target.value}))}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_10rem]",children:[e.jsx(le,{type:"number",min:"1",value:D.destroyDelayValue,onChange:R=>j(X=>({...X,destroyDelayValue:R.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:D.destroyDelayUnit,onChange:R=>j(X=>({...X,destroyDelayUnit:R.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:D.contentMarkdown.trim()?e.jsx(ms,{markdown:D.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(Q,{pending:I.isPending,pendingLabel:"Saving",disabled:D.contentMarkdown.trim().length===0||D.linkedValues.length===0,onClick:()=>void I.mutateAsync(D),children:"Save note"})})]}):null,Z.isLoading?e.jsx(ae,{className:"text-sm text-white/58",children:"Loading notes…"}):ne.length===0?e.jsx(gt,{eyebrow:"Notes",title:"No matching notes yet",description:"Try broader linked-entity filters, remove a date bound, or add the first durable note from the button above."}):e.jsx("div",{className:"grid gap-3",children:ne.map(R=>{const X=_d(R),be=X?Xs(X.entityType,X.entityId):null,Ie=S===R.id&&A!==null;return e.jsxs(ae,{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:[(R.author??"Unknown author").toString()," •"," ",new Date(R.updatedAt).toLocaleString()]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[R.links.map(te=>e.jsxs(L,{className:"bg-white/[0.08] text-white/68",wrap:!0,children:[zs(te.entityType),te.anchorKey?` · ${Na(te.anchorKey)}`:""]},`${R.id}-${te.entityType}-${te.entityId}-${te.anchorKey??""}`)),(R.tags??[]).map(te=>e.jsx(L,{className:"bg-cyan-400/10 text-cyan-50",wrap:!0,children:te},`${R.id}-tag-${te}`)),R.destroyAt?e.jsxs(L,{className:"bg-amber-400/10 text-amber-100",wrap:!0,children:["Ephemeral · deletes"," ",new Date(R.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:te=>{te.preventDefault(),te.stopPropagation();const ce=te.currentTarget.getBoundingClientRect();$({noteId:R.id,position:{x:ce.right-8,y:ce.bottom+8}})},"aria-label":`Open actions for note ${R.id}`,children:e.jsx(cn,{className:"size-4"})})]}),Ie?e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsx(Me,{value:A.contentMarkdown,onChange:te=>T(ce=>ce&&{...ce,contentMarkdown:te.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(le,{value:A.author,onChange:te=>T(ce=>ce&&{...ce,author:te.target.value}),placeholder:"Optional author"}),e.jsx(et,{options:_,selectedValues:A.linkedValues,onChange:te=>T(ce=>ce&&{...ce,linkedValues:te}),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(ci,{value:A.tags,onChange:te=>T(ce=>ce&&{...ce,tags:te})}),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(le,{type:"datetime-local",value:A.destroyAtInput,onChange:te=>T(ce=>ce&&{...ce,destroyAtInput:te.target.value})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_10rem]",children:[e.jsx(le,{type:"number",min:"1",value:A.destroyDelayValue,onChange:te=>T(ce=>ce&&{...ce,destroyDelayValue:te.target.value}),placeholder:"Destroy after"}),e.jsxs("select",{className:"rounded-[14px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:A.destroyDelayUnit,onChange:te=>T(ce=>ce&&{...ce,destroyDelayUnit:te.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:A.contentMarkdown.trim()?e.jsx(ms,{markdown:A.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(Q,{variant:"ghost",onClick:()=>{p(null),T(null)},children:"Cancel"}),e.jsx(Q,{pending:G.isPending,pendingLabel:"Saving",disabled:A.contentMarkdown.trim().length===0||A.linkedValues.length===0,onClick:()=>void G.mutateAsync({noteId:R.id,draft:A}),children:"Save changes"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"mt-4 w-full text-left",onClick:()=>{be&&t(be.includes("#")?be:`${be}#notes`)},disabled:!be,children:e.jsx(ms,{markdown:R.contentMarkdown,className:"line-clamp-none"})}),be?e.jsx("div",{className:"mt-4 inline-flex text-xs uppercase tracking-[0.16em] text-[var(--secondary)]",children:"Open linked record"}):null]})]},R.id)})}),e.jsx(gm,{open:!!k,title:"Note actions",subtitle:de?de.contentPlain.slice(0,80)||"Markdown note":void 0,items:H,position:(k==null?void 0:k.position)??null,onClose:()=>$(null)})]})}const Ga={lg:1280,md:996,sm:768,xs:480},ll={lg:12,md:10,sm:6,xs:4,xxs:2},Dy="forge.surface-layout.v3";function Bm(t){return`${Dy}.${t}`}function ol(t,s,i){return Math.min(Math.max(t,s),i)}function $y(t){return t>=Ga.lg?"lg":t>=Ga.md?"md":t>=Ga.sm?"sm":t>=Ga.xs?"xs":"xxs"}function Oy(t,s){const i=ll[s];if(s==="lg")return ol(t.defaultWidth,t.minWidth??1,Math.min(t.maxWidth??i,i));const a=Math.round(t.defaultWidth/ll.lg*i);return ol(Math.max(t.minWidth??1,a||(t.minWidth??1)),t.minWidth??1,Math.min(t.maxWidth??i,i))}function Fy(t){return{hidden:t.defaultHidden??!1,fullWidth:t.defaultFullWidth??!1,titleVisible:t.defaultTitleVisible??!0,descriptionVisible:t.defaultDescriptionVisible??!0}}function dl(t,s){const i=[...s.filter(a=>a.defaultPlacement==="top"),...s.filter(a=>a.defaultPlacement!=="top")];return{surfaceId:t,order:i.map(a=>a.id),widgets:Object.fromEntries(s.map(a=>[a.id,Fy(a)])),updatedAt:new Date(0).toISOString()}}function Sr(t,s,i){const a=dl(t,s),n=new Set(s.map(c=>c.id)),r=((i==null?void 0:i.order)??[]).filter(c=>n.has(c)),l=a.order.filter(c=>!r.includes(c)),o=Object.fromEntries(s.map(c=>{var v,u,f,h,m;const x=(v=i==null?void 0:i.widgets)==null?void 0:v[c.id];return[c.id,{...a.widgets[c.id],hidden:(x==null?void 0:x.hidden)??((u=a.widgets[c.id])==null?void 0:u.hidden)??!1,fullWidth:(x==null?void 0:x.fullWidth)??((f=a.widgets[c.id])==null?void 0:f.fullWidth)??!1,titleVisible:(x==null?void 0:x.titleVisible)??((h=a.widgets[c.id])==null?void 0:h.titleVisible)??!0,descriptionVisible:(x==null?void 0:x.descriptionVisible)??((m=a.widgets[c.id])==null?void 0:m.descriptionVisible)??!0}]}));return{surfaceId:t,order:[...r,...l],widgets:o,updatedAt:typeof(i==null?void 0:i.updatedAt)=="string"?i.updatedAt:a.updatedAt}}function _y(t,s){const i=new Map(s.order.map((a,n)=>[a,n]));return[...t].sort((a,n)=>{const r=i.get(a.id)??Number.MAX_SAFE_INTEGER,l=i.get(n.id)??Number.MAX_SAFE_INTEGER;return r!==l?r-l:a.id.localeCompare(n.id)})}function Ry(t,s,i){const a=t.indexOf(s);if(a===-1)return t;const n=ol(i,0,t.length-1);if(a===n)return t;const r=[...t];return r.splice(a,1),r.splice(n,0,s),r}function Cr(t){if(typeof window>"u")return null;try{const s=window.localStorage.getItem(Bm(t));return s?JSON.parse(s):null}catch{return null}}function Ir(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Bm(t.surfaceId),JSON.stringify(t))}catch{}}const zy=500;function nc(t,s){return t.surfaceId===s.surfaceId&&JSON.stringify(t.order)===JSON.stringify(s.order)&&JSON.stringify(t.widgets)===JSON.stringify(s.widgets)}function qy({definition:t,preferences:s,editing:i,width:a,children:n}){const r=a<=4;return t.surfaceChrome==="none"?e.jsx("div",{"data-surface-card":"true",className:re("min-w-0",i&&"rounded-[28px] ring-1 ring-white/8 ring-inset"),children:n}):e.jsxs(ae,{"data-surface-card":"true",className:re("surface-grid-card flex min-w-0 flex-col gap-3 overflow-visible p-4 md:p-5",i&&"ring-1 ring-white/8"),children:[s.titleVisible||s.descriptionVisible&&t.description?e.jsxs("div",{className:"min-w-0",children:[s.titleVisible?e.jsx("div",{className:"truncate text-[0.72rem] font-semibold uppercase tracking-[0.16em] text-white/40",children:t.title}):null,s.descriptionVisible&&t.description&&!r?e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/52",children:t.description}):null]}):null,e.jsx("div",{className:"min-h-0 flex-1",children:n})]})}function By({widget:t,preferences:s,index:i,total:a,onMove:n,onToggleHidden:r,onToggleFullWidth:l}){const o=Dl({id:t.id});return e.jsxs("div",{ref:o.setNodeRef,style:{transform:$l.Transform.toString(o.transform),transition:o.transition},className:"flex min-w-0 items-center gap-2 rounded-[18px] border border-white/8 bg-white/[0.04] px-3 py-2.5",children:[e.jsx("button",{type:"button",className:"inline-flex size-8 shrink-0 items-center justify-center rounded-full bg-white/[0.05] text-white/50 transition hover:bg-white/[0.08] hover:text-white","aria-label":`Drag ${t.title}`,...o.attributes,...o.listeners,children:e.jsx(qn,{className:"size-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white",children:t.title}),t.description?e.jsx("div",{className:"truncate text-[12px] text-white/48",children:t.description}):null]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx("button",{type:"button",className:"inline-flex size-8 items-center justify-center rounded-full bg-white/[0.05] text-white/60 transition hover:bg-white/[0.08] hover:text-white disabled:opacity-40",onClick:()=>n(i-1),disabled:i===0,"aria-label":`Move ${t.title} up`,children:e.jsx(xp,{className:"size-3.5"})}),e.jsx("button",{type:"button",className:"inline-flex size-8 items-center justify-center rounded-full bg-white/[0.05] text-white/60 transition hover:bg-white/[0.08] hover:text-white disabled:opacity-40",onClick:()=>n(i+1),disabled:i===a-1,"aria-label":`Move ${t.title} down`,children:e.jsx(gp,{className:"size-3.5"})}),e.jsxs("button",{type:"button",className:re("inline-flex h-8 items-center gap-2 rounded-full px-3 text-[12px] transition",s.fullWidth?"bg-[var(--primary)] text-slate-950":"bg-white/[0.05] text-white/72 hover:bg-white/[0.08] hover:text-white"),onClick:l,children:[s.fullWidth?e.jsx(fp,{className:"size-3.5"}):e.jsx(bp,{className:"size-3.5"}),s.fullWidth?"Normal width":"Full width"]}),t.removable!==!1?e.jsxs("button",{type:"button",className:"inline-flex h-8 items-center gap-2 rounded-full bg-white/[0.05] px-3 text-[12px] text-white/72 transition hover:bg-white/[0.08] hover:text-white",onClick:r,children:[e.jsx(bh,{className:"size-3.5"}),"Hide"]}):null]})]})}function Ky({surfaceId:t,widgets:s,defaultEditing:i=!1,actions:a}){var F;const n=d.useMemo(()=>JSON.stringify(s.map(z=>({id:z.id,defaultWidth:z.defaultWidth,defaultHidden:z.defaultHidden,defaultPlacement:z.defaultPlacement,defaultFullWidth:z.defaultFullWidth,defaultTitleVisible:z.defaultTitleVisible,defaultDescriptionVisible:z.defaultDescriptionVisible}))),[s]),r=d.useMemo(()=>dl(t,s),[t,n]),[l,o]=d.useState(i),[c,x]=d.useState(1280),[v,u]=d.useState(()=>Sr(t,s,Cr(t)??r)),f=d.useRef(null),h=d.useRef(!1),m=d.useRef(Sr(t,s,Cr(t)??r)),b=d.useRef(null),w=Ml(Al(El,{activationConstraint:{distance:6}})),M=fe({queryKey:["forge-surface-layout",t],queryFn:()=>kf(t)}),E=xe({mutationFn:z=>Sf(t,{order:z.order,widgets:z.widgets})}),D=xe({mutationFn:()=>Cf(t)});d.useEffect(()=>{var J;const z=Sr(t,s,((J=M.data)==null?void 0:J.layout)??Cr(t)??r);u(O=>nc(O,z)?O:z),Ir(z),m.current=z,h.current=!0},[r,(F=M.data)==null?void 0:F.layout,t,n,s]),d.useEffect(()=>{const z=b.current;if(!z||typeof ResizeObserver>"u")return;const J=new ResizeObserver(O=>{var B;const _=((B=O[0])==null?void 0:B.contentRect.width)??z.clientWidth;x(Math.max(320,Math.round(_)))});return J.observe(z),x(Math.max(320,Math.round(z.clientWidth||1280))),()=>J.disconnect()},[]),d.useEffect(()=>{if(h.current&&!nc(v,m.current))return Ir(v),f.current!==null&&window.clearTimeout(f.current),f.current=window.setTimeout(()=>{const z=v;E.mutateAsync(z).then(()=>{m.current=z})},zy),()=>{f.current!==null&&window.clearTimeout(f.current)}},[v,E,t]);const j=$y(c),S=ll[j],p=d.useMemo(()=>_y(s,v),[v,s]),A=p.filter(z=>{var J;return!((J=v.widgets[z.id])!=null&&J.hidden)}),T=p.filter(z=>{var J;return(J=v.widgets[z.id])==null?void 0:J.hidden});function k(z,J){u(O=>({...O,widgets:{...O.widgets,[z]:{...O.widgets[z],...J}}}))}function $(z,J){u(O=>({...O,order:Ry(O.order,z,J)}))}function g(z){const{active:J,over:O}=z;!O||J.id===O.id||u(_=>{const B=_.order.indexOf(String(J.id)),K=_.order.indexOf(String(O.id));return B===-1||K===-1?_:{..._,order:Th(_.order,B,K)}})}function C(){const z=dl(t,s);u(z),Ir(z),m.current=z,D.mutateAsync()}return e.jsxs("div",{className:"grid gap-4",children:[l?e.jsx(Ll,{sensors:w,collisionDetection:Ih,onDragEnd:g,children:e.jsxs("div",{className:"grid gap-3 rounded-[24px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-[0.16em] text-white/40",children:"Visible boxes"}),e.jsx(yn,{items:A.map(z=>z.id),strategy:jn,children:e.jsx("div",{className:"grid gap-2",children:A.map((z,J)=>{const O=v.widgets[z.id]??{hidden:!1,fullWidth:!1,titleVisible:!0,descriptionVisible:!0};return e.jsx(By,{widget:z,preferences:O,index:J,total:A.length,onMove:_=>$(z.id,_),onToggleHidden:()=>k(z.id,{hidden:!0}),onToggleFullWidth:()=>k(z.id,{fullWidth:!O.fullWidth})},z.id)})})}),T.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"pt-2 text-[12px] uppercase tracking-[0.16em] text-white/40",children:"Hidden boxes"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:T.map(z=>e.jsx("button",{type:"button",className:"rounded-full bg-white/[0.06] px-3 py-2 text-sm text-white/76 transition hover:bg-white/[0.1] hover:text-white",onClick:()=>k(z.id,{hidden:!1}),children:z.title},z.id))})]}):null]})}):null,e.jsxs("div",{ref:b,className:"relative",children:[e.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 flex max-w-[calc(100%-1.5rem)] flex-wrap items-center justify-end gap-1.5",children:e.jsxs("div",{className:"pointer-events-auto flex flex-wrap items-center justify-end gap-1.5",children:[a,l?e.jsxs(Q,{type:"button",size:"sm",variant:"secondary",className:"h-8 rounded-full border-white/10 bg-[rgba(30,39,69,0.82)] px-2.5 text-[12px] text-white/78 backdrop-blur-xl hover:bg-[rgba(37,47,81,0.94)] hover:text-white",onClick:C,children:[e.jsx(fh,{className:"size-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Reset"})]}):null,e.jsxs(Q,{type:"button",size:"sm",variant:l?"primary":"secondary",className:re("h-8 rounded-full px-2.5 text-[12px] backdrop-blur-xl",l?"bg-[var(--primary)] text-slate-950 hover:opacity-95":"border-white/10 bg-[rgba(30,39,69,0.82)] text-white/78 hover:bg-[rgba(37,47,81,0.94)] hover:text-white"),onClick:()=>o(z=>!z),children:[e.jsx(ch,{className:"size-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:l?"Done":"Layout"})]})]})}),e.jsx("div",{className:"surface-flow-grid",style:{display:"grid",gap:"16px",gridTemplateColumns:`repeat(${S}, minmax(0, 1fr))`,alignItems:"start"},children:A.map(z=>{const J=v.widgets[z.id]??{hidden:!1,fullWidth:!1,titleVisible:!0,descriptionVisible:!0},O=J.fullWidth?S:Math.min(Oy(z,j),S);return e.jsx("div",{style:{gridColumn:`span ${O} / span ${O}`},children:e.jsx(qy,{definition:z,preferences:J,editing:l,width:O,children:z.render({compact:O<=4,width:O,editing:l,preferences:J})})},z.id)})})]})]})}function _a({surfaceId:t,baseWidgets:s,actions:i}){return e.jsx(Ky,{surfaceId:t,widgets:s,actions:e.jsxs(e.Fragment,{children:[i,e.jsxs(Ae,{to:`/connectors?surface=${encodeURIComponent(t)}`,className:"inline-flex h-8 items-center gap-1.5 rounded-full border border-white/10 bg-[rgba(32,40,70,0.78)] px-2.5 text-[12px] font-medium text-white/78 backdrop-blur-xl transition hover:border-white/16 hover:bg-[rgba(40,49,82,0.9)] hover:text-white",children:[e.jsx(vp,{className:"size-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Connectors"})]})]})})}function Uy(t){const s=new Date(t.getFullYear(),t.getMonth(),1),i=(s.getDay()+6)%7,a=new Date(s);return a.setDate(a.getDate()-i),Array.from({length:35},(n,r)=>{const l=new Date(a);return l.setDate(a.getDate()+r),l})}function Qy(t,s){return typeof window>"u"?s:window.localStorage.getItem(t)??s}function Wy(t,s){typeof window>"u"||window.localStorage.setItem(t,s)}function ro({compact:t}){const[s,i]=d.useState(()=>new Date);return d.useEffect(()=>{const a=window.setInterval(()=>i(new Date),3e4);return()=>window.clearInterval(a)},[]),e.jsxs("div",{className:"flex h-full flex-col justify-between gap-4 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/45",children:[e.jsx(rh,{className:"size-4"}),e.jsx("span",{className:"text-[12px] uppercase tracking-[0.16em]",children:"Local time"})]}),e.jsx("div",{className:re("font-display text-white",t?"text-3xl":"text-5xl"),children:new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(s)}),e.jsx("div",{className:"text-sm text-white/58",children:new Intl.DateTimeFormat(void 0,{weekday:"long",month:"long",day:"numeric"}).format(s)})]})}function lo({compact:t}){const s=new Date,i=d.useMemo(()=>Uy(s),[s]),a=t?["M","T","W","T","F","S","S"]:["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];return e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white",children:[e.jsx(Xt,{className:"size-4 text-[var(--primary)]"}),new Intl.DateTimeFormat(void 0,{month:"long",year:"numeric"}).format(s)]}),e.jsx("div",{className:"text-[12px] text-white/45",children:t?"Mini":"Month view"})]}),e.jsxs("div",{className:"grid grid-cols-7 gap-1.5",children:[a.map(n=>e.jsx("div",{className:"text-center text-[11px] uppercase tracking-[0.14em] text-white/35",children:n},n)),i.map(n=>{const r=n.getMonth()===s.getMonth(),l=n.toDateString()===s.toDateString();return e.jsx("div",{className:re("flex min-h-9 items-center justify-center rounded-xl text-sm",l?"bg-[var(--primary)] text-slate-950":r?"bg-white/[0.04] text-white/78":"bg-transparent text-white/24"),children:n.getDate()},n.toISOString())})]})]})}function oo({surfaceId:t}){const s=`forge.utility.spotify.${t}`,[i,a]=d.useState(()=>Qy(s,"https://open.spotify.com/"));return d.useEffect(()=>{Wy(s,i)},[s,i]),e.jsxs("div",{className:"grid h-full gap-3 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[e.jsx(yp,{className:"size-4 text-[var(--secondary)]"}),e.jsx("span",{className:"text-sm font-semibold",children:"Spotify link"})]}),e.jsx("input",{value:i,onChange:n=>a(n.target.value),className:"w-full rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2.5 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.35)]",placeholder:"Paste a playlist, album, or artist URL"}),e.jsxs("a",{href:i,target:"_blank",rel:"noreferrer",className:"inline-flex min-h-10 items-center justify-center gap-2 rounded-2xl bg-[rgba(78,222,163,0.14)] px-3 py-2 text-sm font-medium text-[var(--secondary)] transition hover:bg-[rgba(78,222,163,0.22)]",children:["Open Spotify",e.jsx(Wi,{className:"size-4"})]})]})}function co({compact:t}){const[s,i]=d.useState(null),[a,n]=d.useState("Locating…");return d.useEffect(()=>{if(typeof navigator>"u"||!navigator.geolocation){n("Location unavailable");return}let r=!1;return navigator.geolocation.getCurrentPosition(async l=>{try{const c=await(await fetch(`https://api.open-meteo.com/v1/forecast?latitude=${l.coords.latitude}&longitude=${l.coords.longitude}¤t=temperature_2m,weather_code`)).json();if(r||!c.current)return;i({temperature:Number(c.current.temperature_2m??0),weatherCode:Number(c.current.weather_code??0)}),n("Live")}catch{r||n("Weather unavailable")}},()=>{r||n("Permission denied")},{maximumAge:3e5,timeout:6e3}),()=>{r=!0}},[]),e.jsxs("div",{className:"flex h-full flex-col justify-between gap-4 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[e.jsx(wp,{className:"size-4 text-[var(--tertiary)]"}),e.jsx("span",{className:"text-sm font-semibold",children:"Weather"})]}),s?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:re("font-display text-white",t?"text-3xl":"text-5xl"),children:[Math.round(s.temperature),"°"]}),e.jsxs("div",{className:"text-sm text-white/58",children:["Code ",s.weatherCode," · ",a]})]}):e.jsx("div",{className:"text-sm text-white/58",children:a})]})}function ho({compact:t,defaultUserId:s}){const i=We(),a=d.useRef(null),n=d.useRef(null),[r,l]=d.useState(""),[o,c]=d.useState(""),x=xe({mutationFn:async()=>$a({contentMarkdown:`# ${r.trim()||"Quick note"}
|
|
11
|
-
|
|
12
|
-
${o.trim()}`,author:"Forge quick capture",userId:s??null,links:[]}),onSuccess:async()=>{l(""),c(""),await i.invalidateQueries({queryKey:["notes-index"]})}}),v=xe({mutationFn:async()=>Fh({title:r.trim()||"Quick capture",contentMarkdown:o.trim(),summary:o.trim().slice(0,180),author:"Forge quick capture"}),onSuccess:async()=>{l(""),c(""),await i.invalidateQueries({queryKey:["wiki-pages"]})}});function u(f,h=f){const m=n.current;if(!m)return;const b=m.selectionStart??0,w=m.selectionEnd??0,M=o.slice(b,w),E=`${o.slice(0,b)}${f}${M}${h}${o.slice(w)}`;c(E),requestAnimationFrame(()=>{m.focus(),m.selectionStart=b+f.length,m.selectionEnd=w+f.length})}return e.jsxs("div",{className:"grid h-full min-h-0 gap-3 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[e.jsx(Ki,{className:"size-4 text-[var(--primary)]"}),e.jsx("span",{className:"text-sm font-semibold",children:"Quick capture"})]}),e.jsx("input",{ref:a,value:r,onChange:f=>l(f.target.value),className:"w-full rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2.5 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.35)]",placeholder:"Title"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[{label:"B",action:()=>u("**")},{label:"I",action:()=>u("_")},{label:"H1",action:()=>u("# ","")},{label:"[]",action:()=>u("- [ ] ","")}].map(f=>e.jsx("button",{type:"button",className:"inline-flex min-h-8 items-center justify-center rounded-xl bg-white/[0.05] px-2.5 text-[12px] font-semibold text-white/72 transition hover:bg-white/[0.08] hover:text-white",onClick:f.action,children:f.label},f.label))}),e.jsx("textarea",{ref:n,value:o,onChange:f=>c(f.target.value),className:re("min-h-0 w-full rounded-[20px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.35)]",t?"h-28":"h-40"),placeholder:"Write a quick note or rough wiki draft"}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs("button",{type:"button",className:"inline-flex min-h-10 items-center justify-center gap-2 rounded-2xl bg-[rgba(192,193,255,0.16)] px-3 py-2 text-sm font-medium text-[var(--primary)] transition hover:bg-[rgba(192,193,255,0.24)] disabled:opacity-50",disabled:!o.trim()||x.isPending,onClick:()=>x.mutate(),children:[e.jsx(Yi,{className:"size-4"}),"Save as note"]}),e.jsxs("button",{type:"button",className:"inline-flex min-h-10 items-center justify-center gap-2 rounded-2xl bg-[rgba(255,185,95,0.16)] px-3 py-2 text-sm font-medium text-[var(--tertiary)] transition hover:bg-[rgba(255,185,95,0.24)] disabled:opacity-50",disabled:!o.trim()||v.isPending,onClick:()=>v.mutate(),children:[e.jsx(Ki,{className:"size-4"}),"Save as wiki"]})]})]})}function Km({eyebrow:t,title:s,description:i,items:a,tone:n="core",className:r}){return e.jsxs("section",{className:re("min-w-0 overflow-hidden rounded-[28px] border border-white/6 shadow-[0_20px_54px_rgba(4,8,18,0.24)]",n==="core"?"bg-[linear-gradient(180deg,rgba(22,28,46,0.98),rgba(12,17,30,0.95))]":"bg-[linear-gradient(180deg,rgba(16,29,33,0.98),rgba(12,22,27,0.95))]",r),children:[e.jsxs("div",{className:re("grid min-w-0 gap-3 px-4 py-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,26rem)] lg:px-5",n==="core"?"bg-[radial-gradient(circle_at_top_right,rgba(192,193,255,0.12),transparent_36%),linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0))]":"bg-[radial-gradient(circle_at_top_right,rgba(110,231,183,0.1),transparent_36%),linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0))]"),children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:re("font-label text-[11px] uppercase tracking-[0.2em]",n==="core"?"text-[var(--secondary)]":"text-[rgba(110,231,183,0.82)]"),children:t}),e.jsx("h2",{className:"mt-2 max-w-3xl font-display text-[clamp(1.35rem,2vw,1.9rem)] leading-none text-white",children:s}),e.jsx("p",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/60",children:i})]}),e.jsx("div",{className:"grid min-w-0 gap-2 sm:grid-cols-3",children:a.slice(0,3).map(l=>l.href?e.jsxs(Ae,{to:l.href,className:re("min-w-0 rounded-[20px] border border-white/6 px-3 py-3 backdrop-blur-sm transition hover:bg-white/[0.08]",n==="core"?"bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.025))]":"bg-[linear-gradient(180deg,rgba(110,231,183,0.08),rgba(255,255,255,0.02))]"),children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:l.label}),e.jsx("div",{className:"mt-1.5 min-w-0 font-medium text-white",children:l.title})]},l.id):e.jsxs("div",{className:re("min-w-0 rounded-[20px] border border-white/6 px-3 py-3 backdrop-blur-sm",n==="core"?"bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.025))]":"bg-[linear-gradient(180deg,rgba(110,231,183,0.08),rgba(255,255,255,0.02))]"),children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:l.label}),e.jsx("div",{className:"mt-1.5 min-w-0 font-medium text-white",children:l.title})]},l.id))})]}),e.jsx("div",{className:"grid min-w-0 gap-3 px-4 py-4 lg:grid-cols-2 lg:px-5",children:a.map((l,o)=>{const c=re("group flex min-h-[13.5rem] min-w-0 flex-col overflow-hidden rounded-[24px] border border-white/7 p-0 transition hover:-translate-y-0.5 hover:shadow-[0_22px_46px_rgba(3,8,18,0.28)] sm:min-h-[15.5rem]",n==="core"?"bg-[linear-gradient(180deg,rgba(19,26,42,0.98),rgba(11,16,28,0.96))] hover:border-white/12 hover:bg-[linear-gradient(180deg,rgba(24,31,50,0.98),rgba(13,19,33,0.97))]":"bg-[linear-gradient(180deg,rgba(17,29,32,0.98),rgba(9,18,22,0.97))] hover:border-white/12 hover:bg-[linear-gradient(180deg,rgba(21,36,40,0.98),rgba(11,22,27,0.97))]"),x=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:re("flex min-w-0 flex-1 flex-col p-4",n==="core"?"bg-[radial-gradient(circle_at_top_left,rgba(192,193,255,0.1),transparent_28%),linear-gradient(180deg,rgba(255,255,255,0.025),rgba(255,255,255,0))]":"bg-[radial-gradient(circle_at_top_left,rgba(110,231,183,0.08),transparent_28%),linear-gradient(180deg,rgba(255,255,255,0.025),rgba(255,255,255,0))]"),children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:l.label}),e.jsx("div",{className:"mt-2.5 min-w-0 font-display text-[1.25rem] leading-tight text-white sm:text-[1.4rem]",children:l.title})]}),l.badge?e.jsx(L,{wrap:!0,className:"max-w-[10rem] shrink-0 self-start bg-white/[0.08] text-white/72",children:l.badge}):null]}),e.jsx("div",{className:"mt-2.5 text-sm leading-6 text-white/60",children:l.detail}),e.jsx("div",{className:"flex-1"})]}),l.href?e.jsx("div",{className:"border-t border-white/6 bg-[linear-gradient(180deg,rgba(255,255,255,0.02),rgba(255,255,255,0.01))] px-4 py-3",children:e.jsxs("div",{className:"inline-flex min-h-10 min-w-0 max-w-full items-center gap-2 rounded-full border border-white/8 bg-white/[0.05] px-4 text-sm text-white/68 transition group-hover:border-white/14 group-hover:bg-white/[0.08] group-hover:text-white",children:[l.actionLabel??"Open",e.jsx(Gt,{className:"size-3.5"})]})}):null]});return e.jsx(Kt.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.22,delay:.04*o,ease:"easeOut"},children:l.href?e.jsx(Ae,{to:l.href,className:c,children:x}):e.jsx("div",{className:c,children:x})},l.id)})})]})}function Ks({label:t,value:s,tone:i="default",detail:a,className:n}){return e.jsxs(ae,{className:re("rounded-[22px] p-4",i==="core"&&"bg-[linear-gradient(180deg,rgba(29,24,48,0.95),rgba(17,17,31,0.92))]",i==="psyche"&&"bg-[linear-gradient(180deg,rgba(18,31,34,0.96),rgba(13,24,27,0.94))]",n),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}),a?e.jsx("div",{className:"mt-2 text-sm text-white/56",children:a}):null]})}function Hy(){const{t}=lt(),s=Je(),i=s.snapshot,a=i.dashboard.milestoneRewards.find(h=>!h.completed)??i.dashboard.milestoneRewards[0]??null,n=i.overview.topTasks[0]??null,r=i.overview.dueHabits[0]??null,l=i.overview.neglectedGoals[0]??null,o=i.overview.recentEvidence[0]??null,c=new Map(i.projects.map(h=>[h.id,h])),x=i.metrics.momentumScore>=80?"Strong":i.metrics.momentumScore>=60?"Steady":"Needs attention",v=i.overview.activeGoals.length>0||i.overview.projects.length>0||i.overview.topTasks.length>0||i.overview.recentEvidence.length>0||i.overview.dueHabits.length>0||i.overview.neglectedGoals.length>0;function u(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}`}if(!v)return e.jsxs("div",{className:"grid min-w-0 gap-4",children:[e.jsx(qe,{title:"Overview",titleText:"Overview",description:"See your main goals, active projects, top tasks, and recent activity in one place.",badge:"0 live signals"}),e.jsx(gt,{eyebrow:t("common.overview.heroEyebrow"),title:t("common.overview.emptyTitle"),description:t("common.overview.emptyDescription"),action:e.jsx(Ae,{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 f=[{id:"hero",title:"Overview",description:"The route header stays movable like any other surface block.",defaultWidth:12,defaultHeight:2,removable:!1,minHeight:2,maxHeight:3,surfaceChrome:"none",defaultTitleVisible:!1,defaultDescriptionVisible:!1,render:()=>e.jsx(qe,{title:"Overview",titleText:"Overview",description:`${x}. Core goals, active projects, top tasks, and momentum are all here.`,badge:`${i.metrics.streakDays} day streak`})},{id:"signals",title:"Action signals",description:"Direct links to the next things worth opening.",defaultWidth:7,defaultHeight:4,minWidth:4,render:()=>e.jsx(Km,{eyebrow:"Actions",title:"Open what matters now",description:"These cards stay compact by default so the page can fit more live context at once.",items:[{id:"top-task",label:n?"Top task":r?"Due habit":"Recovery lane",title:(n==null?void 0:n.title)??(r==null?void 0:r.title)??"Get a real task moving",detail:(n==null?void 0:n.description)||(r==null?void 0:r.description)||"There is no single top task yet, so use this surface to choose one clean next move.",badge:n?`${n.points} xp`:r?`${r.rewardXp} xp`:`${i.metrics.weeklyXp} weekly xp`,href:n?`/tasks/${n.id}`:r?"/habits":"/today",actionLabel:n?"Open task":r?"Open habits":"Open today"},{id:"reward",label:"Next reward",title:(a==null?void 0:a.title)??"Keep the streak alive",detail:(a==null?void 0:a.progressLabel)??`Level ${i.metrics.level} is active. ${i.metrics.weeklyXp} weekly XP is already logged.`,badge:(a==null?void 0:a.rewardLabel)??`${i.metrics.comboMultiplier.toFixed(2)}x combo`,href:"/today",actionLabel:"Open today"},{id:"recent-activity",label:"Recent activity",title:o?tr(o):"No recent evidence",detail:o?sr(o):"The next work closeout or note will appear here.",badge:(o==null?void 0:o.source)??"activity",href:o?u(o):"/activity",actionLabel:"Open"}]})},{id:"summary",title:"Momentum summary",description:"Smaller titles and denser metrics free space for the widgets themselves.",defaultWidth:5,defaultHeight:4,minWidth:4,render:({compact:h})=>e.jsxs("div",{className:"grid h-full gap-3",children:[e.jsxs("div",{className:h?"grid gap-3":"grid gap-3 sm:grid-cols-2",children:[e.jsx(Ks,{label:"Level",value:i.metrics.level,tone:"core",detail:`${i.metrics.currentLevelXp} XP in the current level`}),e.jsx(Ks,{label:"Weekly XP",value:i.metrics.weeklyXp,tone:"core",detail:`${i.metrics.totalXp} total XP recorded`})]}),e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-[0.16em] text-white/38",children:"Goal needing attention"}),e.jsx(L,{className:"bg-white/[0.08] text-white/70",children:(l==null?void 0:l.risk)??"stable"})]}),e.jsx("div",{className:"mt-3 text-base font-semibold text-white",children:(l==null?void 0:l.title)??"No goal is drifting hard right now"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(l==null?void 0:l.summary)??`Only ${i.overview.strategicHeader.overdueTasks} overdue task${i.overview.strategicHeader.overdueTasks===1?"":"s"} are slowing the system.`})]})]})},{id:"goals",title:"Goals",description:"Long-range direction stays visible without taking over the whole page.",defaultWidth:8,defaultHeight:5,minWidth:4,render:({compact:h})=>e.jsx("div",{className:"grid gap-3",children:i.overview.activeGoals.slice(0,h?2:4).map(m=>{var b;return e.jsxs(Ae,{to:`/goals/${m.id}`,className:"rounded-[20px] bg-white/[0.04] p-4 transition hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[e.jsx(Te,{kind:"goal",label:((b=m.tags[0])==null?void 0:b.name)??m.horizon,compact:!0,gradient:!1}),e.jsxs("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:[m.progress,"%"]})]}),e.jsx("div",{className:"mt-3",children:e.jsx(Xe,{kind:"goal",label:m.title,variant:"heading",size:h?"md":"lg",lines:2,className:"max-w-full",labelClassName:"[overflow-wrap:anywhere]"})}),h?null:e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:m.description}),e.jsx("div",{className:"mt-3",children:e.jsx(us,{value:m.progress})}),e.jsx("div",{className:"mt-3",children:e.jsx(Vt,{entityType:"goal",entityId:m.id,count:is(i.dashboard.notesSummaryByEntity,"goal",m.id).count})})]},m.id)})})},{id:"pipeline",title:"Projects, habits, tasks",description:"Execution blocks can shrink while keeping the useful subtitles visible.",defaultWidth:12,defaultHeight:5,minWidth:6,render:({compact:h})=>e.jsxs("div",{className:"grid min-w-0 gap-4 xl:grid-cols-3",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-[0.16em] text-white/38",children:"Projects"}),i.overview.projects.slice(0,h?3:4).map(m=>{var b;return e.jsxs(Ae,{to:`/projects/${m.id}`,className:"rounded-[18px] bg-white/[0.04] px-4 py-3 transition hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-semibold text-white",children:m.title}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:((b=c.get(m.id))==null?void 0:b.status)??"active"})]}),e.jsxs(L,{wrap:!0,className:"max-w-[7rem] shrink-0",children:[m.earnedPoints," xp"]})]}),h?null:e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:m.description})]},m.id)})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-[0.16em] text-white/38",children:"Due habits"}),i.overview.dueHabits.slice(0,h?3:4).map(m=>e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:e.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-semibold text-white",children:m.title}),h?null:e.jsx("div",{className:"mt-1 text-sm text-white/56",children:m.description})]}),e.jsxs(L,{className:"bg-[rgba(78,222,163,0.14)] text-[var(--secondary)]",children:[m.rewardXp," xp"]})]})},m.id))]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-[0.16em] text-white/38",children:"Top tasks"}),i.overview.topTasks.slice(0,h?3:4).map(m=>e.jsx(Ae,{to:`/tasks/${m.id}`,className:"rounded-[18px] bg-white/[0.04] px-4 py-3 transition hover:bg-white/[0.06]",children:e.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-semibold text-white",children:m.title}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:m.status.replaceAll("_"," ")})]}),e.jsxs(L,{className:"bg-white/[0.08] text-white/72",children:[m.points," xp"]})]})},m.id))]})]})},{id:"time",title:"Clock",description:"Optional utility widget.",defaultWidth:3,defaultHeight:2,defaultHidden:!0,render:({compact:h})=>e.jsx(ro,{compact:h})},{id:"weather",title:"Weather",description:"Optional utility widget.",defaultWidth:3,defaultHeight:2,defaultHidden:!0,render:({compact:h})=>e.jsx(co,{compact:h})},{id:"mini-calendar",title:"Mini calendar",description:"Optional utility widget.",defaultWidth:4,defaultHeight:3,defaultHidden:!0,render:({compact:h})=>e.jsx(lo,{compact:h})},{id:"spotify",title:"Spotify",description:"Optional utility widget.",defaultWidth:4,defaultHeight:2,defaultHidden:!0,render:()=>e.jsx(oo,{surfaceId:"overview"})},{id:"quick-capture",title:"Quick capture",description:"Save a standalone note or wiki draft from any dashboard.",defaultWidth:5,defaultHeight:3,defaultHidden:!0,render:({compact:h})=>{var m;return e.jsx(ho,{compact:h,defaultUserId:s.selectedUserIds[0]??((m=i.users[0])==null?void 0:m.id)??null})}}];return e.jsx(_a,{surfaceId:"overview",baseWidgets:f})}const Gy=[10,15,30,45,60];function rc(){return{mode:"add",minutes:15,note:""}}function Um({open:t,onOpenChange:s,entityType:i,entityId:a,targetLabel:n,currentCreditedSeconds:r,pending:l=!1,onSubmit:o}){const[c,x]=d.useState(rc),[v,u]=d.useState(null);d.useEffect(()=>{t&&(x(rc()),u(null))},[t]);const f=fe({queryKey:["forge-xp-metrics"],queryFn:Kh,enabled:t}),h=d.useMemo(()=>{var D;const w=(D=f.data)==null?void 0:D.metrics.rules.find(j=>j.code==="task_run_progress"),M=Math.max(1,Number((w==null?void 0:w.config.intervalMinutes)??10)),E=Number((w==null?void 0:w.config.fixedXp)??4);return{intervalMinutes:M,fixedXp:E,intervalSeconds:M*60}},[f.data]),m=d.useMemo(()=>{const w=Math.max(0,Math.trunc(c.minutes||0)),M=c.mode==="add"?w:-w,E=Math.max(0,Math.floor(r/60)),D=M>=0?M:-Math.min(Math.abs(M),E),j=Math.max(0,r+D*60),S=Math.floor(Math.max(0,r)/h.intervalSeconds),A=Math.floor(j/h.intervalSeconds)-S;return{requestedDeltaMinutes:M,appliedDeltaMinutes:D,nextCreditedSeconds:j,bucketDelta:A,xpDelta:A*h.fixedXp,maxRemovableMinutes:E}},[h.fixedXp,h.intervalSeconds,r,c.minutes,c.mode]),b=[{id:"adjustment",eyebrow:i==="task"?"Task work":"Project work",title:`Adjust tracked work for ${n}`,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:(w,M)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Mode",labelHelp:"Add minutes when work happened off-timer. Remove minutes when the tracked total needs a correction.",children:e.jsx(Ze,{value:w.mode,onChange:E=>M({mode:E}),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(se,{label:"Minutes",description:`Currently tracked: ${Math.floor(r/60)} minutes.`,hint:w.mode==="remove"?`You can remove up to ${m.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(le,{type:"number",min:1,className:"w-36",value:w.minutes,onChange:E=>M({minutes:Number(E.target.value)||0})}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Gy.map(E=>e.jsxs(Q,{type:"button",variant:w.minutes===E?"primary":"secondary",onClick:()=>M({minutes:E}),children:[E," min"]},E))})]})}),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:[m.appliedDeltaMinutes>0?"+":"",m.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:[m.xpDelta>0?"+":"",m.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(m.nextCreditedSeconds/60)," min"]})]})]}),e.jsxs("div",{className:"mt-3 text-sm leading-6 text-white/58",children:["Reward cadence: ",h.fixedXp," XP every ",h.intervalMinutes," credited minutes. ",m.bucketDelta===0?"This change does not cross a reward bucket.":`This change crosses ${Math.abs(m.bucketDelta)} reward bucket${Math.abs(m.bucketDelta)===1?"":"s"}.`]})]}),e.jsx(se,{label:"Note",description:"Optional context for why this correction is being added. The note stays attached to the adjustment metadata.",children:e.jsx(Me,{className:"min-h-28",value:w.note,onChange:E=>M({note:E.target.value}),placeholder:"Captured the review session that happened away from the live timer."})})]})}];return e.jsx(rt,{open:t,onOpenChange:s,eyebrow:i==="task"?"Adjust task work":"Adjust project work",title:`Adjust work for ${n}`,description:"Add or remove tracked minutes without creating a live task run.",value:c,onChange:x,steps:b,submitLabel:"Save adjustment",pending:l,pendingLabel:"Saving adjustment...",error:v,onSubmit:async()=>{var D;u(null);const w=Math.max(0,Math.trunc(c.minutes||0)),M=c.mode==="add"?w:-w,E=av.safeParse({entityType:i,entityId:a,deltaMinutes:M,note:c.note});if(!E.success){u(((D=E.error.issues[0])==null?void 0:D.message)??"Enter a valid minute adjustment.");return}try{await o({entityType:i,entityId:a,deltaMinutes:E.data.deltaMinutes,note:E.data.note||void 0}),s(!1)}catch(j){u(j instanceof Error?j.message:"Could not save the work adjustment right now.")}}})}const Qm={allowWorkBlockKinds:[],blockWorkBlockKinds:[],allowCalendarIds:[],blockCalendarIds:[],allowEventTypes:[],blockEventTypes:[],allowEventKeywords:[],blockEventKeywords:[],allowAvailability:[],blockAvailability:[]};function Xy(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean)}function Tr(t,s){const i=Xy(t);if(i.length===0)return!1;const a=s.join(" ").toLowerCase();return i.some(n=>a.includes(n))}function Vy(t){return t.allowWorkBlockKinds.length>0||t.allowCalendarIds.length>0||t.allowEventTypes.length>0||t.allowEventKeywords.length>0||t.allowAvailability.length>0}function Jy(t,s){return t??s??Qm}function Wm(t){const s=t.rules??Qm,a=(t.at??new Date).getTime(),n=t.overview,r=(n==null?void 0:n.workBlockInstances.filter(f=>{const h=new Date(f.startAt).getTime(),m=new Date(f.endAt).getTime();return h<=a&&a<m}))??[],l=(n==null?void 0:n.events.filter(f=>{if(f.deletedAt)return!1;const h=new Date(f.startAt).getTime(),m=new Date(f.endAt).getTime();return h<=a&&a<m}))??[],o=[],c=r.some(f=>s.blockWorkBlockKinds.includes(f.kind))||l.some(f=>(f.calendarId?s.blockCalendarIds.includes(f.calendarId):!1)||s.blockEventTypes.includes(f.eventType)||s.blockAvailability.includes(f.availability)||Tr(s.blockEventKeywords,[f.title,f.description,f.location,...f.categories]));c&&(r.some(f=>s.blockWorkBlockKinds.includes(f.kind))&&o.push("The current work block is marked as blocked."),l.some(f=>f.calendarId?s.blockCalendarIds.includes(f.calendarId):!1)&&o.push("The active calendar belongs to a blocked calendar source."),l.some(f=>s.blockEventTypes.includes(f.eventType))&&o.push("The active calendar event type is blocked."),l.some(f=>s.blockAvailability.includes(f.availability))&&o.push("The active calendar availability is blocked."),l.some(f=>Tr(s.blockEventKeywords,[f.title,f.description,f.location,...f.categories]))&&o.push("The active calendar event matches a blocked keyword."));const x=Vy(s),v=r.some(f=>s.allowWorkBlockKinds.includes(f.kind))||l.some(f=>(f.calendarId?s.allowCalendarIds.includes(f.calendarId):!1)||s.allowEventTypes.includes(f.eventType)||s.allowAvailability.includes(f.availability)||Tr(s.allowEventKeywords,[f.title,f.description,f.location,...f.categories]));!c&&x&&!v&&o.push("The current calendar context does not match the allowed rules yet.");const u=[...r.map(f=>`${f.title} (${f.kind.replaceAll("_"," ")})`),...l.map(f=>f.title)];return o.length>0?{blocked:!0,label:"Blocked right now",tone:"blocked",conflicts:o,context:u}:u.length>0?{blocked:!1,label:"Allowed right now",tone:"allowed",conflicts:[],context:u}:{blocked:!1,label:x?"Waiting for an allowed calendar context":"No live calendar conflict right now",tone:x?"waiting":"allowed",conflicts:[],context:[]}}function Yy(t,s){return Jy(t.schedulingRules,s)}function Zy(t){return!!(t&&t.startsWith("campaign:"))}function e0(){var Z;const{t}=lt(),s=Je(),i=Array.isArray(s.selectedUserIds)?s.selectedUserIds:[],a=es(),n=ut(),r=We(),[l,o]=d.useState(!1),[c,x]=d.useState(!1),[v,u]=d.useState(!1),[f]=d.useState(()=>{const U=new Date,I=new Date(U);I.setHours(0,0,0,0);const G=new Date(U);return G.setHours(23,59,59,999),{from:I.toISOString(),to:G.toISOString()}}),h=Mt(i),m=s.snapshot.dashboard.projects.find(U=>U.id===a.projectId)??null,b=m?s.snapshot.goals.find(U=>U.id===m.goalId)??null:null,w=m?s.snapshot.tasks.filter(U=>U.projectId===m.id||!U.projectId&&U.goalId===m.goalId):[],M=new Set(w.map(U=>U.id)),E=m?s.snapshot.activity.filter(U=>U.entityId===m.goalId||U.entityId===m.id||M.has(U.entityId)||U.entityType==="task_run"&&typeof U.metadata.taskId=="string"&&M.has(U.metadata.taskId)):[],D=Zy(a.projectId),j=fe({queryKey:["project-board",a.projectId],queryFn:()=>gf(a.projectId),enabled:!!a.projectId&&!D}),S=fe({queryKey:["project-calendar-overview",a.projectId,f.from,f.to,...i],queryFn:()=>Xn({...f,userIds:i}),enabled:!!a.projectId&&!D}),p=xe({mutationFn:U=>Ql(U),onSuccess:async()=>{await Promise.all([r.invalidateQueries({queryKey:["forge-snapshot"]}),r.invalidateQueries({queryKey:["project-board",a.projectId]})])}}),A=xe({mutationFn:Gh,onSuccess:async()=>{await Promise.all([r.invalidateQueries({queryKey:["forge-snapshot"]}),r.invalidateQueries({queryKey:["project-board",a.projectId]}),r.invalidateQueries({queryKey:["forge-xp-metrics"]}),r.invalidateQueries({queryKey:["forge-reward-ledger"]}),r.invalidateQueries({queryKey:["forge-operator-context"]})])}}),T=xe({mutationFn:U=>Hh(a.projectId,{status:U}),onSuccess:async()=>{await Promise.all([r.invalidateQueries({queryKey:["forge-snapshot"]}),r.invalidateQueries({queryKey:["project-board",a.projectId]}),r.invalidateQueries({queryKey:["forge-xp-metrics"]}),r.invalidateQueries({queryKey:["forge-reward-ledger"]}),r.invalidateQueries({queryKey:["forge-operator-context"]})])}}),k=xe({mutationFn:()=>kb(a.projectId),onSuccess:async()=>{await Promise.all([r.invalidateQueries({queryKey:["forge-snapshot"]}),r.invalidateQueries({queryKey:["project-board",a.projectId]})]),n("/projects")}}),$=xe({mutationFn:U=>Ul(U),onSuccess:async()=>{await Promise.all([r.invalidateQueries({queryKey:["forge-snapshot"]}),r.invalidateQueries({queryKey:["project-board",a.projectId]}),r.invalidateQueries({queryKey:["task-context"]})])}}),g=j.data??(m&&b?{project:m,goal:b,tasks:w,activity:E}:void 0),C=s.snapshot.dashboard.projects.find(U=>U.id===a.projectId)??null;if(j.isError&&!D)return e.jsx(ze,{eyebrow:t("common.projectDetail.errorEyebrow"),error:j.error,onRetry:()=>void j.refetch()});if(!g)return e.jsx(It,{});const F=g.tasks.find(U=>U.status==="focus"||U.status==="in_progress")??g.tasks[0]??null,z=g.tasks.find(U=>U.status==="blocked")??g.tasks.find(U=>U.status==="backlog")??null;g.activity[0];const J="notesSummaryByEntity"in g?g.notesSummaryByEntity:s.snapshot.dashboard.notesSummaryByEntity,O=T.isPending||k.isPending,_=Wm({rules:g.project.schedulingRules,overview:(Z=S.data)==null?void 0:Z.calendar}),B=async U=>{await T.mutateAsync(U)},K=async()=>{window.confirm(t("common.projectDetail.deleteProjectConfirm",{title:g.project.title}))&&await k.mutateAsync()};return e.jsxs("div",{className:"grid min-w-0 gap-5",children:[e.jsx(qe,{entityKind:"project",title:e.jsx(Xe,{kind:"project",label:g.project.title,variant:"heading",size:"lg"}),titleText:g.project.title,description:g.project.description?e.jsx(ms,{markdown:g.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(Te,{kind:"goal",label:g.goal.title,compact:!0,gradient:!1}),actions:e.jsx(er,{userId:h,domain:"projects",entityType:"project",entityId:g.project.id,label:g.project.title,description:g.project.description})}),g.project.user?e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-white/62",children:[e.jsx("span",{className:"text-white/42",children:"Owned by"}),e.jsx(Ue,{user:g.project.user})]}):null,D?e.jsxs(ae,{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(Q,{onClick:()=>x(!0),children:t("common.projectDetail.addTask")}),D?null:e.jsx(Q,{variant:"secondary",onClick:()=>u(!0),children:"Adjust work"}),D?null:e.jsx(Q,{variant:"secondary",onClick:()=>o(!0),children:t("common.projectDetail.editProject")}),!D&&g.project.status==="active"?e.jsx(Q,{variant:"secondary",pending:O&&T.variables==="paused",pendingLabel:t("common.projectDetail.suspending"),onClick:()=>void B("paused"),children:t("common.projectDetail.suspendProject")}):null,!D&&g.project.status!=="completed"?e.jsx(Q,{pending:O&&T.variables==="completed",pendingLabel:t("common.projectDetail.finishing"),onClick:()=>void B("completed"),children:t("common.projectDetail.finishProject")}):null,!D&&g.project.status!=="active"?e.jsx(Q,{variant:"secondary",pending:O&&T.variables==="active",pendingLabel:t("common.projectDetail.restarting"),onClick:()=>void B("active"),children:t("common.projectDetail.restartProject")}):null,D?null:e.jsx(Q,{variant:"ghost",pending:k.isPending,pendingLabel:t("common.projectDetail.deleting"),onClick:()=>void K(),children:t("common.projectDetail.deleteProject")}),e.jsx(Ae,{to:`/goals/${g.goal.id}`,children:e.jsx(Q,{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(ae,{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(Te,{kind:"project",compact:!0,gradient:!1}),e.jsx(Te,{kind:"goal",label:g.goal.title,compact:!0,gradient:!1})]})]}),e.jsxs("div",{className:"mt-4 grid gap-3 lg:grid-cols-2",children:[e.jsxs(Ae,{to:F?`/tasks/${F.id}`:`/projects/${g.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")}),F?e.jsx(Te,{kind:"task",compact:!0,gradient:!1}):null]}),e.jsx("div",{className:"mt-2 font-medium text-white",children:(F==null?void 0:F.title)??t("common.projectDetail.noNextTask")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(F==null?void 0:F.description)||t("common.projectDetail.noNextTaskDetail")})]}),e.jsxs(Ae,{to:z?`/tasks/${z.id}`:`/projects/${g.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")}),z?e.jsx(Te,{kind:"task",compact:!0,gradient:!1}):null]}),e.jsx("div",{className:"mt-2 font-medium text-white",children:(z==null?void 0:z.title)??t("common.projectDetail.noRisk")}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(z==null?void 0:z.description)||t("common.projectDetail.noRiskDetail")})]})]})]}),e.jsxs(ae,{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(L,{className:"bg-white/[0.08] text-white/72",children:t(`common.enums.projectStatus.${g.project.status}`)}),e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:g.project.momentumLabel}),e.jsxs(L,{className:"bg-white/[0.08] text-white/72",children:[Math.floor(g.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:[g.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:g.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.${g.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:g.tasks.filter(U=>U.status==="focus"||U.status==="in_progress").length})]})]})]})]}),D?null:e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,1fr)_22rem]",children:[e.jsx(Yl,{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:g.project.schedulingRules,saveLabel:"Save project scheduling",onSave:async({schedulingRules:U})=>{await s.patchProject(g.project.id,{schedulingRules:U}),await r.invalidateQueries({queryKey:["project-board",a.projectId]}),await r.invalidateQueries({queryKey:["project-calendar-overview",a.projectId]})}}),e.jsxs(ae,{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(L,{className:_.tone==="blocked"?"bg-rose-500/14 text-rose-100":_.tone==="waiting"?"bg-amber-500/14 text-amber-100":"bg-emerald-500/14 text-emerald-100",children:_.label}),e.jsx(L,{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."}),_.context.length>0?e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Current context"}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:_.context.map(U=>e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:U},U))})]}):null,_.conflicts.length>0?e.jsx("div",{className:"mt-4 grid gap-2",children:_.conflicts.map(U=>e.jsx("div",{className:"rounded-[16px] bg-rose-500/10 px-3 py-2 text-sm text-rose-100",children:U},U))}):null,e.jsx("div",{className:"mt-4",children:e.jsx(Ae,{to:"/calendar",children:e.jsx(Q,{variant:"secondary",children:"Open calendar workspace"})})})]})]}),e.jsx($m,{tasks:g.tasks,goals:s.snapshot.goals,tags:s.snapshot.tags,notesSummaryByEntity:J,selectedTaskId:null,onMove:async(U,I)=>{await s.patchTaskStatus(U,I),await r.invalidateQueries({queryKey:["project-board",a.projectId]})},onSelectTask:U=>n(`/tasks/${U}`),onQuickReopenTask:async U=>{await p.mutateAsync(U)},onDeleteTask:async U=>{await $.mutateAsync(U)}}),D?null:e.jsx(Zn,{entityType:"project",entityId:g.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(ae,{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:g.activity.slice(0,6).map(U=>e.jsxs(Ae,{to:Gs(U)??`/activity?eventId=${U.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:tr(U)}),e.jsx(L,{children:U.source})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:sr(U)})]},U.id))})]}),e.jsx(Xl,{open:l,goals:s.snapshot.goals,users:s.snapshot.users,editingProject:C,defaultUserId:(C==null?void 0:C.userId)??h,onOpenChange:o,onSubmit:async(U,I)=>{I&&(await s.patchProject(I,U),await r.invalidateQueries({queryKey:["project-board",a.projectId]}))}}),e.jsx(Jn,{open:c,goals:s.snapshot.goals,projects:s.snapshot.dashboard.projects,tags:s.snapshot.tags,users:s.snapshot.users,editingTask:null,initialProjectId:D?null:g.project.id,defaultUserId:g.project.userId??h,onOpenChange:x,onSubmit:async(U,I)=>{I?await Oa(I,U):await s.createTask(U),await r.invalidateQueries({queryKey:["project-board",a.projectId]})}}),D?null:e.jsx(Um,{open:v,onOpenChange:u,entityType:"project",entityId:g.project.id,targetLabel:g.project.title,currentCreditedSeconds:g.project.time.totalCreditedSeconds,pending:A.isPending,onSubmit:async U=>{await A.mutateAsync(U)}})]})}function t0(t){return t.trim().toLowerCase()}function lc(t,s=!1){switch(t.kind){case"goal":return e.jsx(Te,{kind:"goal",label:t.label,compact:!0,gradient:!1});case"task":return e.jsx(Te,{kind:"task",label:t.label,compact:!0,gradient:!1});case"tag":return e.jsx(L,{className:"bg-white/[0.08] text-white/78",children:t.label});case"status":return e.jsx(L,{className:"bg-[rgba(192,193,255,0.12)] text-white/84",children:t.label});case"type":return e.jsx(L,{className:"bg-[rgba(86,170,255,0.12)] text-white/84",children:t.label});case"user":return e.jsx(L,{className:"bg-[rgba(110,231,183,0.12)] text-white/84",children:t.label});default:return t.label}}function s0({query:t,onQueryChange:s,options:i,selectedOptionIds:a,onSelectedOptionIdsChange:n,resultSummary:r}){const[l,o]=d.useState(!1),[c,x]=d.useState(0),v=d.useMemo(()=>a.map(w=>i.find(M=>M.id===w)).filter(Boolean),[i,a]),u=t0(t),f=d.useMemo(()=>{const w=i.filter(M=>!a.includes(M.id));return u?w.filter(M=>`${M.label} ${M.description??""} ${M.searchText??""}`.toLowerCase().includes(u)).slice(0,10):w.slice(0,10)},[u,i,a]),h=w=>{a.includes(w)||(n([...a,w]),s(""),x(0),o(!1))},m=w=>{n(a.filter(M=>M!==w))},b=()=>{s(""),n([]),x(0),o(!1)};return e.jsx("div",{className:"grid gap-3",children:e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(135deg,rgba(19,28,48,0.9),rgba(10,14,26,0.98))] p-4 shadow-[0_30px_80px_rgba(3,8,18,0.28)] sm:p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Project search"}),e.jsx("div",{className:"mt-2 max-w-2xl text-sm leading-6 text-white/62",children:"Search with free text, then pin matching goals, tasks, tags, human users, bot users, statuses, or project-type chips as you narrow the list."})]}),t.trim().length>0||a.length>0?e.jsx("button",{type:"button",onClick:b,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:[v.length>0?e.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:v.map(w=>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:[lc(w,!0),e.jsx("button",{type:"button",className:"rounded-full text-white/52 transition hover:text-white",onClick:()=>m(w.id),"aria-label":`Remove ${w.label}`,children:e.jsx(mt,{className:"size-3.5"})})]},w.id))}):null,e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(bt,{className:"size-4 text-white/36"}),e.jsx("input",{value:t,onChange:w=>{s(w.target.value),o(!0),x(0)},onFocus:()=>o(!0),onBlur:()=>{window.setTimeout(()=>o(!1),120)},onKeyDown:w=>{if(w.key==="Backspace"&&!t&&a.length>0){m(a[a.length-1]);return}if(w.key==="ArrowDown"){w.preventDefault(),o(!0),x(M=>f.length===0?0:Math.min(f.length-1,M+1));return}if(w.key==="ArrowUp"){w.preventDefault(),x(M=>Math.max(0,M-1));return}if(w.key==="Escape"){o(!1);return}w.key==="Enter"&&f[c]&&(w.preventDefault(),h(f[c].id))},placeholder:"Type a project, goal, task, human, bot, user, or tag",className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]}),l?e.jsx("div",{className:"absolute top-full z-20 mt-2 w-full rounded-[22px] border border-white/8 bg-[rgba(8,13,24,0.96)] p-2 shadow-[0_26px_60px_rgba(4,8,18,0.32)] backdrop-blur-xl",children:f.length>0?f.map((w,M)=>e.jsx("button",{type:"button",className:re("flex w-full items-start justify-between gap-3 rounded-[18px] px-3 py-2.5 text-left transition",M===c?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>x(M),onMouseDown:E=>E.preventDefault(),onClick:()=>h(w.id),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:lc(w)}),w.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/46",children:w.description}):null]})},w.id)):e.jsx("div",{className:"px-3 py-2.5 text-sm text-white/42",children:"Keep typing to search by free text, or select a suggested goal, task, human or bot owner, tag, status, or type chip when it appears."})}):null]})]}),e.jsx("div",{className:"mt-3 text-sm text-white/52",children:r})]})})}const i0={execution:"Execution",value:"Value",category:"Category"};function a0(t){return t.trim().toLowerCase()}function n0(){const t=Je(),[s,i]=d.useState("active"),[a,n]=d.useState(""),[r,l]=d.useState([]),[o,c]=d.useState(null),x=d.useMemo(()=>eo(t.snapshot.dashboard.projects),[t.snapshot.dashboard.projects]),v=d.useMemo(()=>{const j=new Map(t.snapshot.dashboard.goals.map(T=>[T.id,T])),S=new Map(t.snapshot.tags.map(T=>[T.id,T])),p=new Map(t.snapshot.users.map(T=>[T.id,T])),A=new Map;for(const T of t.snapshot.tasks){if(!T.projectId)continue;const k=A.get(T.projectId)??[];k.push(T),A.set(T.projectId,k)}return new Map(t.snapshot.dashboard.projects.map(T=>{const k=j.get(T.goalId)??null,$=A.get(T.id)??[],g=T.userId?p.get(T.userId)??null:null,C=new Map;for(const J of(k==null?void 0:k.tags)??[])C.set(J.id,{id:J.id,name:J.name,kind:J.kind});for(const J of $)for(const O of J.tagIds){const _=S.get(O);_&&C.set(_.id,{id:_.id,name:_.name,kind:_.kind})}const F=Array.from(new Set(Array.from(C.values()).map(J=>J.kind))),z=[T.title,T.description,T.goalTitle,(g==null?void 0:g.displayName)??"",(g==null?void 0:g.handle)??"",(g==null?void 0:g.kind)??"",(k==null?void 0:k.description)??"",T.nextTaskTitle??"",T.momentumLabel,T.status,$.map(J=>J.title).join(" "),Array.from(C.values()).map(J=>`${J.name} ${J.kind}`).join(" ")].join(" ").toLowerCase();return[T.id,{tagIds:Array.from(C.keys()),tags:Array.from(C.values()),taskIds:$.map(J=>J.id),typeKeys:F,userId:T.userId,searchText:z}]}))},[t.snapshot.dashboard.goals,t.snapshot.dashboard.projects,t.snapshot.tags,t.snapshot.tasks,t.snapshot.users]),u=d.useMemo(()=>{var g,C,F,z,J;const j=new Map,S=new Map,p=new Map,A=new Map,T=new Map,k=new Map,$=new Map;for(const O of t.snapshot.dashboard.projects){const _=v.get(O.id);if(_){S.has(O.goalId)||S.set(O.goalId,new Set),S.get(O.goalId).add(O.id),T.has(O.status)||T.set(O.status,new Set),T.get(O.status).add(O.id);for(const B of _.taskIds)p.has(B)||p.set(B,new Set),p.get(B).add(O.id);for(const B of _.tags)A.has(B.id)||A.set(B.id,new Set),A.get(B.id).add(O.id);for(const B of _.typeKeys)k.has(B)||k.set(B,new Set),k.get(B).add(O.id);_.userId&&($.has(_.userId)||$.set(_.userId,new Set),$.get(_.userId).add(O.id))}}for(const O of t.snapshot.dashboard.goals){const _=((g=S.get(O.id))==null?void 0:g.size)??0;_!==0&&j.set(`goal:${O.id}`,{id:`goal:${O.id}`,kind:"goal",value:O.id,label:O.title,description:Ke(`${_} project${_===1?"":"s"} linked to this goal`,O.user,`${_} project${_===1?"":"s"} linked to this goal`),searchText:Be([O.title,O.description],O)})}for(const O of t.snapshot.tasks){const _=((C=p.get(O.id))==null?void 0:C.size)??0;_!==0&&j.set(`task:${O.id}`,{id:`task:${O.id}`,kind:"task",value:O.id,label:O.title,description:Ke(`${_} project${_===1?"":"s"} linked to this task`,O.user,`${_} project${_===1?"":"s"} linked to this task`),searchText:Be([O.title,O.description],O)})}for(const O of t.snapshot.tags){const _=((F=A.get(O.id))==null?void 0:F.size)??0;_!==0&&j.set(`tag:${O.id}`,{id:`tag:${O.id}`,kind:"tag",value:O.id,label:O.name,description:Ke(`${_} project${_===1?"":"s"} touching this tag`,O.user,`${_} project${_===1?"":"s"} touching this tag`),searchText:Be([O.name,O.kind,O.description],O)})}for(const[O,_]of Object.entries(x))O==="all"||_===0||j.set(`status:${O}`,{id:`status:${O}`,kind:"status",value:O,label:O==="paused"?"Suspended":O==="completed"?"Finished":"Active",description:`${_} project${_===1?"":"s"} currently ${O==="paused"?"suspended":O==="completed"?"finished":"active"}`,searchText:`${O} ${O==="paused"?"suspended":""} ${O==="completed"?"finished":""}`});for(const[O,_]of Object.entries(i0)){const B=((z=k.get(O))==null?void 0:z.size)??0;B!==0&&j.set(`type:${O}`,{id:`type:${O}`,kind:"type",value:O,label:_,description:`${B} project${B===1?"":"s"} linked to ${_.toLowerCase()} tags`,searchText:`${_} ${O} project type`})}for(const O of t.snapshot.users){const _=((J=$.get(O.id))==null?void 0:J.size)??0;_!==0&&j.set(`user:${O.id}`,{id:`user:${O.id}`,kind:"user",value:O.id,label:O.displayName,description:`${_} project${_===1?"":"s"} owned by this ${O.kind}`,searchText:`${O.displayName} ${O.handle} ${O.kind} ${O.description}`})}return Array.from(j.values()).sort((O,_)=>O.label.localeCompare(_.label))},[x,v,t.snapshot.dashboard.goals,t.snapshot.dashboard.projects,t.snapshot.tags,t.snapshot.tasks,t.snapshot.users]),f=d.useMemo(()=>r.map(j=>u.find(S=>S.id===j)).filter(Boolean),[u,r]),h=d.useMemo(()=>{const j=a0(a);return to(t.snapshot.dashboard.projects,s).filter(S=>{const p=v.get(S.id);return!p||!f.every(T=>{switch(T.kind){case"goal":return S.goalId===T.value;case"task":return p.taskIds.includes(T.value);case"tag":return p.tagIds.includes(T.value);case"status":return S.status===T.value;case"type":return p.typeKeys.includes(T.value);case"user":return p.userId===T.value;default:return!0}})?!1:j?p.searchText.includes(j):!0})},[s,v,a,f,t.snapshot.dashboard.projects]),m=s==="all"?x.all:x[s],w=a.trim().length>0||r.length>0?`${h.length} matching project${h.length===1?"":"s"} in the current collection view`:`${m} project${m===1?"":"s"} in ${s==="all"?"all project states":s==="paused"?"the suspended view":s==="completed"?"the finished view":"the active view"}`,M=async j=>{c(j);try{await t.patchProject(j,{status:"active"})}finally{c(null)}},E=e.jsx("div",{className:"grid gap-4 lg:grid-cols-2 2xl:grid-cols-3",children:h.map(j=>{const S=is(t.snapshot.dashboard.notesSummaryByEntity,"project",j.id),p=v.get(j.id),A=(p==null?void 0:p.tags.slice(0,3))??[];return e.jsxs(ae,{className:"flex h-full flex-col transition hover:bg-white/[0.06]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx(Te,{kind:"goal",label:j.goalTitle,compact:!0}),e.jsx(Ue,{user:j.user,compact:!0})]}),e.jsx(L,{className:j.status==="completed"?"text-emerald-300":j.status==="paused"?"text-amber-300":"text-[var(--primary)]",children:j.status==="paused"?"Suspended":j.status==="completed"?"Finished":"Active"})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Ae,{to:`/projects/${j.id}`,className:"transition hover:opacity-90",children:e.jsx(Xe,{kind:"project",label:j.title,variant:"heading",size:"xl",lines:2})})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:j.description}),A.length>0?e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:A.map(T=>e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:T.name},T.id))}):null,e.jsx("div",{className:"mt-4",children:e.jsx(us,{value:j.progress,tone:j.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:j.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:j.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:j.earnedPoints})]})]}),e.jsx("div",{className:"mt-5 text-[11px] uppercase tracking-[0.16em] text-white/40",children:j.nextTaskTitle?`Next move: ${j.nextTaskTitle}`:"Ready for the next task"}),e.jsx("div",{className:"mt-4",children:e.jsx(Vt,{entityType:"project",entityId:j.id,count:S.count})}),e.jsxs("div",{className:"mt-5 flex flex-wrap items-center justify-between gap-3 pt-1",children:[e.jsx(Ae,{to:`/projects/${j.id}`,children:e.jsx(Q,{variant:"ghost",children:"Open project"})}),s!=="active"&&j.status!=="active"?e.jsx(Q,{variant:"secondary",pending:o===j.id,pendingLabel:"Restarting…",onClick:()=>void M(j.id),children:"Restart"}):null]})]},j.id)})}),D=[{id:"hero",title:"Projects",description:"Route header",defaultWidth:12,defaultHeight:2,removable:!1,surfaceChrome:"none",defaultTitleVisible:!1,defaultDescriptionVisible:!1,render:()=>e.jsx(qe,{entityKind:"project",title:e.jsx(Xe,{kind:"project",label:"Projects",variant:"heading",size:"lg"}),titleText:"Projects",description:"Projects are the concrete paths that move a life goal forward.",badge:`${t.snapshot.dashboard.projects.length} total projects`})},{id:"search-results",title:"Search and results",description:"Search stays grouped with its live result set.",defaultWidth:8,defaultHeight:6,minWidth:6,render:({compact:j})=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(s0,{query:a,onQueryChange:n,options:u,selectedOptionIds:r,onSelectedOptionIdsChange:l,resultSummary:w}),e.jsx(Zl,{value:s,counts:x,onChange:i}),h.length===0?e.jsxs(ae,{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."})]}):j?e.jsx("div",{className:"grid gap-3",children:h.slice(0,5).map(S=>e.jsx(Ae,{to:`/projects/${S.id}`,className:"rounded-[18px] bg-white/[0.04] px-4 py-3 transition hover:bg-white/[0.06]",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-semibold text-white",children:S.title}),e.jsx("div",{className:"text-sm text-white/54",children:S.goalTitle})]}),e.jsxs(L,{className:"shrink-0 bg-white/[0.08] text-white/72",children:[S.earnedPoints," xp"]})]})},S.id))}):E]})},{id:"summary",title:"Collection summary",description:"Counts and spotlight cards.",defaultWidth:4,defaultHeight:5,minWidth:4,render:()=>{const j=h[0]??t.snapshot.dashboard.projects[0]??null;return e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-1",children:[e.jsxs(ae,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Active"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-white",children:x.active})]}),e.jsxs(ae,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Finished"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-white",children:x.completed})]})]}),j?e.jsxs(ae,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Spotlight"}),e.jsx("div",{className:"mt-3 text-base font-semibold text-white",children:j.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:j.description}),e.jsx("div",{className:"mt-3",children:e.jsx(us,{value:j.progress})})]}):null]})}}];return e.jsx("div",{className:"grid gap-5",children:t.snapshot.dashboard.projects.length===0?e.jsx(gt,{eyebrow:"Projects",title:"No projects in flight",description:"Create the first practical path under a life goal so execution, kanban, and evidence all have a concrete home.",action:e.jsx(Ae,{to:"/goals",className:"inline-flex min-h-10 min-w-max shrink-0 items-center justify-center rounded-full bg-white/[0.08] px-4 py-3 text-sm whitespace-nowrap text-white transition hover:bg-white/[0.12]",children:"Open goals"})}):e.jsx(_a,{surfaceId:"projects",baseWidgets:D})})}const Xa=[{to:"/settings",label:"General",icon:vh},{to:"/settings/users",label:"Users",icon:jl},{to:"/settings/calendar",label:"Calendar",icon:Xt},{to:"/settings/mobile",label:"Mobile",icon:jp},{to:"/settings/models",label:"Models",icon:uh},{to:"/settings/agents",label:"Agents",icon:Ui},{to:"/settings/wiki",label:"Wiki",icon:Rn},{to:"/settings/logs",label:"Logs",icon:Np},{to:"/settings/rewards",label:"Rewards",icon:kp},{to:"/settings/bin",label:"Bin",icon:Hr}];function Pr(t,s){return s==="/settings"?t==="/settings":t===s||t.startsWith(`${s}/`)}function vs({className:t}){const s=fi(),[i,a]=d.useState(!1),n=d.useMemo(()=>[...Xa].sort((r,l)=>l.to.length-r.to.length).find(r=>Pr(s.pathname,r.to))??Xa[0],[s.pathname]);return d.useEffect(()=>{if(!i)return;const r=document.body.style.overflow,l=document.body.style.touchAction,o=c=>{c.key==="Escape"&&a(!1)};return document.body.style.overflow="hidden",document.body.style.touchAction="none",window.addEventListener("keydown",o),()=>{document.body.style.overflow=r,document.body.style.touchAction=l,window.removeEventListener("keydown",o)}},[i]),e.jsxs(e.Fragment,{children:[e.jsxs(ae,{className:re("overflow-hidden bg-[linear-gradient(180deg,rgba(15,24,31,0.94),rgba(10,18,25,0.92))] p-2",t),children:[e.jsx("div",{className:"hidden items-center gap-3 lg:flex",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:Xa.map(r=>e.jsxs(hi,{to:r.to,end:r.to==="/settings",className:({isActive:l})=>re("inline-flex items-center gap-2 whitespace-nowrap rounded-full px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] transition",l||Pr(s.pathname,r.to)?"bg-[var(--primary)]/[0.18] text-[var(--primary)]":"bg-white/[0.04] text-white/58 hover:bg-white/[0.08] hover:text-white"),children:[e.jsx(r.icon,{className:"size-3.5"}),e.jsx("span",{children:r.label})]},r.to))})}),e.jsx("div",{className:"flex items-center justify-between gap-3 lg:hidden",children:e.jsxs("button",{type:"button",className:"inline-flex min-w-0 flex-1 items-center justify-between gap-3 rounded-[22px] border border-white/8 bg-[linear-gradient(180deg,rgba(19,28,42,0.96),rgba(11,17,30,0.94))] px-3.5 py-2.5 text-left shadow-[0_18px_38px_rgba(3,8,18,0.2)] transition hover:border-white/12 hover:bg-[linear-gradient(180deg,rgba(24,34,50,0.98),rgba(12,19,34,0.96))]",onClick:()=>a(!0),children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-2xl border border-[var(--primary)]/20 bg-[var(--primary)]/12",children:e.jsx(n.icon,{className:"size-4 text-[var(--primary)]"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[10px] uppercase tracking-[0.18em] text-white/40",children:"Settings section"}),e.jsx("span",{className:"mt-0.5 block truncate text-sm font-medium text-white",children:n.label})]})]}),e.jsx("span",{className:"rounded-full border border-white/8 bg-white/[0.04] px-2.5 py-1 text-[10px] uppercase tracking-[0.16em] text-white/48",children:"Browse"})]})})]}),i&&typeof document<"u"?zn.createPortal(e.jsxs("div",{className:"lg:hidden",children:[e.jsx("div",{className:"fixed inset-0 z-50 bg-[rgba(5,10,18,0.78)] backdrop-blur-xl"}),e.jsx("button",{type:"button","aria-label":"Close settings sections",className:"fixed inset-0 z-[51]",onClick:()=>a(!1)}),e.jsx("div",{className:"pointer-events-none fixed inset-0 z-[52] flex items-end justify-center px-3 pt-3 sm:px-4 sm:pt-4",style:{paddingLeft:"max(0.75rem, calc(var(--forge-safe-area-left) + 0.75rem))",paddingRight:"max(0.75rem, calc(var(--forge-safe-area-right) + 0.75rem))",paddingTop:"max(0.75rem, calc(env(safe-area-inset-top) + 0.75rem))",paddingBottom:"calc(var(--forge-mobile-nav-clearance) - 0.25rem)"},children:e.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Settings sections",className:"pointer-events-auto flex max-h-[min(34rem,calc(100dvh-var(--forge-mobile-nav-clearance)-1rem))] w-full max-w-xl min-h-0 flex-col overflow-hidden rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top,rgba(99,102,241,0.12),transparent_40%),linear-gradient(180deg,rgba(18,27,42,0.98),rgba(10,15,28,0.98))] shadow-[0_36px_110px_rgba(3,8,18,0.5)]",children:[e.jsx("div",{className:"shrink-0 border-b border-white/8 px-4 pb-3 pt-4 sm:px-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-white/38",children:"Settings"}),e.jsxs("div",{className:"mt-1 flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx("div",{className:"truncate text-base font-semibold text-white",children:"Tune Forge"}),e.jsx("span",{className:"rounded-full border border-[var(--primary)]/20 bg-[var(--primary)]/12 px-2.5 py-1 text-[10px] uppercase tracking-[0.16em] text-[var(--primary)]",children:n.label})]}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/55",children:"Jump between users, calendar, models, rewards, and more."})]}),e.jsx("button",{type:"button","aria-label":"Close settings sections",className:"inline-flex size-10 shrink-0 items-center justify-center rounded-full border border-white/8 bg-white/[0.05] text-white/65 transition hover:border-white/12 hover:bg-white/[0.09] hover:text-white",onClick:()=>a(!1),children:e.jsx(mt,{className:"size-4"})})]})}),e.jsx("div",{className:"min-h-0 overflow-y-auto p-3 overscroll-contain sm:p-4",children:e.jsx("div",{className:"grid gap-2",children:Xa.map(r=>{const l=Pr(s.pathname,r.to);return e.jsxs(hi,{to:r.to,end:r.to==="/settings",onClick:()=>a(!1),className:re("group flex items-center justify-between gap-3 rounded-[22px] border px-3.5 py-3 transition-[transform,border-color,background-color,color] duration-150 hover:-translate-y-[1px] hover:text-white",l?"border-[var(--primary)]/18 bg-[var(--primary)]/12 text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:border-white/12 hover:bg-white/[0.06]"),children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:re("flex size-10 shrink-0 items-center justify-center rounded-2xl border transition",l?"border-[var(--primary)]/18 bg-[var(--primary)]/14 text-[var(--primary)]":"border-white/8 bg-[rgba(255,255,255,0.03)] text-white/58 group-hover:border-white/12 group-hover:text-white/80"),children:e.jsx(r.icon,{className:"size-4"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate text-sm font-semibold text-white",children:r.label}),e.jsx("span",{className:"mt-0.5 block text-[10px] uppercase tracking-[0.16em] text-white/35",children:"Forge settings"})]})]}),e.jsx("span",{className:re("rounded-full px-2.5 py-1 text-[10px] uppercase tracking-[0.16em]",l?"bg-[var(--primary)]/16 text-[var(--primary)]":"bg-white/[0.05] text-white/42"),children:l?"Current":"Open"})]},r.to)})})})]})})]}),document.body):null]})}const Hm=[{value:"gpt-5.4",label:"GPT-5.4",description:"Highest quality drafting for long, connected wiki pages."},{value:"gpt-5.4-mini",label:"GPT-5.4 mini",description:"Balanced speed and quality for regular ingest jobs."},{value:"gpt-5.4-nano",label:"GPT-5.4 nano",description:"Fastest and cheapest option for smaller imports."}];Hm[1].value;const r0="medium",l0="medium";function o0(t){const s=t==null?void 0:t.reasoningEffort;return s==="none"||s==="low"||s==="medium"||s==="high"||s==="xhigh"?s:r0}function d0(t){const s=t==null?void 0:t.verbosity;return s==="low"||s==="medium"||s==="high"?s:l0}function oc(t){var i;return{model:((i=Hm.find(a=>a.value===t.model))==null?void 0:i.label)??t.model,reasoning:o0(t.metadata),verbosity:d0(t.metadata),hasKey:!!t.secretId}}function c0(){var O,_;const t=We(),[s,i]=d.useState(""),[a,n]=d.useState(""),[r,l]=d.useState("personal"),[o,c]=d.useState("Fast wiki search"),[x,v]=d.useState("text-embedding-3-small"),[u,f]=d.useState("https://api.openai.com/v1"),[h,m]=d.useState(""),[b,w]=d.useState("1200"),[M,E]=d.useState("200"),D=fe({queryKey:["forge-wiki-settings"],queryFn:Gn}),j=fe({queryKey:["forge-settings"],queryFn:vi}),S=async()=>{await Promise.all([t.invalidateQueries({queryKey:["forge-wiki-settings"]}),t.invalidateQueries({queryKey:["forge-wiki-pages"]}),t.invalidateQueries({queryKey:["forge-wiki-page"]}),t.invalidateQueries({queryKey:["forge-wiki-search"]})])},p=xe({mutationFn:()=>yg({label:s.trim(),description:a.trim(),visibility:r}),onSuccess:async()=>{i(""),n(""),l("personal"),await S()}}),A=xe({mutationFn:()=>Eg({label:o.trim(),model:x.trim(),baseUrl:u.trim(),apiKey:h.trim()||void 0,chunkSize:Number(b),chunkOverlap:Number(M)}),onSuccess:async()=>{m(""),await S()}}),T=xe({mutationFn:({kind:B,profileId:K})=>Lg(B,K),onSuccess:S}),k=xe({mutationFn:()=>Mg(),onSuccess:S}),$=xe({mutationFn:()=>Ag(),onSuccess:S});if(D.isLoading)return e.jsx(nt,{eyebrow:"Wiki settings",title:"Loading wiki controls",description:"Fetching spaces and profile configuration for the Forge wiki."});if(D.isError)return e.jsx(ze,{eyebrow:"Wiki settings",error:D.error,onRetry:()=>void D.refetch()});const g=(O=D.data)==null?void 0:O.settings;if(!g)return e.jsx(ze,{eyebrow:"Wiki settings",error:new Error("Forge returned an empty wiki settings payload."),onRetry:()=>void D.refetch()});const C=g.llmProfiles.find(B=>B.enabled)??g.llmProfiles[0]??null,F=C?oc(C):null,z="Canonical knowledge lives as markdown and media files on disk, with Forge keeping a synced metadata, link, and search index on top. Text search and entity-linked search work without embeddings, while semantic search stays additive and profile-driven. Ingest jobs can create pages and media assets now, with room for richer OCR, transcription, and multimodal compilation later.",J=(_=j.data)==null?void 0:_.settings.modelSettings.forgeAgent.wiki;return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1440px] gap-5",children:[e.jsx(qe,{eyebrow:"File-first memory",title:"Wiki Settings",titleText:"Wiki Settings",description:"Configure file-backed spaces, parse models, and embedding profiles for the Forge wiki memory system.",badge:`${g.spaces.length} spaces · ${g.embeddingProfiles.length} embedding profiles`,actions:e.jsxs(e.Fragment,{children:[e.jsx(Q,{variant:"secondary",pending:k.isPending,pendingLabel:"Syncing",onClick:()=>void k.mutateAsync(),children:"Sync vault"}),e.jsx(Q,{pending:$.isPending,pendingLabel:"Reindexing",onClick:()=>void $.mutateAsync(),disabled:g.embeddingProfiles.length===0,children:"Reindex embeddings"})]})}),e.jsx(vs,{}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ae,{className:"grid gap-4",children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-white",children:"Auto-ingest model"}),e.jsx("div",{className:"text-xs leading-5 text-white/50",children:"Wiki ingest now reads its credentials and model slot from the dedicated Models settings page instead of owning the OpenAI setup flow here."})]})}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.8fr)_minmax(24rem,0.9fr)]",children:[e.jsxs("div",{className:"grid gap-5 rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(22,32,49,0.9),rgba(12,18,31,0.9))] p-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Current profile"}),e.jsx("div",{className:"mt-2 text-xl font-semibold text-white",children:(J==null?void 0:J.connectionLabel)??(C==null?void 0:C.label)??"No external wiki model selected"}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:J!=null&&J.connectionLabel?"Forge now resolves wiki ingest through the selected Models connection and syncs the managed wiki profile automatically.":"Pick a Models connection when you want Forge wiki ingest to run through the OpenAI API or a local compatible endpoint."})]}),e.jsx(Ae,{to:"/settings/models",className:"inline-flex min-h-11 items-center rounded-[16px] bg-white/[0.08] px-4 py-3 text-sm text-white transition hover:bg-white/[0.12]",children:"Open model settings"})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Model"}),e.jsx("div",{className:"mt-2 text-white",children:(J==null?void 0:J.model)??(F==null?void 0:F.model)??"Not set"})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Provider"}),e.jsx("div",{className:"mt-2 text-white",children:(J==null?void 0:J.connectionLabel)??"Not set"})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Endpoint"}),e.jsx("div",{className:"mt-2 flex items-center gap-2 text-white",children:(J==null?void 0:J.baseUrl)??(C==null?void 0:C.baseUrl)??"Not set"})]})]})]}),e.jsxs("div",{className:"grid gap-3 rounded-[28px] border border-white/8 bg-white/[0.03] p-6",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Supported controls"}),e.jsxs("div",{className:"text-sm leading-6 text-white/58",children:["OpenAI API and local compatible endpoints are configured under Settings ","->"," Models. OpenAI Codex OAuth lives there as a chat agent path, while Wiki keeps the file-backed memory controls here and consumes the selected ingest model slot."]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:["GPT-5.4","GPT-5.4 mini","GPT-5.4 nano"].map(B=>e.jsx(L,{className:"bg-white/[0.06] text-white/78",children:B},B))}),e.jsxs(Ae,{to:"/settings/models",className:"inline-flex min-h-11 items-center rounded-[16px] bg-white/[0.08] px-4 py-3 text-sm text-white transition hover:bg-white/[0.12]",children:["Open model settings",e.jsx(Ms,{className:"ml-2 size-4"})]})]})]}),e.jsxs("div",{className:"grid gap-3",children:[g.llmProfiles.length===0?e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 bg-white/[0.02] px-4 py-5 text-sm leading-6 text-white/58",children:"No LLM profile yet. Set up OpenAI once, test it, and Forge will use it for wiki auto-ingest."}):null,g.llmProfiles.map(B=>{const K=oc(B);return e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-white",children:B.label}),e.jsxs("div",{className:"mt-1 text-xs text-white/46",children:[K.model," · thinking ",K.reasoning," · verbosity ",K.verbosity]})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("button",{type:"button",className:"rounded-full p-2 text-white/48 transition hover:bg-white/[0.08] hover:text-white",onClick:()=>void T.mutateAsync({kind:"llm",profileId:B.id}),children:e.jsx(ct,{className:"size-4"})})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs text-white/58",children:[e.jsx(L,{className:"bg-white/[0.06] text-white/76",children:B.baseUrl}),e.jsx(L,{className:"bg-white/[0.06] text-white/76",children:K.hasKey?"key saved":"key missing"})]})]},B.id)})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Sp,{className:"size-4 text-[var(--secondary)]"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"text-sm text-white",children:"Spaces"}),e.jsx(it,{content:z,label:"Explain the wiki operating model"})]}),e.jsx("div",{className:"text-xs leading-5 text-white/50",children:"Personal and shared wiki vaults map to explicit file-backed roots and metadata namespaces."})]})]}),e.jsx("div",{className:"grid gap-3",children:g.spaces.map(B=>e.jsxs("div",{className:"grid gap-1 rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-white",children:B.label}),e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/42",children:B.visibility})]}),e.jsx("div",{className:"text-xs text-white/46",children:B.slug}),e.jsx("div",{className:"text-sm text-white/60",children:B.description||"No description yet."})]},B.id))}),e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsx(le,{value:s,onChange:B=>i(B.target.value),placeholder:"New space label"}),e.jsx(le,{value:a,onChange:B=>n(B.target.value),placeholder:"Description"}),e.jsxs("select",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:r,onChange:B=>l(B.target.value),children:[e.jsx("option",{value:"personal",children:"Personal"}),e.jsx("option",{value:"shared",children:"Shared"})]}),e.jsx(Q,{pending:p.isPending,pendingLabel:"Creating",disabled:!s.trim(),onClick:()=>void p.mutateAsync(),children:"Create space"})]})]}),e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Cp,{className:"size-4 text-[var(--secondary)]"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-white",children:"Embedding profiles"}),e.jsx("div",{className:"text-xs leading-5 text-white/50",children:"Semantic search stays opt-in. The recommended starter is fast and cheap, with heading-aware chunking for agent memory retrieval."})]})]}),e.jsx("div",{className:"grid gap-3",children:g.embeddingProfiles.map(B=>e.jsxs("div",{className:"grid gap-2 rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-white",children:B.label}),e.jsx("button",{type:"button",className:"rounded-full p-2 text-white/48 transition hover:bg-white/[0.08] hover:text-white",onClick:()=>void T.mutateAsync({kind:"embedding",profileId:B.id}),children:e.jsx(ct,{className:"size-4"})})]}),e.jsxs("div",{className:"text-xs text-white/46",children:[B.model," · ",B.baseUrl]}),e.jsxs("div",{className:"text-sm text-white/60",children:["chunkSize ",B.chunkSize," · overlap"," ",B.chunkOverlap]})]},B.id))}),e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.03] p-4",children:[e.jsx(le,{value:o,onChange:B=>c(B.target.value),placeholder:"Profile label"}),e.jsx(le,{value:x,onChange:B=>v(B.target.value),placeholder:"Model"}),e.jsx(le,{value:u,onChange:B=>f(B.target.value),placeholder:"Base URL"}),e.jsx(le,{value:h,onChange:B=>m(B.target.value),placeholder:"API key (optional)",type:"password"}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsx(le,{value:b,onChange:B=>w(B.target.value),placeholder:"Chunk size",type:"number"}),e.jsx(le,{value:M,onChange:B=>E(B.target.value),placeholder:"Chunk overlap",type:"number"})]}),e.jsx(Q,{pending:A.isPending,pendingLabel:"Saving",disabled:!o.trim()||!x.trim(),onClick:()=>void A.mutateAsync(),children:"Save embedding profile"})]})]})]})]})]})}function mo(t){return[{id:"title",label:"Strategy title is set",satisfied:t.title.trim().length>0},{id:"graph",label:"Graph contains at least one linked project or task",satisfied:t.graph.nodes.length>0},{id:"targets",label:"At least one target goal or project is selected",satisfied:t.targetGoalIds.length>0||t.targetProjectIds.length>0},{id:"narrative",label:"The plan already names an overview or end state",satisfied:t.overview.trim().length>0||t.endStateDescription.trim().length>0}]}function Gm(t){return mo(t).every(s=>s.satisfied)}function uo(t){return[{id:"coverage",label:"Agreed work moving",value:t.planCoverageScore,detail:`${t.startedNodeCount}/${t.totalNodeCount} agreed steps have started or finished.`},{id:"order",label:"Order respected",value:t.sequencingScore,detail:`${t.outOfOrderNodeIds.length} step${t.outOfOrderNodeIds.length===1?"":"s"} started before prerequisites were complete.`},{id:"scope",label:"Scope held",value:t.scopeDisciplineScore,detail:`${t.offPlanEntityCount} unagreed item${t.offPlanEntityCount===1?"":"s"} are inside the strategy scope, ${t.offPlanActiveEntityCount} still active.`},{id:"satisfaction",label:"End-state satisfaction",value:t.qualityScore,detail:`${t.targetProgressScore}% target progress with ${t.blockedNodeIds.length} blocked step${t.blockedNodeIds.length===1?"":"s"}.`}]}function h0(t){return t.trim().toLowerCase()}function Fi(t,s){return t.includes(s)?t.filter(i=>i!==s):[...t,s]}function dc(t,s){return t.some(i=>i.entityType===s.entityType&&i.entityId===s.entityId)?t.filter(i=>!(i.entityType===s.entityType&&i.entityId===s.entityId)):[...t,s]}function cc(t,s){if(t.length!==s.length)return!1;const i=new Set(s);return t.every(a=>i.has(a))}function Ln(t="project",s){return{id:`strategy_node_${Math.random().toString(36).slice(2,10)}`,entityType:t,entityId:"",branchLabel:"",notes:"",dependencyMode:"after_previous",customPredecessorIds:[],...s}}function m0(t){const s=new Map(t.graph.nodes.map(o=>[o.id,o])),i=new Map(t.graph.nodes.map(o=>[o.id,0])),a=new Map,n=new Map(t.graph.nodes.map((o,c)=>[o.id,c]));for(const o of t.graph.nodes)a.set(o.id,[]);for(const o of t.graph.edges)i.set(o.to,(i.get(o.to)??0)+1),a.set(o.from,[...a.get(o.from)??[],o.to]);const r=t.graph.nodes.filter(o=>(i.get(o.id)??0)===0).sort((o,c)=>(n.get(o.id)??0)-(n.get(c.id)??0)).map(o=>o.id),l=[];for(;r.length>0;){r.sort((x,v)=>(n.get(x)??0)-(n.get(v)??0));const o=r.shift();if(!o)continue;const c=s.get(o);if(c){l.push(c);for(const x of a.get(o)??[]){const v=(i.get(x)??0)-1;i.set(x,v),v===0&&r.push(x)}}}return l.length===t.graph.nodes.length?l:t.graph.nodes}function u0(t){const s=new Map;for(const a of t.graph.nodes)s.set(a.id,[]);for(const a of t.graph.edges)s.set(a.to,[...s.get(a.to)??[],a.from]);const i=m0(t);return{title:t.title,overview:t.overview,endStateDescription:t.endStateDescription,status:t.status,userId:t.userId??null,targetGoalIds:t.targetGoalIds,targetProjectIds:t.targetProjectIds,linkedEntities:t.linkedEntities,nodes:i.map((a,n)=>{const r=s.get(a.id)??[],l=i[n-1],o=l?s.get(l.id)??[]:[];let c="custom";return r.length===0?c="start":l&&cc(r,[l.id])?c="after_previous":l&&r.length>0&&cc(r,o)&&(c="parallel_with_previous"),Ln(a.entityType,{id:a.id,entityId:a.entityId,branchLabel:a.branchLabel,notes:a.notes,dependencyMode:c,customPredecessorIds:r})})}}function Xm(t){const s=new Map,i=new Set;for(const[a,n]of t.entries()){const r=t[a-1];let l;switch(n.dependencyMode){case"after_previous":l=r?[r.id]:[];break;case"parallel_with_previous":l=r?[...s.get(r.id)??[]]:[];break;case"custom":l=n.customPredecessorIds.filter(o=>i.has(o));break;case"start":default:l=[];break}s.set(n.id,l),i.add(n.id)}return s}function hc(t){const s=Xm(t),i=new Set,a=new Set;function n(r){if(a.has(r))return!0;if(i.has(r))return!1;i.add(r),a.add(r);for(const l of s.get(r)??[])if(n(l))return!0;return a.delete(r),!1}return t.some(r=>n(r.id))}const mc={title:"",overview:"",endStateDescription:"",status:"active",userId:null,targetGoalIds:[],targetProjectIds:[],linkedEntities:[],nodes:[Ln("project",{dependencyMode:"start"})]};function Ni(t,s){const i=s[0];return{title:"",description:"",goalId:(i==null?void 0:i.goalId)??"",projectId:(i==null?void 0:i.id)??"",userId:(i==null?void 0:i.userId)??t,priority:"medium",effort:"deep",energy:"steady",points:60}}function p0(t,s,i){const a=Xm(t.nodes),n=new Set(t.nodes.filter(r=>r.entityId).map(r=>r.id));return{nodes:t.nodes.filter(r=>r.entityId).map(r=>{var l,o;return{id:r.id,entityType:r.entityType,entityId:r.entityId,title:r.entityType==="project"?((l=s.get(r.entityId))==null?void 0:l.title)??r.entityId:((o=i.get(r.entityId))==null?void 0:o.title)??r.entityId,branchLabel:r.branchLabel.trim(),notes:r.notes.trim()}}),edges:t.nodes.flatMap(r=>n.has(r.id)?(a.get(r.id)??[]).filter(l=>n.has(l)).map(l=>({from:l,to:r.id,label:"",condition:""})):[])}}function uc(t){return((t==null?void 0:t.progress)??0)/100}function x0(t){switch(t==null?void 0:t.status){case"done":return 1;case"in_progress":return .66;case"focus":return .5;case"blocked":return .25;default:return 0}}function g0(t){const{draft:s,graph:i,goals:a,projects:n,projectsById:r,tasks:l,tasksById:o}=t,c=new Map(i.nodes.map(K=>[K.id,K.entityType==="project"?uc(r.get(K.entityId)):x0(o.get(K.entityId))])),x=new Map;for(const K of i.nodes)x.set(K.id,[]);for(const K of i.edges)x.set(K.to,[...x.get(K.to)??[],K.from]);const v=i.nodes.filter(K=>(c.get(K.id)??0)>=1).map(K=>K.id),u=i.nodes.filter(K=>(c.get(K.id)??0)>0).map(K=>K.id),f=i.nodes.filter(K=>{var Z,U;return K.entityType==="project"?((Z=r.get(K.entityId))==null?void 0:Z.status)==="paused":((U=o.get(K.entityId))==null?void 0:U.status)==="blocked"}).map(K=>K.id),h=i.nodes.filter(K=>(c.get(K.id)??0)<=0?!1:(x.get(K.id)??[]).some(U=>(c.get(U)??0)<1)).map(K=>K.id),m=i.nodes.filter(K=>(c.get(K.id)??0)>=1?!1:(x.get(K.id)??[]).every(U=>(c.get(U)??0)>=1)).map(K=>K.id),b=new Map(a.map(K=>[K.id,K])),w=s.targetGoalIds.map(K=>{var U;const Z=l.filter(I=>I.goalId===K);return Z.length===0?((U=b.get(K))==null?void 0:U.status)==="completed"?1:0:Z.filter(I=>I.status==="done").length/Z.length}),M=s.targetProjectIds.map(K=>uc(r.get(K))),E=[...w,...M],D=i.nodes.length===0?0:i.nodes.reduce((K,Z)=>K+(c.get(Z.id)??0),0)/i.nodes.length,j=E.length===0?D:E.reduce((K,Z)=>K+Z,0)/E.length,S=new Set(i.nodes.filter(K=>K.entityType==="project").map(K=>K.entityId)),p=new Set(i.nodes.filter(K=>K.entityType==="task").map(K=>K.entityId)),A=new Set,T=new Set,k=new Set;for(const K of s.targetProjectIds){const Z=n.find(U=>U.id===K);if(Z&&!S.has(Z.id)&&Z.status!=="completed"){const U=`project:${Z.id}`;A.add(U),T.add(U)}for(const U of l.filter(I=>I.projectId===K))if(!p.has(U.id)&&["focus","in_progress","done","blocked"].includes(U.status)){const I=`task:${U.id}`;A.add(I),U.status==="done"?k.add(I):T.add(I)}}for(const K of s.targetGoalIds)for(const Z of l.filter(U=>U.goalId===K))if(!p.has(Z.id)&&["focus","in_progress","done","blocked"].includes(Z.status)){const U=`task:${Z.id}`;A.add(U),Z.status==="done"?k.add(U):T.add(U)}const $=Math.max(1,i.nodes.length),g=A.size,C=f.length/$,F=Math.max(0,Math.min(100,Math.round(D*100))),z=Math.max(0,Math.min(100,Math.round(100-h.length/$*100))),J=Math.max(0,Math.min(100,Math.round(100-g/$*100))),O=Math.max(0,Math.min(100,Math.round(Math.max(0,Math.min(1,j*.8+(1-C)*.2))*100))),_=Math.max(0,Math.min(100,Math.round(j*100)));return{alignmentScore:Math.max(0,Math.min(100,Math.round(F*.35+z*.3+J*.2+O*.15))),planCoverageScore:F,sequencingScore:z,scopeDisciplineScore:J,qualityScore:O,targetProgressScore:_,completedNodeCount:v.length,startedNodeCount:u.length,readyNodeCount:m.length,totalNodeCount:$,completedTargetCount:E.filter(K=>K>=1).length,totalTargetCount:E.length,offPlanEntityCount:g,offPlanActiveEntityCount:T.size,offPlanCompletedEntityCount:k.size,activeNodeIds:m.slice(0,8),nextNodeIds:m.slice(0,5),blockedNodeIds:f,outOfOrderNodeIds:h}}function f0({node:t,index:s,total:i,projectsById:a,tasksById:n,usersById:r,allNodes:l,onUpdate:o,onRemove:c}){const{attributes:x,listeners:v,setNodeRef:u,transform:f,transition:h,isDragging:m}=Dl({id:t.id}),b=t.entityType==="project"?a.get(t.entityId):n.get(t.entityId),w=b&&"userId"in b&&b.userId?r.get(b.userId)??b.user??null:null,M=l.slice(0,s);return e.jsxs("div",{ref:u,style:{transform:$l.Transform.toString(f),transition:h},className:re("min-w-0 overflow-hidden rounded-[24px] border border-white/8 bg-[rgba(8,14,26,0.8)] p-4 shadow-[0_24px_60px_rgba(0,0,0,0.2)]",m&&"opacity-70"),children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[e.jsx("button",{type:"button",className:"mt-1 rounded-full bg-white/[0.06] p-2 text-white/58 transition hover:bg-white/[0.1] hover:text-white",...x,...v,children:e.jsx(qn,{className:"size-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(L,{className:"bg-white/[0.08] text-white/76",children:["Step ",s+1]}),e.jsx(L,{className:"bg-white/[0.08] text-white/76",children:t.entityType}),b?e.jsx(Te,{kind:t.entityType,label:b.title,compact:!0,gradient:!1}):null]}),e.jsx("div",{className:"mt-3 text-base font-medium text-white",children:(b==null?void 0:b.title)||"Select an entity for this step"}),e.jsx("div",{className:"mt-2 break-words text-sm leading-6 text-white/54",children:t.notes||(b&&"description"in b?b.description:"")||"Add an optional note if this phase needs intent or setup context."}),w?e.jsx("div",{className:"mt-3",children:e.jsx(Ue,{user:w,compact:!0})}):null]})]}),e.jsxs(Q,{type:"button",variant:"secondary",size:"sm",className:"w-full sm:w-auto",disabled:i===1,onClick:()=>c(t.id),children:[e.jsx(ct,{className:"size-4"}),"Remove"]})]}),e.jsxs("div",{className:"mt-4 grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]",children:[e.jsx(se,{label:"Relationship to the flow",labelHelp:"Keep the sequence mostly linear in the form. Use parallel when this step should open beside the previous one, or custom only when the dependency is special.",children:e.jsx(Ze,{value:t.dependencyMode,columns:2,onChange:E=>o(t.id,{dependencyMode:E}),options:[{value:"start",label:"Start here",description:"This step opens immediately."},{value:"after_previous",label:"After previous",description:"Use the prior step as the gate."},{value:"parallel_with_previous",label:"Parallel with previous",description:"Open beside the prior branch."},{value:"custom",label:"Custom dependency",description:"Pick earlier steps manually."}]})}),e.jsxs("div",{className:"grid gap-4",children:[e.jsx(se,{label:"Branch label",children:e.jsx(le,{value:t.branchLabel,onChange:E=>o(t.id,{branchLabel:E.target.value}),placeholder:"Core path, fallback lane, support branch"})}),e.jsx(se,{label:"Step note",children:e.jsx(Me,{value:t.notes,onChange:E=>o(t.id,{notes:E.target.value}),placeholder:"Explain what has to be true before or after this step."})})]})]}),t.dependencyMode==="custom"?e.jsxs("div",{className:"mt-4 rounded-[20px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Depends on"}),e.jsx("div",{className:"mt-3 grid gap-2",children:M.length===0?e.jsx("div",{className:"text-sm text-white/52",children:"No earlier steps available yet."}):M.map(E=>{const D=E.entityType==="project"?a.get(E.entityId):n.get(E.entityId);return e.jsxs("label",{className:"flex items-start justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-white",children:(D==null?void 0:D.title)||`Step ${l.indexOf(E)+1}`}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/52",children:E.branchLabel||E.entityType})]}),e.jsx("input",{type:"checkbox",checked:t.customPredecessorIds.includes(E.id),onChange:()=>o(t.id,{customPredecessorIds:Fi(t.customPredecessorIds,E.id)})})]},E.id)})})]}):null]})}function Vm({open:t,pending:s=!1,editingStrategy:i,goals:a,projects:n,tasks:r,habits:l,strategies:o,users:c,defaultUserId:x=null,initialStepId:v,onOpenChange:u,onSubmit:f}){const[h,m]=d.useState(mc),[b,w]=d.useState(""),[M,E]=d.useState(""),[D,j]=d.useState(""),[S,p]=d.useState(null),[A,T]=d.useState([]),[k,$]=d.useState(Ni(x,n)),[g,C]=d.useState(!1),[F,z]=d.useState(null),[J,O]=d.useState(!1);d.useEffect(()=>{var V,ge,ye;if(!t)return;const N=i?u0(i):{...mc,userId:x,nodes:[Ln("project",{dependencyMode:"start"})]};m(N),w(""),E(""),j(""),T([]),C(!1),$(Ni(x,n).projectId&&N.targetProjectIds[0]?{...Ni(x,n),goalId:((V=n.find(Ce=>Ce.id===N.targetProjectIds[0]))==null?void 0:V.goalId)??"",projectId:N.targetProjectIds[0]??((ge=n[0])==null?void 0:ge.id)??"",userId:((ye=n.find(Ce=>Ce.id===N.targetProjectIds[0]))==null?void 0:ye.userId)??x}:Ni(x,n)),z(null),p(null)},[x,i,t,n]);const _=d.useDeferredValue(b),B=d.useDeferredValue(M),K=d.useDeferredValue(D),Z=d.useMemo(()=>{const N=new Set(A.map(V=>V.id));return[...A,...r.filter(V=>!N.has(V.id))]},[A,r]),U=d.useMemo(()=>new Map(a.map(N=>[N.id,N])),[a]),I=d.useMemo(()=>new Map(n.map(N=>[N.id,N])),[n]),G=d.useMemo(()=>new Map(Z.map(N=>[N.id,N])),[Z]),W=d.useMemo(()=>new Map(c.map(N=>[N.id,N])),[c]),ne=c.find(N=>N.id===x)??null,de=c.find(N=>N.id===h.userId)??ne,we=(N,V,ge)=>{const ye=h0(N);return ye.length===0||Be(V,ge).includes(ye)},Ne=d.useMemo(()=>a.filter(N=>we(B,[N.title,N.description],N.user)),[B,a]),H=d.useMemo(()=>a.filter(N=>we(_,[N.title,N.description],N.user)),[a,_]),me=d.useMemo(()=>n.filter(N=>we(_,[N.title,N.description,N.goalTitle,N.status],N.user)),[_,n]),y=d.useMemo(()=>n.filter(N=>we(B,[N.title,N.description,N.goalTitle,N.status],N.user)),[B,n]),P=d.useMemo(()=>Z.filter(N=>we(B,[N.title,N.description,N.owner,N.status],N.user)),[Z,B]),q=d.useMemo(()=>l.filter(N=>we(B,[N.title,N.description,N.frequency,N.status],N.user)),[B,l]),pe=d.useMemo(()=>o.filter(N=>N.id!==(i==null?void 0:i.id)&&we(B,[N.title,N.overview,N.endStateDescription,N.status],N.user)),[B,i==null?void 0:i.id,o]),ee=d.useMemo(()=>[...Ne.map(V=>({key:`goal:${V.id}`,entityType:"goal",entityId:V.id,label:V.title,description:Ke(V.description,V.user,"Goal"),user:V.user??null})),...y.map(V=>({key:`project:${V.id}`,entityType:"project",entityId:V.id,label:V.title,description:Ke(`${V.goalTitle}${V.goalTitle?" · ":""}${V.status}`,V.user,`Project · ${V.goalTitle}`),user:V.user??null})),...P.map(V=>({key:`task:${V.id}`,entityType:"task",entityId:V.id,label:V.title,description:Ke(`${V.status} · ${V.owner}`,V.user,`Task · ${V.owner}`),user:V.user??null})),...q.map(V=>({key:`habit:${V.id}`,entityType:"habit",entityId:V.id,label:V.title,description:Ke(V.description,V.user,"Habit"),user:V.user??null})),...pe.map(V=>({key:`strategy:${V.id}`,entityType:"strategy",entityId:V.id,label:V.title,description:Ke(V.overview,V.user,"Strategy"),user:V.user??null}))].sort((V,ge)=>V.label.localeCompare(ge.label)),[Ne,q,y,pe,P]),Y=d.useMemo(()=>p0(h,I,G),[h,I,G]),R=d.useMemo(()=>g0({draft:h,graph:Y,goals:a,projects:n,projectsById:I,tasks:Z,tasksById:G}),[Z,h,Y,a,n,I,G]),X=d.useMemo(()=>[...mo({title:h.title,overview:h.overview,endStateDescription:h.endStateDescription,targetGoalIds:h.targetGoalIds,targetProjectIds:h.targetProjectIds,graph:Y}),{id:"acyclic",label:"Graph stays directed and non-looping",satisfied:!hc(h.nodes)}],[h.endStateDescription,h.nodes,h.overview,h.targetGoalIds,h.targetProjectIds,h.title,Y]),be=d.useMemo(()=>Gm({title:h.title,overview:h.overview,endStateDescription:h.endStateDescription,targetGoalIds:h.targetGoalIds,targetProjectIds:h.targetProjectIds,graph:Y}),[h.endStateDescription,h.overview,h.targetGoalIds,h.targetProjectIds,h.title,Y]),Ie=d.useMemo(()=>uo(R),[R]),te=d.useMemo(()=>{if(!h.title.trim())return"Strategy title is required.";if(h.nodes.length===0)return"Add at least one project or task step.";const N=new Set;for(const V of h.nodes){if(!V.entityId)return"Every step needs a linked project or task.";const ge=`${V.entityType}:${V.entityId}`;if(N.has(ge))return"Each project or task should appear only once in the sequence.";N.add(ge)}return hc(h.nodes)?"Strategy graph must stay directed and non-loopy.":null},[h.nodes,h.title]),ce=N=>N==="sequence"?S??te??(be?null:"This can still be saved as a draft. Add the target plus the overview or end state later, then lock it as the contract from the strategy detail page."):null,Se=d.useMemo(()=>a.filter(N=>we(K,[N.title,N.description],N.user)),[a,K]),he=d.useMemo(()=>n.filter(N=>we(K,[N.title,N.description,N.goalTitle,N.status],N.user)),[n,K]),Ge=d.useMemo(()=>Z.filter(N=>we(K,[N.title,N.description,N.owner,N.status],N.user)),[Z,K]),De=d.useMemo(()=>new Set(h.targetGoalIds),[h.targetGoalIds]),ue=d.useMemo(()=>new Set(h.targetProjectIds),[h.targetProjectIds]),Fe=d.useMemo(()=>new Set(h.nodes.map(N=>`${N.entityType}:${N.entityId}`)),[h.nodes]),dt=d.useMemo(()=>h.targetGoalIds.map(N=>U.get(N)).filter(N=>!!N),[h.targetGoalIds,U]),yt=d.useMemo(()=>h.targetProjectIds.map(N=>I.get(N)).filter(N=>!!N),[h.targetProjectIds,I]),wt=d.useMemo(()=>he.filter(N=>ue.has(N.id)||De.has(N.goalId)),[he,De,ue]),kt=d.useMemo(()=>Ge.filter(N=>ue.has(N.projectId??"")||De.has(N.goalId??"")),[Ge,De,ue]),Qt=d.useMemo(()=>H.slice(0,8),[H]),oe=d.useMemo(()=>me.slice(0,8),[me]),ke=d.useMemo(()=>ee.slice(0,12),[ee]),$e=d.useMemo(()=>Se.slice(0,6),[Se]),Ye=d.useMemo(()=>he.slice(0,8),[he]),Pe=d.useMemo(()=>Ge.slice(0,10),[Ge]),ve=d.useMemo(()=>wt.slice(0,4),[wt]),Ee=d.useMemo(()=>kt.slice(0,6),[kt]),Oe=d.useMemo(()=>{if(!k.goalId)return n;const N=n.filter(V=>V.goalId===k.goalId);return N.length>0?N:n},[k.goalId,n]),tt=K.length>0,Qe=$e.length>0||Ye.length>0||Pe.length>0,St=(N,V)=>{m(ge=>({...ge,nodes:ge.nodes.map(ye=>ye.id===N?{...ye,...V}:ye)}))},Le=(N,V)=>{h.nodes.some(ge=>ge.entityType===N&&ge.entityId===V)||m(ge=>({...ge,nodes:[...ge.nodes,Ln(N,{entityId:V,dependencyMode:ge.nodes.length===0?"start":"after_previous"})]}))},pt=N=>{m(V=>{const ge=V.nodes.filter(ye=>ye.id!==N);return{...V,nodes:ge.map((ye,Ce)=>({...ye,dependencyMode:Ce===0&&ye.dependencyMode==="after_previous"?"start":ye.dependencyMode,customPredecessorIds:ye.customPredecessorIds.filter(xt=>xt!==N)}))}})},_t=Ml(Al(El,{activationConstraint:{distance:6}})),Jt=N=>{!N.over||N.active.id===N.over.id||m(V=>{const ge=V.nodes.findIndex(Ce=>Ce.id===N.active.id),ye=V.nodes.findIndex(Ce=>{var xt;return Ce.id===((xt=N.over)==null?void 0:xt.id)});return ge<0||ye<0?V:{...V,nodes:Th(V.nodes,ge,ye)}})},ws=()=>{const N=D.trim(),V=h.targetProjectIds.map(Ce=>I.get(Ce)).find(Ce=>!!Ce)??I.get(k.projectId)??n[0]??null,ge=(V==null?void 0:V.goalId)??h.targetGoalIds[0]??"",ye=n.find(Ce=>Ce.goalId===ge&&(V?Ce.id===V.id:!0))??n.find(Ce=>Ce.goalId===ge)??V;$(Ce=>({...Ni(x,n),title:N||Ce.title,description:Ce.description,goalId:ge,projectId:(ye==null?void 0:ye.id)??Ce.projectId,userId:(ye==null?void 0:ye.userId)??Ce.userId??x})),z(null),C(!0)},Js=async()=>{const N=I.get(k.projectId);if(!k.title.trim()){z("Task title is required.");return}if(!N){z("Pick a project for the new task.");return}O(!0),z(null);try{const V=W.get(k.userId??N.userId??"")??N.user??de??ne,ge=(await Sn({title:k.title.trim(),description:k.description.trim(),owner:(V==null?void 0:V.displayName)??"Albert",userId:k.userId??N.userId??h.userId,goalId:N.goalId,projectId:N.id,priority:k.priority,status:"focus",effort:k.effort,energy:k.energy,dueDate:"",points:k.points,tagIds:[],notes:[]})).task;T(ye=>[ge,...ye]),Le("task",ge.id),$({...Ni(x,n),goalId:N.goalId,projectId:N.id,userId:ge.userId??N.userId??h.userId}),j(""),C(!1)}catch(V){z(V instanceof Error?V.message:"Task creation failed.")}finally{O(!1)}},Ys=async()=>{if(te){p(te);return}try{await f({title:h.title.trim(),overview:h.overview.trim(),endStateDescription:h.endStateDescription.trim(),status:h.status,userId:h.userId,targetGoalIds:h.targetGoalIds,targetProjectIds:h.targetProjectIds,linkedEntities:h.linkedEntities,graph:Y},i==null?void 0:i.id),p(null),u(!1)}catch(N){p(N instanceof Error?N.message:"Strategy save failed.")}},Zs=[{id:"foundation",eyebrow:"Foundation",title:"Set the owner and the strategic frame",description:"Start with who owns the strategy, what the plan is called, and whether this should open as active, paused, or already landed.",render:(N,V)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(16rem,0.8fr)]",children:[e.jsx(se,{label:"Strategy title",children:e.jsx(le,{value:N.title,onChange:ge=>V({title:ge.target.value}),placeholder:"Land the multi-user planning system"})}),e.jsx(se,{label:"Status",children:e.jsx(Ze,{value:N.status,onChange:ge=>V({status:ge}),options:[{value:"active",label:"Active",description:"Use this when the plan should drive work now."},{value:"paused",label:"Paused",description:"Keep the strategy visible without active pressure."},{value:"completed",label:"Completed",description:"The end state is already landed."}]})})]}),e.jsx(ss,{value:N.userId,users:c,onChange:ge=>V({userId:ge}),label:"Owner user",defaultLabel:ts(ne),help:"Strategies can belong to a human or a bot even when the sequence spans multiple owners."}),e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(135deg,rgba(192,193,255,0.16),rgba(125,211,252,0.08))] px-5 py-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/46",children:"Live posture"}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(Te,{kind:"strategy",label:N.title.trim()||"Untitled strategy",compact:!0,gradient:!1}),e.jsx(L,{className:"bg-white/[0.12] text-white/86",children:N.status}),de?e.jsx(Ue,{user:de,compact:!0}):null]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/62",children:"This flow is built to keep strategy creation as guided as the other major entities in Forge: clear questions first, then a focused sequence stage at the end."})]})]})},{id:"objective",eyebrow:"Objective",title:"Define the objective and the end targets",description:"Capture what this strategy is coordinating, what done looks like, and which goals or projects are the real targets.",render:(N,V)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsx(se,{label:"Overview",children:e.jsx(Me,{value:N.overview,onChange:ge=>V({overview:ge.target.value}),placeholder:"Explain what this strategy is coordinating and why it matters right now."})}),e.jsx(se,{label:"End state",children:e.jsx(Me,{value:N.endStateDescription,onChange:ge=>V({endStateDescription:ge.target.value}),placeholder:"Describe what reality should look like when this strategy lands."})})]}),e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(21,28,44,0.9),rgba(12,17,30,0.88))] px-5 py-5",children:[e.jsx(se,{label:"Search goals or projects",description:"Keep this page search-first. Add only the targets that truly define what this strategy is trying to land.",children:e.jsxs("div",{className:"flex items-center gap-3 rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[e.jsx(bt,{className:"size-4 text-white/42"}),e.jsx(le,{className:"border-none bg-transparent px-0 py-0",value:b,onChange:ge=>w(ge.target.value),placeholder:"Search goals, projects, owners, humans, or bots"})]})}),e.jsxs("div",{className:"mt-5 grid gap-4 xl:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Selected goals"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:dt.length===0?e.jsx(L,{className:"bg-white/[0.08] text-white/62",children:"No target goals yet"}):dt.map(ge=>e.jsxs("button",{type:"button",className:"inline-flex items-center gap-2 rounded-full bg-[rgba(192,193,255,0.14)] px-3 py-1.5 text-sm text-white transition hover:bg-[rgba(192,193,255,0.2)]",onClick:()=>V({targetGoalIds:Fi(N.targetGoalIds,ge.id)}),children:[e.jsx(Te,{kind:"goal",label:ge.title,compact:!0,gradient:!1}),e.jsx("span",{children:"Remove"})]},ge.id))})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Selected projects"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:yt.length===0?e.jsx(L,{className:"bg-white/[0.08] text-white/62",children:"No target projects yet"}):yt.map(ge=>e.jsxs("button",{type:"button",className:"inline-flex items-center gap-2 rounded-full bg-[rgba(192,193,255,0.14)] px-3 py-1.5 text-sm text-white transition hover:bg-[rgba(192,193,255,0.2)]",onClick:()=>V({targetProjectIds:Fi(N.targetProjectIds,ge.id)}),children:[e.jsx(Te,{kind:"project",label:ge.title,compact:!0,gradient:!1}),e.jsx("span",{children:"Remove"})]},ge.id))})]})]})]}),e.jsxs("div",{className:"grid gap-5 xl:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Goal matches"}),_?e.jsxs(L,{className:"bg-white/[0.08] text-white/72",children:[H.length," found"]}):null]}),e.jsx("div",{className:"mt-3 grid gap-3",children:_?Qt.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"No goals match this search yet."}):Qt.map(ge=>{const ye=N.targetGoalIds.includes(ge.id);return e.jsxs("button",{type:"button",className:re("rounded-[22px] border px-4 py-4 text-left transition",ye?"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:()=>V({targetGoalIds:Fi(N.targetGoalIds,ge.id)}),children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-between gap-2",children:[e.jsx(Xe,{kind:"goal",label:ge.title,className:"max-w-full min-w-0"}),e.jsx(Ue,{user:ge.user,compact:!0})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:ge.description||"No strategic note attached yet."})]},ge.id)}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"Search for the goal this strategy is meant to land."})})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Project matches"}),_?e.jsxs(L,{className:"bg-white/[0.08] text-white/72",children:[me.length," found"]}):null]}),e.jsx("div",{className:"mt-3 grid gap-3",children:_?oe.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"No projects match this search yet."}):oe.map(ge=>{const ye=N.targetProjectIds.includes(ge.id);return e.jsxs("button",{type:"button",className:re("rounded-[22px] border px-4 py-4 text-left transition",ye?"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:()=>V({targetProjectIds:Fi(N.targetProjectIds,ge.id)}),children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-between gap-2",children:[e.jsx(Xe,{kind:"project",label:ge.title,className:"max-w-full min-w-0",showIcon:!1}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(L,{className:"bg-white/[0.08] text-white/70",children:ge.goalTitle}),e.jsx(Ue,{user:ge.user,compact:!0})]})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:ge.description||"No project summary attached yet."})]},ge.id)}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"Search for the concrete project this strategy should land or organize."})})]})]})]})},{id:"context",eyebrow:"Context",title:"Keep the right supporting entities in view",description:"Linked entities stay visible in the strategy context without becoming part of the main execution sequence.",render:(N,V)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Search supporting context",description:"Search across goals, projects, tasks, habits, and other strategies.",children:e.jsxs("div",{className:"flex items-center gap-3 rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[e.jsx(bt,{className:"size-4 text-white/42"}),e.jsx(le,{className:"border-none bg-transparent px-0 py-0",value:M,onChange:ge=>E(ge.target.value),placeholder:"Search by title, owner, @handle, human, or bot"})]})}),e.jsx("div",{className:"flex flex-wrap gap-2",children:N.linkedEntities.length===0?e.jsx(L,{className:"bg-white/[0.08] text-white/62",children:"No extra linked context yet"}):N.linkedEntities.map(ge=>{const ye=ee.find(Ce=>Ce.entityType===ge.entityType&&Ce.entityId===ge.entityId);return e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 rounded-full bg-[rgba(192,193,255,0.14)] px-3 py-1.5 text-sm text-white/82 transition hover:bg-[rgba(192,193,255,0.22)]",onClick:()=>V({linkedEntities:N.linkedEntities.filter(Ce=>!(Ce.entityType===ge.entityType&&Ce.entityId===ge.entityId))}),children:[e.jsx(fs,{className:"mr-1 size-3.5"}),(ye==null?void 0:ye.label)??`${ge.entityType}:${ge.entityId}`,e.jsx("span",{children:"Remove"})]},`${ge.entityType}:${ge.entityId}`)})}),e.jsx("div",{className:"grid gap-3",children:B?ke.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"No supporting entities match this search yet."}):ke.map(ge=>{const ye=N.linkedEntities.some(Ce=>Ce.entityType===ge.entityType&&Ce.entityId===ge.entityId);return e.jsxs("label",{className:re("flex items-start justify-between gap-3 rounded-[20px] border px-4 py-4",ye?"border-[rgba(192,193,255,0.24)] bg-[rgba(192,193,255,0.12)]":"border-white/8 bg-white/[0.04]"),children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Te,{kind:ge.entityType,label:ge.label,compact:!0,gradient:!1}),ge.user?e.jsx(Ue,{user:ge.user,compact:!0}):null]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:ge.description})]}),e.jsx("input",{type:"checkbox",checked:ye,onChange:()=>V({linkedEntities:dc(N.linkedEntities,{entityType:ge.entityType,entityId:ge.entityId})})})]},ge.key)}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"Search when you want to pull another entity into the background context. This keeps the page focused instead of dumping every record into one long list."})})]})},{id:"sequence",eyebrow:"Sequence",title:"Build the execution sequence",description:"Search, add steps, and create missing tasks.",render:()=>e.jsxs("div",{className:"grid min-w-0 gap-5",children:[e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(21,28,44,0.9),rgba(12,17,30,0.88))] px-5 py-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Search and add"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Search goals, projects, tasks, humans, and bots."})]}),e.jsxs(L,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[h.nodes.length," planned steps"]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[e.jsx(bt,{className:"size-4 text-white/42"}),e.jsx(le,{className:"border-none bg-transparent px-0 py-0",value:D,onChange:N=>j(N.target.value),placeholder:"Search goals, projects, tasks, owners, humans, or bots"})]}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsxs(Q,{type:"button",className:"w-full justify-start",variant:"secondary",onClick:ws,children:[e.jsx(zt,{className:"size-4"}),"Create new task"]}),g?e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"New task"}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:"Add the task and place it in the sequence."})]}),e.jsx(Q,{type:"button",variant:"secondary",className:"w-full sm:w-auto",onClick:()=>{C(!1),z(null)},children:"Close"})]}),e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsx(se,{label:"Task title",children:e.jsx(le,{value:k.title,onChange:N=>$(V=>({...V,title:N.target.value})),placeholder:"Draft the shared strategy hierarchy view"})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(se,{label:"Goal",children:e.jsxs("select",{value:k.goalId,onChange:N=>{const V=N.target.value,ge=n.find(ye=>ye.goalId===V)??null;$(ye=>({...ye,goalId:V,projectId:(ge==null?void 0:ge.id)??"",userId:(ge==null?void 0:ge.userId)??ye.userId??x}))},className:"min-h-10 rounded-[var(--radius-control)] border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.3)]",children:[e.jsx("option",{value:"",children:"Select goal"}),a.map(N=>e.jsx("option",{value:N.id,children:N.title},N.id))]})}),e.jsx(se,{label:"Project",children:e.jsxs("select",{value:k.projectId,onChange:N=>$(V=>{var ge,ye;return{...V,projectId:N.target.value,goalId:((ge=I.get(N.target.value))==null?void 0:ge.goalId)??V.goalId,userId:((ye=I.get(N.target.value))==null?void 0:ye.userId)??V.userId}}),className:"min-h-10 rounded-[var(--radius-control)] border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.3)]",children:[e.jsx("option",{value:"",children:"Select project"}),Oe.map(N=>e.jsx("option",{value:N.id,children:N.title},N.id))]})})]}),e.jsx(se,{label:"Notes",children:e.jsx(Me,{value:k.description,onChange:N=>$(V=>({...V,description:N.target.value})),placeholder:"Optional detail or acceptance note."})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(se,{label:"Priority",children:e.jsxs("select",{value:k.priority,onChange:N=>$(V=>({...V,priority:N.target.value})),className:"min-h-10 rounded-[var(--radius-control)] border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.3)]",children:[e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"medium",children:"Medium"}),e.jsx("option",{value:"high",children:"High"}),e.jsx("option",{value:"critical",children:"Critical"})]})}),e.jsx(se,{label:"Points",children:e.jsx(le,{type:"number",value:k.points,onChange:N=>$(V=>({...V,points:Number(N.target.value)||0}))})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(se,{label:"Effort",children:e.jsxs("select",{value:k.effort,onChange:N=>$(V=>({...V,effort:N.target.value})),className:"min-h-10 rounded-[var(--radius-control)] border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.3)]",children:[e.jsx("option",{value:"light",children:"Light"}),e.jsx("option",{value:"deep",children:"Deep"}),e.jsx("option",{value:"extended",children:"Extended"})]})}),e.jsx(se,{label:"Energy",children:e.jsxs("select",{value:k.energy,onChange:N=>$(V=>({...V,energy:N.target.value})),className:"min-h-10 rounded-[var(--radius-control)] border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white outline-none transition focus:border-[rgba(192,193,255,0.3)]",children:[e.jsx("option",{value:"calm",children:"Calm"}),e.jsx("option",{value:"steady",children:"Steady"}),e.jsx("option",{value:"intense",children:"Intense"})]})})]}),F?e.jsx("div",{className:"rounded-[18px] border border-rose-400/20 bg-rose-500/[0.08] px-4 py-3 text-sm text-rose-100/90",children:F}):null,e.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[e.jsx(Q,{type:"button",variant:"secondary",className:"w-full sm:w-auto",onClick:()=>{C(!1),z(null)},children:"Cancel"}),e.jsxs(Q,{type:"button",className:"w-full sm:w-auto",pending:J,pendingLabel:"Creating task",onClick:()=>void Js(),children:[e.jsx(zt,{className:"size-4"}),"Create task"]})]})]})]}):null,tt?Qe?e.jsxs("div",{className:"grid gap-3",children:[$e.length>0?e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Goals"}):null,$e.map(N=>{const V=h.targetGoalIds.includes(N.id),ge=h.linkedEntities.some(ye=>ye.entityType==="goal"&&ye.entityId===N.id);return e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Te,{kind:"goal",label:N.title,compact:!0,gradient:!1}),e.jsx(Ue,{user:N.user,compact:!0})]}),N.description?e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:N.description}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Q,{type:"button",className:"w-full sm:w-auto",variant:V?"secondary":"primary",onClick:()=>m(ye=>({...ye,targetGoalIds:Fi(ye.targetGoalIds,N.id)})),children:V?"Targeted":"Add target"}),e.jsx(Q,{type:"button",className:"w-full sm:w-auto",variant:"secondary",onClick:()=>m(ye=>({...ye,linkedEntities:dc(ye.linkedEntities,{entityType:"goal",entityId:N.id})})),children:ge?"Unlink":"Link"})]})]})},N.id)}),Ye.length>0?e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Projects"}):null,Ye.map(N=>{const V=Fe.has(`project:${N.id}`);return e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Te,{kind:"project",label:N.title,compact:!0,gradient:!1}),e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:N.goalTitle}),e.jsx(Ue,{user:N.user,compact:!0})]}),N.description?e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:N.description}):null]}),e.jsx(Q,{type:"button",className:"w-full sm:w-auto",variant:V?"secondary":"primary",disabled:V,onClick:()=>Le("project",N.id),children:V?"In sequence":"Add step"})]})},`sequence-project:${N.id}`)}),Pe.length>0?e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Tasks"}):null,Pe.map(N=>{const V=Fe.has(`task:${N.id}`);return e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Te,{kind:"task",label:N.title,compact:!0,gradient:!1}),e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:N.status}),e.jsx(Ue,{user:N.user,compact:!0})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:N.description||`${N.owner} · ${N.projectId}`})]}),e.jsx(Q,{type:"button",className:"w-full sm:w-auto",variant:V?"secondary":"primary",disabled:V,onClick:()=>Le("task",N.id),children:V?"In sequence":"Add step"})]})},`sequence-task:${N.id}`)})]}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"No goals, projects, or tasks match this search."}):ve.length>0||Ee.length>0?e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Suggested from targets"}),ve.map(N=>{const V=Fe.has(`project:${N.id}`);return e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Te,{kind:"project",label:N.title,compact:!0,gradient:!1}),e.jsx(Ue,{user:N.user,compact:!0})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:N.description||N.goalTitle})]}),e.jsx(Q,{type:"button",className:"w-full sm:w-auto",variant:V?"secondary":"primary",disabled:V,onClick:()=>Le("project",N.id),children:V?"In sequence":"Add step"})]})},`suggested-project:${N.id}`)}),Ee.map(N=>{const V=Fe.has(`task:${N.id}`);return e.jsx("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Te,{kind:"task",label:N.title,compact:!0,gradient:!1}),e.jsx(Ue,{user:N.user,compact:!0})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:N.description||`${N.owner} · ${N.status}`})]}),e.jsx(Q,{type:"button",className:"w-full sm:w-auto",variant:V?"secondary":"primary",disabled:V,onClick:()=>Le("task",N.id),children:V?"In sequence":"Add step"})]})},`suggested-task:${N.id}`)})]}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/56",children:"Type to search."})]})]}),e.jsxs("div",{className:"grid min-w-0 gap-4",children:[e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.03] px-5 py-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Sequence"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Keep the flow mostly linear here. When a step should open beside the previous one, switch it to parallel. Use custom only for special joins."})]}),e.jsxs(L,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[h.nodes.length," planned steps"]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[h.targetGoalIds.map(N=>{const V=U.get(N);return V?e.jsx(Te,{kind:"goal",label:V.title,compact:!0,gradient:!1},N):null}),h.targetProjectIds.map(N=>{const V=I.get(N);return V?e.jsx(Te,{kind:"project",label:V.title,compact:!0,gradient:!1},N):null})]})]}),e.jsx(Ll,{sensors:_t,collisionDetection:Ih,onDragEnd:Jt,children:e.jsx(yn,{items:h.nodes.map(N=>N.id),strategy:jn,children:e.jsx("div",{className:"grid gap-3",children:h.nodes.map((N,V)=>e.jsx(f0,{node:N,index:V,total:h.nodes.length,projectsById:I,tasksById:G,usersById:W,allNodes:h.nodes,onUpdate:St,onRemove:pt},N.id))})})})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Contract readiness"}),e.jsx("div",{className:"mt-3 grid gap-2",children:X.map(N=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[14px] bg-white/[0.03] px-3 py-2",children:[e.jsx("div",{className:"text-sm text-white/62",children:N.label}),e.jsx(L,{className:N.satisfied?"bg-emerald-500/12 text-emerald-200":"bg-amber-500/12 text-amber-200",children:N.satisfied?"Ready":"Missing"})]},N.id))})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Alignment preview"}),e.jsx("div",{className:"mt-3 grid gap-3",children:Ie.map(N=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm text-white/60",children:[e.jsx("span",{children:N.label}),e.jsxs("span",{children:[N.value,"%"]})]}),e.jsx(us,{value:N.value,className:"mt-2"})]},N.id))})]})]})]})}];return e.jsx(rt,{open:t,onOpenChange:u,eyebrow:"Strategy",title:i?"Edit strategy":"Create strategy",description:"Strategies connect goals, projects, and tasks into a guided multi-step plan with a focused sequence builder at the end.",value:h,onChange:m,steps:Zs,initialStepId:v,contentClassName:"lg:h-[min(56rem,calc(100vh-1rem))] lg:w-[min(78rem,calc(100vw-1.5rem))]",submitLabel:i?be?"Save strategy":"Save draft":be?"Create strategy":"Create draft",pending:s,pendingLabel:"Saving strategy",resolveError:ce,onSubmit:Ys})}function b0(t){return t.trim().toLowerCase()}function v0(){const t=Je(),s=ut(),i=We(),[a,n]=Pt(),[r,l]=d.useState(!1),[o,c]=d.useState(null),[x,v]=d.useState(""),u=Mt(t.selectedUserIds);d.useEffect(()=>{a.get("create")==="1"&&(c(null),l(!0),n(D=>{const j=new URLSearchParams(D);return j.delete("create"),j},{replace:!0}))},[a,n]);const f=async()=>{await i.invalidateQueries({queryKey:["strategy-detail"]}),await t.refresh()},h=xe({mutationFn:async({input:D,strategyId:j})=>j?(await Jr(j,D)).strategy:(await ob(D)).strategy,onSuccess:async()=>{await f()}}),m=xe({mutationFn:async D=>Bh(D),onSuccess:async()=>{await f()}}),b=d.useMemo(()=>new Map(t.snapshot.goals.map(D=>[D.id,D])),[t.snapshot.goals]),w=d.useMemo(()=>new Map(t.snapshot.dashboard.projects.map(D=>[D.id,D])),[t.snapshot.dashboard.projects]),M=d.useMemo(()=>new Map(t.snapshot.tasks.map(D=>[D.id,D])),[t.snapshot.tasks]),E=d.useMemo(()=>{const D=b0(x);return D?t.snapshot.strategies.filter(j=>{var T,k,$;const S=j.targetGoalIds.map(g=>{var C;return((C=b.get(g))==null?void 0:C.title)??""}).join(" "),p=j.targetProjectIds.map(g=>{var C;return((C=w.get(g))==null?void 0:C.title)??""}).join(" "),A=j.graph.nodes.map(g=>{var C,F;return g.entityType==="project"?((C=w.get(g.entityId))==null?void 0:C.title)??"":((F=M.get(g.entityId))==null?void 0:F.title)??""}).join(" ");return[j.title,j.overview,j.endStateDescription,j.status,((T=j.user)==null?void 0:T.displayName)??"",((k=j.user)==null?void 0:k.handle)??"",(($=j.user)==null?void 0:$.kind)??"",S,p,A].join(" ").toLowerCase().includes(D)}):t.snapshot.strategies},[b,w,x,t.snapshot.strategies,M]);return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{title:"Strategies",titleText:"Strategies",description:"Strategies connect human and bot work into a directed plan, with explicit end goals, ownership, and live alignment metrics.",badge:`${t.snapshot.strategies.length} strategies`,actions:e.jsxs(Q,{onClick:()=>{c(null),l(!0)},children:[e.jsx(zt,{className:"size-4"}),"New strategy"]})}),e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(bt,{className:"size-4 text-white/38"}),e.jsx(le,{value:x,onChange:D=>v(D.target.value),placeholder:"Search strategy title, target, graph node, human, or bot"})]}),e.jsx("div",{className:"text-sm text-white/56",children:"Search includes owners, target goals/projects, and graph nodes so cross-user plans stay discoverable."})]}),E.length===0?e.jsx(gt,{eyebrow:"Strategies",title:"No strategies in this scope",description:"Create a strategy to connect projects and tasks into a non-looping execution plan across human and bot actors.",action:e.jsx(Q,{onClick:()=>{c(null),l(!0)},children:"Create strategy"})}):e.jsx("div",{className:"grid gap-4",children:E.map(D=>{const j=D.graph.nodes.filter(p=>D.metrics.activeNodeIds.includes(p.id)),S=uo(D.metrics);return e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0",children:e.jsxs("button",{type:"button",className:"text-left",onClick:()=>s(`/strategies/${D.id}`),children:[e.jsx("div",{className:"font-display text-2xl text-white",children:D.title}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:D.overview||D.endStateDescription})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Ue,{user:D.user}),e.jsx(L,{className:D.isLocked?"bg-amber-500/12 text-amber-200":"bg-emerald-500/12 text-emerald-200",children:D.isLocked?"Contract locked":"Editable draft"}),e.jsx(L,{className:"bg-white/[0.08] text-white/78",children:D.status}),e.jsxs(L,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[D.metrics.alignmentScore,"% aligned"]})]})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Graph progress"}),e.jsxs("div",{className:"mt-2 text-xl text-white",children:[D.metrics.startedNodeCount,"/",D.metrics.totalNodeCount]}),e.jsxs("div",{className:"text-xs leading-5 text-white/46",children:[D.metrics.completedNodeCount," completed"]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Ready branches"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:D.metrics.readyNodeCount}),e.jsx("div",{className:"text-xs leading-5 text-white/46",children:"Nodes whose prerequisites are already satisfied."})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"End targets"}),e.jsxs("div",{className:"mt-2 text-xl text-white",children:[D.metrics.completedTargetCount,"/",D.metrics.totalTargetCount||0]}),e.jsxs("div",{className:"text-xs leading-5 text-white/46",children:[D.metrics.targetProgressScore,"% target progress"]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Sequencing"}),e.jsxs("div",{className:"mt-2 text-xl text-white",children:[D.metrics.sequencingScore,"%"]})]})]}),e.jsxs("div",{className:"grid gap-3 xl:grid-cols-[minmax(0,1.2fr)_minmax(16rem,0.8fr)]",children:[e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Active next nodes"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:j.length===0?e.jsx("div",{className:"text-sm text-white/52",children:"No currently open branch."}):j.map(p=>e.jsx(L,{className:"bg-white/[0.08] text-white/80",children:p.title},p.id))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Alignment breakdown"}),e.jsx("div",{className:"mt-3 grid gap-2 text-sm text-white/58",children:S.map(p=>e.jsxs("div",{children:[p.label," ",p.value,"%"]},p.id))})]})]})}),e.jsxs("div",{className:"flex flex-wrap items-end justify-end gap-2",children:[D.isLocked?null:e.jsxs(Q,{variant:"secondary",onClick:()=>{c(D),l(!0)},children:[e.jsx(mi,{className:"size-4"}),"Edit"]}),e.jsxs(Q,{variant:"secondary",pending:m.isPending&&m.variables===D.id,pendingLabel:"Deleting strategy",onClick:()=>{window.confirm(`Delete strategy "${D.title}"?`)&&m.mutateAsync(D.id)},children:[e.jsx(ct,{className:"size-4"}),"Delete"]}),e.jsx(Q,{onClick:()=>s(`/strategies/${D.id}`),children:"Open strategy"})]})]})]},D.id)})}),e.jsx(Vm,{open:r,pending:h.isPending,editingStrategy:o,goals:t.snapshot.dashboard.goals,projects:t.snapshot.dashboard.projects,tasks:t.snapshot.tasks,habits:t.snapshot.habits,strategies:t.snapshot.strategies,users:t.snapshot.users,defaultUserId:u,onOpenChange:l,onSubmit:async(D,j)=>{await h.mutateAsync({input:D,strategyId:j})}})]})}function Jm(t){const s=new Map;for(const n of t.nodes)s.set(n.id,[]);for(const n of t.edges)s.set(n.to,[...s.get(n.to)??[],n.from]);const i=new Map,a=n=>{const r=i.get(n);if(r!==void 0)return r;const l=s.get(n)??[],o=l.length===0?0:Math.max(...l.map(c=>a(c)))+1;return i.set(n,o),o};for(const n of t.nodes)a(n.id);return i}function w0(t){const s=Jm(t),i=new Map;for(const a of t.nodes){const n=s.get(a.id)??0;i.set(n,[...i.get(n)??[],a.id])}return Array.from(i.entries()).sort((a,n)=>a[0]-n[0]).map(([a,n])=>({level:a,nodeIds:n}))}function y0(t,s){const i=Jm(t.graph),a=new Map;for(const n of t.graph.nodes){const r=i.get(n.id)??0;a.set(r,[...a.get(r)??[],n.id])}return t.graph.nodes.map(n=>{const r=i.get(n.id)??0,l=(a.get(r)??[]).indexOf(n.id),o=t.metrics.activeNodeIds.includes(n.id),c=t.metrics.blockedNodeIds.includes(n.id),x=t.metrics.outOfOrderNodeIds.includes(n.id),v=!o&&!c&&!x,u=(s==null?void 0:s.get(n.id))??null;let f="border-white/10 bg-[rgba(8,14,26,0.92)]";return o?f="border-emerald-400/30 bg-emerald-500/[0.08]":c?f="border-rose-400/28 bg-rose-500/[0.08]":x?f="border-amber-400/28 bg-amber-500/[0.08]":t.metrics.completedNodeCount>0&&(f="border-sky-400/20 bg-sky-500/[0.05]"),{id:n.id,position:{x:72+r*308,y:56+l*168},draggable:!1,selectable:!1,data:{label:e.jsxs("div",{className:`min-w-[220px] rounded-[22px] border px-4 py-4 shadow-[0_24px_70px_rgba(0,0,0,0.24)] ${f}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(L,{className:"bg-white/[0.08] text-white/74",children:n.entityType}),o?e.jsx(L,{className:"bg-emerald-500/12 text-emerald-200",children:"Active"}):null,c?e.jsx(L,{className:"bg-rose-500/12 text-rose-200",children:"Blocked"}):null,x?e.jsx(L,{className:"bg-amber-500/12 text-amber-200",children:"Out of order"}):null,v&&!c&&!x?e.jsx(L,{className:"bg-sky-500/12 text-sky-200",children:"In plan"}):null]}),e.jsx("div",{className:"mt-3 text-base font-medium leading-6 text-white",children:n.title}),n.branchLabel?e.jsx("div",{className:"mt-2 text-xs uppercase tracking-[0.16em] text-white/45",children:n.branchLabel}):null,n.notes?e.jsx("div",{className:"mt-2 text-sm leading-5 text-white/56",children:n.notes}):null,u?e.jsxs("div",{className:"mt-3 flex items-center gap-2 text-xs text-white/52",children:[e.jsx("span",{className:"inline-block size-2.5 rounded-full",style:{backgroundColor:u.color}}),e.jsx("span",{children:u.label})]}):null]})},style:{background:"transparent",border:"none",padding:0}}})}function j0(t){return t.graph.edges.map(s=>{const i=t.metrics.activeNodeIds.includes(s.to),a=t.metrics.blockedNodeIds.includes(s.to),n=t.metrics.outOfOrderNodeIds.includes(s.to);let r="rgba(255,255,255,0.3)";return i?r="#4ade80":a?r="#fb7185":n&&(r="#f59e0b"),{id:`${s.from}->${s.to}`,source:s.from,target:s.to,label:s.label||void 0,animated:i,markerEnd:{type:wh.ArrowClosed,color:r},style:{stroke:r,strokeWidth:i?2.4:1.5},labelStyle:{fill:"rgba(255,255,255,0.56)",fontSize:11,fontWeight:600}}})}function N0({strategy:t,ownerByNodeId:s,heightClassName:i="h-[540px]"}){const a=d.useMemo(()=>y0(t,s),[s,t]),n=d.useMemo(()=>j0(t),[t]);return e.jsx("div",{className:`${i} rounded-[24px] bg-[radial-gradient(circle_at_top,rgba(125,211,252,0.08),transparent_32%),radial-gradient(circle_at_bottom_right,rgba(244,185,122,0.10),transparent_38%),linear-gradient(180deg,rgba(6,10,20,0.97),rgba(8,14,26,0.94))]`,children:e.jsxs(kl,{fitView:!0,nodes:a,edges:n,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!1,attributionPosition:"bottom-left",children:[e.jsx(Cl,{showInteractive:!1}),e.jsx(Sl,{gap:28,size:1,color:"rgba(255,255,255,0.06)"})]})})}function k0(t,s){const i=t.metrics.activeNodeIds.includes(s),a=t.metrics.blockedNodeIds.includes(s),n=t.metrics.outOfOrderNodeIds.includes(s);return a?{label:"Blocked",className:"bg-rose-500/12 text-rose-200"}:n?{label:"Out of order",className:"bg-amber-500/12 text-amber-200"}:i?{label:"Ready now",className:"bg-emerald-500/12 text-emerald-200"}:{label:"In plan",className:"bg-sky-500/12 text-sky-200"}}function S0({strategy:t,projectsById:s,tasksById:i,className:a}){const n=d.useMemo(()=>w0(t.graph),[t.graph]),r=d.useMemo(()=>{const c=new Map;for(const x of t.graph.nodes)c.set(x.id,[]);for(const x of t.graph.edges)c.set(x.to,[...c.get(x.to)??[],x.from]);return c},[t.graph]),[l,o]=d.useState([]);return e.jsxs("div",{className:a??"grid gap-3",children:[n.map(c=>{const x=l.includes(c.level),v=c.level===0?"Launch phase":`Phase ${c.level+1}`,u=c.nodeIds.length>1;return e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.03]",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 px-4 py-4",children:[e.jsxs("button",{type:"button",className:"flex min-w-0 items-center gap-3 text-left",onClick:()=>o(f=>x?f.filter(h=>h!==c.level):[...f,c.level]),children:[e.jsx("span",{className:"rounded-full bg-white/[0.06] p-2 text-white/72",children:x?e.jsx(yh,{className:"size-4"}):e.jsx(Ji,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:v}),e.jsx("div",{className:"mt-1 text-sm text-white/60",children:u?"These branches can progress in parallel once the previous phase is complete.":"This phase advances as one focused step in the strategy."})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(L,{className:"bg-white/[0.08] text-white/76",children:[c.nodeIds.length," node",c.nodeIds.length===1?"":"s"]}),e.jsx(L,{className:"bg-white/[0.08] text-white/76",children:u?e.jsxs(e.Fragment,{children:[e.jsx(Ip,{className:"mr-1 size-3.5"}),"Parallel"]}):e.jsxs(e.Fragment,{children:[e.jsx(Tp,{className:"mr-1 size-3.5"}),"Sequential"]})})]})]}),x?null:e.jsx("div",{className:"grid gap-3 border-t border-white/8 px-4 py-4 lg:grid-cols-2",children:c.nodeIds.map(f=>{var D,j,S;const h=t.graph.nodes.find(p=>p.id===f);if(!h)return null;const m=h.entityType==="project"?s.get(h.entityId):i.get(h.entityId),b=h.entityType==="project"?`/projects/${h.entityId}`:`/tasks/${h.entityId}`,w=h.entityType==="project"?(D=s.get(h.entityId))==null?void 0:D.user:(j=i.get(h.entityId))==null?void 0:j.user,M=((S=r.get(h.id))==null?void 0:S.map(p=>{var A;return((A=t.graph.nodes.find(T=>T.id===p))==null?void 0:A.title)??p}))??[],E=k0(t,h.id);return e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-[rgba(8,14,26,0.76)] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(L,{className:"bg-white/[0.08] text-white/76",children:h.entityType}),e.jsx(L,{className:E.className,children:E.label})]}),e.jsx(Ae,{to:b,className:"mt-3 block text-lg font-medium text-white transition hover:text-[var(--primary)]",children:h.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:h.notes||("description"in(m??{})?m==null?void 0:m.description:"")||"No extra step note attached yet."})]}),e.jsx(Ue,{user:w,compact:!0})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[h.branchLabel?e.jsx(L,{className:"bg-[rgba(192,193,255,0.12)] text-white/82",children:h.branchLabel}):null,M.length===0?e.jsx(L,{className:"bg-emerald-500/10 text-emerald-200",children:"Start node"}):M.map(p=>e.jsxs(L,{className:"bg-white/[0.08] text-white/70",children:["Depends on ",p]},`${h.id}:${p}`))]})]},h.id)})})]},c.level)}),n.length===0?e.jsx("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-4 text-sm text-white/56",children:"No phases mapped yet."}):null]})}function C0(){var T;const t=Je(),{strategyId:s}=es(),i=ut(),a=We(),[n,r]=d.useState(!1),[l,o]=d.useState(),c=Mt(t.selectedUserIds),x=t.snapshot.strategies.find(k=>k.id===s)??null,v=fe({queryKey:["strategy-detail",s],queryFn:async()=>(await db(s)).strategy,enabled:!!(s&&!x)}),u=x??v.data??null,f=async()=>{await Promise.all([a.invalidateQueries({queryKey:["strategy-detail",s]}),t.refresh()])},h=xe({mutationFn:async({input:k,currentStrategyId:$})=>(await Jr($,k)).strategy,onSuccess:f}),m=xe({mutationFn:async k=>Bh(k),onSuccess:async()=>{await f(),i("/strategies")}}),b=xe({mutationFn:async k=>(await Jr(s,{isLocked:k,lockedByUserId:k?c??(u==null?void 0:u.userId)??"user_operator":null})).strategy,onSuccess:f}),w=d.useMemo(()=>new Map(t.snapshot.goals.map(k=>[k.id,k])),[t.snapshot.goals]),M=d.useMemo(()=>new Map(t.snapshot.dashboard.projects.map(k=>[k.id,k])),[t.snapshot.dashboard.projects]),E=d.useMemo(()=>new Map(t.snapshot.tasks.map(k=>[k.id,k])),[t.snapshot.tasks]),D=d.useMemo(()=>u?new Map(u.graph.nodes.map(k=>{var g,C;const $=k.entityType==="project"?(g=M.get(k.entityId))==null?void 0:g.user:(C=E.get(k.entityId))==null?void 0:C.user;return[k.id,$?{label:`${$.displayName} (${$.kind})`,color:$.accentColor}:null]})):new Map,[M,u,E]),j=u??{title:"",overview:"",endStateDescription:"",targetGoalIds:[],targetProjectIds:[],graph:{nodes:[],edges:[]}},S=d.useMemo(()=>mo(j),[j]),p=d.useMemo(()=>Gm(j),[j]),A=d.useMemo(()=>uo((u==null?void 0:u.metrics)??{planCoverageScore:0,sequencingScore:0,scopeDisciplineScore:0,qualityScore:0,targetProgressScore:0,startedNodeCount:0,totalNodeCount:1,offPlanEntityCount:0,offPlanActiveEntityCount:0,blockedNodeIds:[],outOfOrderNodeIds:[]}),[u==null?void 0:u.metrics]);return v.isLoading&&!u?e.jsx(nt,{eyebrow:"Strategy",title:"Loading strategy",description:"Resolving the directed plan, targets, and current alignment."}):v.isError?e.jsx(ze,{eyebrow:"Strategy",error:v.error,onRetry:()=>void v.refetch()}):u?e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{title:u.title,titleText:u.title,description:u.overview||u.endStateDescription,badge:`${u.metrics.alignmentScore}% aligned`,actions:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(er,{userId:c,domain:"strategies",entityType:"strategy",entityId:u.id,label:u.title,description:u.overview||u.endStateDescription}),u.isLocked?null:e.jsx(Q,{variant:"secondary",onClick:()=>{o(void 0),r(!0)},children:"Edit strategy"}),e.jsx(Q,{variant:"secondary",disabled:!u.isLocked&&!p,pending:b.isPending,pendingLabel:u.isLocked?"Unlocking contract":"Locking contract",onClick:()=>{b.mutateAsync(!u.isLocked)},children:u.isLocked?"Unlock contract":"Lock as contract"}),e.jsx(Q,{variant:"secondary",pending:m.isPending,pendingLabel:"Deleting strategy",onClick:()=>{window.confirm(`Delete strategy "${u.title}"?`)&&m.mutateAsync(u.id)},children:"Delete"})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Ue,{user:u.user}),e.jsx(L,{className:u.isLocked?"bg-amber-500/12 text-amber-200":"bg-emerald-500/12 text-emerald-200",children:u.isLocked?"Contract locked":"Editable draft"}),e.jsx(L,{className:"bg-white/[0.08] text-white/76",children:u.status}),e.jsxs(L,{className:"bg-white/[0.08] text-white/76",children:[u.graph.nodes.length," nodes"]}),e.jsxs(L,{className:"bg-white/[0.08] text-white/76",children:[u.graph.edges.length," edges"]})]}),e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.15fr)_minmax(18rem,0.85fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ae,{className:"grid gap-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"End state"}),e.jsx("div",{className:"text-sm leading-7 text-white/64",children:u.endStateDescription||"No end-state description yet."})]}),e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Directed execution graph"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"The graph is the contract surface for this strategy. It shows which branches are available now, where work is blocked, and whether any node is moving out of sequence."})]}),u.isLocked?null:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Q,{variant:"secondary",onClick:()=>{o("sequence"),r(!0)},children:"Refine sequence"}),e.jsx(Q,{onClick:()=>{o("sequence"),r(!0)},children:"Add parallel work"})]})]}),e.jsx(N0,{strategy:u,ownerByNodeId:D}),e.jsx(S0,{strategy:u,projectsById:M,tasksById:E})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ae,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Contract state"}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:u.isLocked?"This strategy is currently locked as a contract. The graph, targets, and descriptive plan stay frozen until you explicitly unlock it.":"This strategy is still a draft. Agents and users can keep refining the plan until you lock it."}),u.isLocked?e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-sm text-white/60",children:[e.jsxs("span",{children:["Locked by"," ",((T=u.lockedByUser)==null?void 0:T.displayName)??"Unknown user"]}),u.lockedAt?e.jsxs("span",{children:["· ",new Date(u.lockedAt).toLocaleString()]}):null]}):null,u.isLocked?null:e.jsx("div",{className:"mt-4 grid gap-2",children:S.map(k=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[14px] bg-white/[0.03] px-3 py-2",children:[e.jsx("div",{className:"text-sm text-white/64",children:k.label}),e.jsx(L,{className:k.satisfied?"bg-emerald-500/12 text-emerald-200":"bg-amber-500/12 text-amber-200",children:k.satisfied?"Ready":"Missing"})]},k.id))})]}),!u.isLocked&&!p?e.jsx("div",{className:"rounded-[18px] border border-amber-400/18 bg-amber-500/[0.08] px-4 py-3 text-sm leading-6 text-amber-100/86",children:"Add a target goal or project plus an overview or end state before locking this draft as the execution contract."}):null,u.isLocked?null:e.jsx("div",{className:"mt-4 text-xs leading-5 text-white/46",children:"Drafts may stay incomplete while humans and agents negotiate the plan. Only the lock action requires the contract checks to pass."})]}),e.jsxs(ae,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Alignment metrics"}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-sm text-white/56",children:"Alignment score"}),e.jsxs("div",{className:"mt-2 font-display text-3xl text-[var(--primary)]",children:[u.metrics.alignmentScore,"%"]}),e.jsxs("div",{className:"mt-3 text-xs leading-5 text-white/48",children:[u.metrics.startedNodeCount,"/",u.metrics.totalNodeCount," planned nodes started,"," ",u.metrics.completedNodeCount," completed,"," ",u.metrics.readyNodeCount," ready now."]})]}),A.map(k=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-sm text-white/56",children:k.label}),e.jsxs("div",{className:"text-sm font-medium text-white",children:[k.value,"%"]})]}),e.jsx(us,{value:k.value,className:"mt-3"}),e.jsx("div",{className:"mt-3 text-xs leading-5 text-white/48",children:k.detail})]},k.id))]}),e.jsxs(ae,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"End targets"}),u.targetGoalIds.map(k=>{const $=w.get(k);return $?e.jsx(Ae,{to:`/goals/${$.id}`,className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/78 transition hover:bg-white/[0.08]",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("span",{children:["Goal: ",$.title]}),e.jsx(Ue,{user:$.user,compact:!0})]})},$.id):null}),u.targetProjectIds.map(k=>{const $=M.get(k);return $?e.jsx(Ae,{to:`/projects/${$.id}`,className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/78 transition hover:bg-white/[0.08]",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("span",{children:["Project: ",$.title]}),e.jsx(Ue,{user:$.user,compact:!0})]})},$.id):null}),u.targetGoalIds.length===0&&u.targetProjectIds.length===0?e.jsx("div",{className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/52",children:"No end targets linked yet."}):null]}),e.jsxs(ae,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Linked entities"}),u.linkedEntities.length===0?e.jsx("div",{className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/52",children:"No additional linked entities."}):u.linkedEntities.map(k=>{var C,F,z,J,O,_,B;const $=Xs(k.entityType,k.entityId),g=k.entityType==="goal"?(C=w.get(k.entityId))==null?void 0:C.title:k.entityType==="project"?(F=M.get(k.entityId))==null?void 0:F.title:k.entityType==="task"?(z=E.get(k.entityId))==null?void 0:z.title:`${k.entityType}:${k.entityId}`;return $?e.jsx(Ae,{to:$,className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/78 transition hover:bg-white/[0.08]",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("span",{children:g}),e.jsx(Ue,{user:k.entityType==="goal"?(J=w.get(k.entityId))==null?void 0:J.user:k.entityType==="project"?(O=M.get(k.entityId))==null?void 0:O.user:k.entityType==="task"?(_=E.get(k.entityId))==null?void 0:_.user:k.entityType==="strategy"?(B=t.snapshot.strategies.find(K=>K.id===k.entityId))==null?void 0:B.user:null,compact:!0})]})},`${k.entityType}:${k.entityId}`):e.jsx("div",{className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/52",children:g},`${k.entityType}:${k.entityId}`)})]})]})]}),e.jsx(Vm,{open:n,pending:h.isPending,editingStrategy:u,goals:t.snapshot.dashboard.goals,projects:t.snapshot.dashboard.projects,tasks:t.snapshot.tasks,habits:t.snapshot.habits,strategies:t.snapshot.strategies,users:t.snapshot.users,defaultUserId:c,initialStepId:l,onOpenChange:k=>{r(k),k||o(void 0)},onSubmit:async k=>{await h.mutateAsync({input:k,currentStrategyId:u.id})}})]}):e.jsx(ze,{eyebrow:"Strategy",error:new Error("Strategy not found."),onRetry:()=>i("/strategies")})}const Ym=[{id:"overview",label:"Overview",icon:xh},{id:"map",label:"Map",icon:oh},{id:"table",label:"Table",icon:Pp},{id:"history",label:"History",icon:jh},{id:"contexts",label:"Contexts",icon:Aa},{id:"concepts",label:"Concepts",icon:Tt}],I0=new Set(["projects","tasks","strategies","habits"]),Va=[{value:"projects",label:"Projects",description:"Goals and projects already living in Forge.",mode:"forge"},{value:"tasks",label:"Tasks",description:"Execution-level work choices inside Forge.",mode:"forge"},{value:"strategies",label:"Strategies",description:"Plan shapes and sequencing choices in Forge.",mode:"forge"},{value:"habits",label:"Habits",description:"Recurring behaviors and routines from Forge.",mode:"forge"},{value:"activities",label:"Activities",description:"Movement, leisure, and social setting concepts.",mode:"concept"},{value:"food",label:"Food",description:"Cuisine, meal mood, and drink preferences.",mode:"concept"},{value:"places",label:"Places",description:"Living environments, venues, and trip shapes.",mode:"concept"},{value:"countries",label:"Countries",description:"Country-level attraction and lifestyle fit.",mode:"concept"},{value:"fashion",label:"Fashion",description:"Silhouette, material, and palette preferences.",mode:"concept"},{value:"people",label:"People",description:"Presence, body-type, and conversation preferences.",mode:"concept"},{value:"media",label:"Media",description:"Film, reading, and music taste.",mode:"concept"},{value:"tools",label:"Tools",description:"Workflow and capture preferences.",mode:"concept"},{value:"custom",label:"Custom",description:"General-purpose concept libraries you control.",mode:"concept"}],cl={novelty:"Novelty",simplicity:"Simplicity",rigor:"Rigor",aesthetics:"Aesthetics",depth:"Depth",structure:"Structure",familiarity:"Familiarity",surprise:"Surprise"},Ja={novelty:0,simplicity:0,rigor:0,aesthetics:0,depth:0,structure:0,familiarity:0,surprise:0},pc={liked:"bg-emerald-500/12 text-emerald-200",disliked:"bg-rose-500/12 text-rose-200",uncertain:"bg-white/[0.08] text-white/70",vetoed:"bg-rose-500/15 text-rose-100",bookmarked:"bg-sky-500/12 text-sky-200",favorite:"bg-amber-500/12 text-amber-200",must_have:"bg-indigo-500/15 text-indigo-100",neutral:"bg-white/[0.08] text-white/70"},T0=[{signalType:"favorite",label:"Favorite"},{signalType:"must_have",label:"Must-have"},{signalType:"bookmark",label:"Bookmark"},{signalType:"compare_later",label:"Later"},{signalType:"neutral",label:"Neutral"},{signalType:"veto",label:"Veto"}];function Ya(t){return t.trim().toLowerCase()}function qi(t){return`${Math.round(t*100)}%`}function P0(t){return[...t.goals.map(s=>({entityType:"goal",entityId:s.id,domain:"projects",label:s.title,description:s.description,user:s.user,href:`/goals/${s.id}`,searchText:Be([s.title,s.description,s.status,s.horizon],s)})),...t.dashboard.projects.map(s=>({entityType:"project",entityId:s.id,domain:"projects",label:s.title,description:s.description,user:s.user,href:`/projects/${s.id}`,searchText:Be([s.title,s.description,s.status,s.goalTitle],s)})),...t.tasks.map(s=>({entityType:"task",entityId:s.id,domain:"tasks",label:s.title,description:s.description,user:s.user,href:`/tasks/${s.id}`,searchText:Be([s.title,s.description,s.status,s.priority,s.owner],s)})),...t.strategies.map(s=>({entityType:"strategy",entityId:s.id,domain:"strategies",label:s.title,description:s.overview||s.endStateDescription,user:s.user,href:`/strategies/${s.id}`,searchText:Be([s.title,s.overview,s.endStateDescription,s.status],s)})),...t.habits.map(s=>({entityType:"habit",entityId:s.id,domain:"habits",label:s.title,description:s.description,user:s.user,href:null,searchText:Be([s.title,s.description,s.status,s.frequency],s)}))]}function M0(t,s){return!t||!s?null:t==="goal"?`/goals/${s}`:t==="project"?`/projects/${s}`:t==="task"?`/tasks/${s}`:t==="strategy"?`/strategies/${s}`:null}function Za(t){return t.manualStatus??t.status}function A0(t){return t&&Ym.some(s=>s.id===t)?t:"overview"}function E0(t){return t.summary.totalItems<2?{title:"Forge does not know enough yet.",description:"Start the game so Forge can ask a few clean comparisons and build a real preference model."}:t.summary.averageConfidence<.28?{title:"Forge has a rough sketch, not a stable read.",description:"There is some signal, but the model still needs more rounds before its preferences are trustworthy."}:{title:"This is what Forge currently thinks.",description:"The summary below is the current best model for this user, this domain, and the active context."}}function L0({summary:t}){const s=Math.max(-1,Math.min(1,t.leaning)),i=(s+1)/2*100;return e.jsxs("div",{className:"grid gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-white/56",children:[e.jsx("span",{children:cl[t.dimensionId]}),e.jsxs("span",{children:[t.movement>.08?"Rising":t.movement<-.08?"Falling":"Stable"," ","· ",qi(t.confidence)]})]}),e.jsxs("div",{className:"relative h-2 rounded-full bg-white/[0.08]",children:[e.jsx("div",{className:"absolute inset-y-0 left-1/2 w-px bg-white/10"}),e.jsx("div",{className:re("absolute top-1/2 size-3 -translate-x-1/2 -translate-y-1/2 rounded-full border border-white/12",s>=0?"bg-emerald-300":"bg-rose-300"),style:{left:`${i}%`}})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-[11px] uppercase tracking-[0.12em] text-white/38",children:[e.jsxs("span",{children:[s>=0?"Leans toward":"Leans away from"," ",cl[t.dimensionId].toLowerCase()]}),e.jsxs("span",{children:["Context ",qi(t.contextSensitivity)]})]})]})}function xc({title:t,description:s,sideLabel:i,onClick:a}){return e.jsxs("button",{type:"button",className:"grid min-h-[220px] gap-4 rounded-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.07),rgba(255,255,255,0.03))] p-5 text-left transition hover:border-[var(--primary)]/40 hover:bg-[linear-gradient(180deg,rgba(192,193,255,0.14),rgba(255,255,255,0.05))]",onClick:a,children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:i}),e.jsx("div",{className:"font-display text-3xl text-white",children:t}),e.jsx("div",{className:"max-w-[36ch] text-sm leading-6 text-white/56",children:s||"Choose the one that feels more right."}),e.jsx("div",{className:"mt-auto text-sm text-[var(--primary)]",children:"Click this card"})]})}function D0(){var Jt,ws,Js,Ys,Zs;const t=Je(),s=We(),[i,a]=Pt(),[n,r]=d.useState(""),[l,o]=d.useState(""),[c,x]=d.useState(""),[v,u]=d.useState(""),[f,h]=d.useState(""),[m,b]=d.useState({open:!1,phase:"domain",domain:i.get("domain")??"projects"}),[w,M]=d.useState(null),[E,D]=d.useState(!1),[j,S]=d.useState(null),[p,A]=d.useState({label:"",description:"",tags:"",manualStatus:"",manualScore:"",confidenceLock:"",bookmarked:!1,compareLater:!1,frozen:!1,featureWeights:{novelty:"0",simplicity:"0",rigor:"0",aesthetics:"0",depth:"0",structure:"0",familiarity:"0",surprise:"0"}}),[T,k]=d.useState({label:"",description:"",tags:""}),[$,g]=d.useState({name:"",description:"",shareMode:"blended",decayDays:"90"}),[C,F]=d.useState({title:"",description:""}),[z,J]=d.useState({}),[O,_]=d.useState(null),[B,K]=d.useState({title:"",description:""}),[Z,U]=d.useState(null),[I,G]=d.useState({label:"",description:"",tags:""}),W=i.get("userId")??Mt(t.selectedUserIds)??((Jt=t.snapshot.users[0])==null?void 0:Jt.id)??null,ne=i.get("domain")??"projects",de=A0(i.get("tab")),we=i.get("contextId"),Ne=i.get("focusItem"),H=d.useMemo(()=>t.snapshot.users.find(N=>N.id===W)??null,[W,t.snapshot.users]),me=d.useMemo(()=>P0(t.snapshot),[t.snapshot]),y=fe({queryKey:["forge-preferences",W,ne,we],queryFn:async()=>(await Yo({userId:W??void 0,domain:ne,contextId:we??void 0})).workspace,enabled:!!W}),P=fe({queryKey:["forge-preferences-game",W,m.domain,we],queryFn:async()=>(await Yo({userId:W??void 0,domain:m.domain,contextId:we??void 0})).workspace,enabled:!!W&&m.open}),q=y.data??null,pe=m.domain===ne?q:P.data??null;d.useEffect(()=>{var V;if(!q)return;const N=Ne&&q.scores.some(ge=>ge.itemId===Ne)?Ne:((V=q.scores[0])==null?void 0:V.itemId)??null;S(ge=>ge&&q.scores.some(ye=>ye.itemId===ge)?ge:N)},[Ne,q]);const ee=d.useMemo(()=>{if(!q)return[];const N=Ya(n);return N?q.scores.filter(V=>{var ge,ye,Ce;return[((ge=V.item)==null?void 0:ge.label)??"",((ye=V.item)==null?void 0:ye.description)??"",((Ce=V.item)==null?void 0:Ce.tags.join(" "))??"",V.status,V.manualStatus??"",V.dominantDimensions.join(" "),V.explanation.join(" ")].join(" ").toLowerCase().includes(N)}):q.scores},[n,q]),Y=ee.find(N=>N.itemId===j)??(q==null?void 0:q.scores.find(N=>N.itemId===j))??ee[0]??(q==null?void 0:q.scores[0])??null;d.useEffect(()=>{var N,V,ge,ye,Ce,xt,Ds,ys,ia,aa,na;Y&&A({label:((N=Y.item)==null?void 0:N.label)??"",description:((V=Y.item)==null?void 0:V.description)??"",tags:((ge=Y.item)==null?void 0:ge.tags.join(", "))??"",manualStatus:Y.manualStatus??"",manualScore:typeof Y.manualScore=="number"?String(Y.manualScore):"",confidenceLock:typeof Y.confidenceLock=="number"?String(Y.confidenceLock):"",bookmarked:Y.bookmarked,compareLater:Y.compareLater,frozen:Y.frozen,featureWeights:{novelty:String(((ye=Y.item)==null?void 0:ye.featureWeights.novelty)??0),simplicity:String(((Ce=Y.item)==null?void 0:Ce.featureWeights.simplicity)??0),rigor:String(((xt=Y.item)==null?void 0:xt.featureWeights.rigor)??0),aesthetics:String(((Ds=Y.item)==null?void 0:Ds.featureWeights.aesthetics)??0),depth:String(((ys=Y.item)==null?void 0:ys.featureWeights.depth)??0),structure:String(((ia=Y.item)==null?void 0:ia.featureWeights.structure)??0),familiarity:String(((aa=Y.item)==null?void 0:aa.featureWeights.familiarity)??0),surprise:String(((na=Y.item)==null?void 0:na.featureWeights.surprise)??0)}})},[Y]);const R=d.useMemo(()=>{const N=Ya(l);return me.filter(V=>V.domain===ne).filter(V=>N?V.searchText.includes(N):!0).slice(0,12)},[me,l,ne]),X=d.useMemo(()=>{const N=de==="concepts"?q:pe??q,V=(N==null?void 0:N.catalogs)??[],ge=Ya(c);return ge?V.filter(ye=>[ye.title,ye.description,ye.source,...ye.items.flatMap(Ce=>[Ce.label,Ce.description,Ce.tags.join(" ")])].join(" ").toLowerCase().includes(ge)):V},[pe,c,de,q]),be=async()=>{await s.invalidateQueries({queryKey:["forge-preferences"]}),await s.invalidateQueries({queryKey:["forge-preferences-game"]})},Ie=xe({mutationFn:Vr,onSuccess:be}),te=xe({mutationFn:Jx,onSuccess:async({item:N})=>{await be(),k({label:"",description:"",tags:""}),S(N.id)}}),ce=xe({mutationFn:Bx,onSuccess:async()=>{await be(),F({title:"",description:""}),a(N=>{const V=new URLSearchParams(N);return V.set("tab","concepts"),V})}}),Se=xe({mutationFn:({catalogId:N,patch:V})=>Kx(N,V),onSuccess:async()=>{await be(),_(null)}}),he=xe({mutationFn:Ux,onSuccess:be}),Ge=xe({mutationFn:Qx,onSuccess:async()=>{await be()}}),De=xe({mutationFn:({catalogItemId:N,patch:V})=>Wx(N,V),onSuccess:async()=>{await be(),U(null)}}),ue=xe({mutationFn:Hx,onSuccess:be}),Fe=xe({mutationFn:qx,onSuccess:async()=>{await be(),b(N=>({...N,phase:"play"}))}}),dt=xe({mutationFn:Zx,onSuccess:be}),yt=xe({mutationFn:eg,onSuccess:be}),wt=xe({mutationFn:async()=>{!(Y!=null&&Y.item)||!W||!q||(await Yx(Y.item.id,{label:p.label,description:p.description,tags:p.tags.split(",").map(N=>N.trim()).filter(Boolean),featureWeights:Object.fromEntries(Object.keys(Ja).map(N=>[N,Number(p.featureWeights[N]||0)]))}),await tg(Y.item.id,{userId:W,domain:ne,contextId:q.selectedContext.id,manualStatus:p.manualStatus||null,manualScore:p.manualScore.trim().length>0?Number(p.manualScore):null,confidenceLock:p.confidenceLock.trim().length>0?Number(p.confidenceLock):null,bookmarked:p.bookmarked,compareLater:p.compareLater,frozen:p.frozen}))},onSuccess:be}),kt=xe({mutationFn:Gx,onSuccess:async({context:N})=>{await be(),g({name:"",description:"",shareMode:"blended",decayDays:"90"}),a(V=>{const ge=new URLSearchParams(V);return ge.set("contextId",N.id),ge.set("tab","contexts"),ge})}}),Qt=xe({mutationFn:Vx,onSuccess:async()=>{await be(),u(""),h("")}}),oe=xe({mutationFn:({contextId:N,patch:V})=>Xx(N,V),onSuccess:be}),ke=N=>{a(V=>{const ge=new URLSearchParams(V);for(const[ye,Ce]of Object.entries(N))Ce?ge.set(ye,Ce):ge.delete(ye);return ge})},$e=(N=ne)=>{M(null),b({open:!0,phase:"domain",domain:N})},Ye=async N=>{if(!W)return;M(null),D(!0);const V=me.filter(Ce=>{var xt;return Ce.domain===N&&((xt=Ce.user)==null?void 0:xt.id)===W}),ge=me.filter(Ce=>Ce.domain===N),ye=(V.length>0?V:ge).slice(0,12);if(ye.length<2){M("Forge needs at least two matching records in this domain before it can start the game."),D(!1),b(Ce=>({...Ce,phase:"domain"}));return}try{ke({domain:N,tab:"overview",contextId:null,focusItem:null}),await Promise.all(ye.map(Ce=>Vr({userId:W,domain:N,entityType:Ce.entityType,entityId:Ce.entityId,label:Ce.label,description:Ce.description,tags:[]}))),await be(),b({open:!0,phase:"play",domain:N})}catch(Ce){M(Ce instanceof Error?Ce.message:"Forge could not start the game."),b(xt=>({...xt,phase:"domain"}))}finally{D(!1)}},Pe=async(N,V)=>{if(W){M(null),ke({domain:N,tab:"overview",contextId:null,focusItem:null});try{await Fe.mutateAsync({userId:W,domain:N,contextId:we??void 0,catalogId:V}),b({open:!0,phase:"play",domain:N})}catch(ge){M(ge instanceof Error?ge.message:"Forge could not start the game.")}}},ve=async N=>{if(I0.has(N)){await Ye(N);return}M(null),b({open:!0,phase:"catalog",domain:N})},Ee=async(N,V=1)=>{if(!W||!(pe!=null&&pe.compare.nextPair))return;const ge=pe.compare.nextPair;await dt.mutateAsync({userId:W,domain:m.domain,contextId:pe.selectedContext.id,leftItemId:ge.left.id,rightItemId:ge.right.id,outcome:N,strength:V})},Oe=async(N,V)=>{!W||!pe||await yt.mutateAsync({userId:W,domain:m.domain,contextId:pe.selectedContext.id,itemId:N,signalType:V,strength:1})};if(!W)return e.jsx(gt,{eyebrow:"Preferences",title:"No Forge user available",description:"Forge needs at least one human or bot user before it can learn preferences."});if(y.isLoading&&!q)return e.jsx(nt,{eyebrow:"Preferences",title:"Loading preference model",description:"Reconstructing current scores, uncertainty, and concept libraries."});if(y.isError)return e.jsx(ze,{eyebrow:"Preferences",error:y.error,onRetry:()=>void y.refetch()});if(!q)return null;const tt=[...q.dimensions].sort((N,V)=>V.confidence-N.confidence).slice(0,6),Qe=q.scores.filter(N=>Za(N)==="liked"||Za(N)==="favorite").slice(0,4),St=q.scores.filter(N=>N.uncertainty>=.5).slice(0,4),Le=E0(q),pt=M0(((ws=Y==null?void 0:Y.item)==null?void 0:ws.sourceEntityType)??null,((Js=Y==null?void 0:Y.item)==null?void 0:Js.sourceEntityId)??null),_t=(pe==null?void 0:pe.compare.nextPair)??null;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{title:"Preferences",titleText:"Preferences",description:"Forge keeps an explicit, editable model of what one user prefers in one domain. The first job of this page is to show what Forge currently knows.",badge:`${q.summary.totalItems} items · ${qi(q.summary.averageConfidence)} confidence`,actions:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Q,{className:"min-w-[10rem]",onClick:()=>$e(),children:"Start the game"}),e.jsx(Q,{variant:"secondary",onClick:()=>void be(),children:"Refresh model"})]})}),e.jsx(Bt,{}),e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"grid gap-3 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Active user"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("select",{value:W,onChange:N=>ke({userId:N.target.value,contextId:null,focusItem:null}),className:"min-h-10 rounded-[18px] border border-white/8 bg-white/[0.05] px-3 text-sm text-white outline-none",children:t.snapshot.users.map(N=>e.jsxs("option",{value:N.id,children:[N.displayName," · ",N.kind]},N.id))}),e.jsx(Ue,{user:H}),e.jsx("div",{className:"text-sm text-white/54",children:Nt(H)})]})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Domain"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Va.map(N=>e.jsx("button",{type:"button",className:re("rounded-full border px-3 py-2 text-sm transition",N.value===ne?"border-[var(--primary)] bg-[var(--primary)]/14 text-white":"border-white/8 bg-white/[0.04] text-white/62 hover:bg-white/[0.08]"),onClick:()=>ke({domain:N.value,contextId:null,focusItem:null}),children:N.label},N.value))}),e.jsx("div",{className:"text-sm text-white/48",children:(Ys=Va.find(N=>N.value===ne))==null?void 0:Ys.description})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-white/50",children:[e.jsx(L,{className:"bg-white/[0.08] text-white/70",children:q.selectedContext.name}),e.jsx("span",{children:q.selectedContext.shareMode}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[q.compare.pendingCount," queued comparisons"]}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[q.libraries.totalCatalogItems," concept items ready"]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Ym.map(N=>e.jsxs("button",{type:"button",className:re("inline-flex items-center gap-2 rounded-full border px-3 py-2 text-sm transition",N.id===de?"border-[var(--primary)] bg-[var(--primary)]/14 text-white":"border-white/8 bg-white/[0.04] text-white/62 hover:bg-white/[0.08]"),onClick:()=>ke({tab:N.id}),children:[e.jsx(N.icon,{className:"size-4"}),N.label]},N.id))}),de==="overview"?e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.3fr)_360px]",children:[e.jsxs(ae,{className:"grid gap-5",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"What Forge knows"}),e.jsx("div",{className:"font-display text-3xl text-white",children:Le.title}),e.jsx("div",{className:"max-w-[70ch] text-sm leading-6 text-white/58",children:Le.description})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[{label:"Known items",value:q.summary.totalItems,detail:"Items inside this domain"},{label:"Confidence",value:qi(q.summary.averageConfidence),detail:"Average certainty"},{label:"Unknowns",value:q.summary.uncertainCount,detail:"Need more rounds"},{label:"Libraries",value:q.libraries.totalCatalogItems,detail:"Seeded concepts ready"}].map(N=>e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:N.label}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:N.value}),e.jsx("div",{className:"mt-1 text-sm text-white/52",children:N.detail})]},N.label))}),e.jsx("div",{className:"grid gap-4 lg:grid-cols-2",children:tt.map(N=>e.jsx(L0,{summary:N},N.dimensionId))})]}),e.jsxs(ae,{className:"grid gap-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Next move"}),e.jsx("div",{className:"font-display text-2xl text-white",children:"Start the game"}),e.jsx("div",{className:"text-sm leading-6 text-white/58",children:"Forge will ask a small number of pairwise questions. You choose a domain, Forge supplies the candidates, and the model tightens from there."}),e.jsx(Q,{className:"w-full",onClick:()=>$e(),children:"Start the game"}),e.jsxs("div",{className:"grid gap-3 rounded-[22px] bg-white/[0.04] px-4 py-4 text-sm text-white/58",children:[e.jsxs("div",{children:["Current queue: ",q.compare.pendingCount," comparison",q.compare.pendingCount===1?"":"s"]}),e.jsxs("div",{children:["Active context: ",q.selectedContext.name]}),e.jsxs("div",{children:["Library coverage: ",q.libraries.seededCatalogCount," ","seeded lists and ",q.libraries.customCatalogCount," ","custom lists"]})]})]})]}),e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.3fr)_360px]",children:[e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Preference map"}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:"Green drifts positive, red drifts negative, and low opacity still means uncertainty."})]}),e.jsx(Ae,{to:"?tab=map",className:"text-sm text-[var(--primary)]",children:"Open full map"})]}),e.jsxs("div",{className:"relative min-h-[340px] overflow-hidden rounded-[24px] border border-white/8 bg-[radial-gradient(circle_at_top,rgba(87,196,138,0.18),transparent_35%),radial-gradient(circle_at_bottom_right,rgba(255,104,130,0.14),transparent_30%),linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0.01))]",children:[e.jsx("div",{className:"absolute inset-x-0 top-1/2 h-px bg-white/8"}),e.jsx("div",{className:"absolute inset-y-0 left-1/2 w-px bg-white/8"}),q.map.map(N=>e.jsx("button",{type:"button",className:re("absolute -translate-x-1/2 -translate-y-1/2 rounded-full border px-2 py-1 text-[11px] shadow-[0_10px_25px_rgba(5,8,16,0.32)] transition hover:scale-[1.04]",N.itemId===(Y==null?void 0:Y.itemId)?"border-white/30 bg-white/16 text-white":N.score>=0?"border-emerald-300/30 bg-emerald-500/14 text-emerald-100":"border-rose-300/30 bg-rose-500/14 text-rose-100"),style:{left:`${50+N.x*30}%`,top:`${50-N.y*30}%`,opacity:.55+N.confidence*.45},onClick:()=>S(N.itemId),children:N.label},N.itemId))]})]}),e.jsxs(ae,{className:"grid gap-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Best read so far"}),e.jsx("div",{className:"grid gap-2",children:Qe.length>0?Qe.map(N=>{var V;return e.jsxs("button",{type:"button",className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-left transition hover:bg-white/[0.07]",onClick:()=>{S(N.itemId),ke({focusItem:N.itemId})},children:[e.jsx("div",{className:"font-medium text-white",children:((V=N.item)==null?void 0:V.label)??N.itemId}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:N.explanation[0]||"Forge has positive evidence here."})]},N.itemId)}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/58",children:"No clear positives yet. A few comparison rounds will change that."})}),e.jsxs("div",{className:"border-t border-white/8 pt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Biggest unknowns"}),e.jsx("div",{className:"mt-3 grid gap-2",children:St.length>0?St.map(N=>{var V;return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/58",children:[e.jsx("div",{className:"font-medium text-white",children:((V=N.item)==null?void 0:V.label)??N.itemId}),e.jsxs("div",{className:"mt-1",children:["Uncertainty ",qi(N.uncertainty)]})]},N.itemId)}):e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/58",children:"The current unknown list is short."})})]})]})]}),e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Bring in Forge records"}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:"Search goals, projects, tasks, strategies, or habits across human and bot users, then send them straight into this model."})]}),e.jsxs(L,{className:"bg-white/[0.08] text-white/70",children:[R.length," visible"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(bt,{className:"size-4 text-white/38"}),e.jsx(le,{value:l,onChange:N=>o(N.target.value),placeholder:"Search across owners, handles, user kind, title, and description"})]}),e.jsx("div",{className:"grid gap-2",children:R.map(N=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"font-medium text-white",children:N.label}),e.jsx(L,{className:"bg-white/[0.08] text-white/70",children:N.entityType}),N.user?e.jsx(Ue,{user:N.user,compact:!0}):null]}),e.jsx("div",{className:"mt-1 text-sm text-white/52",children:N.description||"No description yet."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[N.href?e.jsx(Ae,{to:N.href,children:e.jsx(Q,{variant:"ghost",size:"sm",children:"Open"})}):null,e.jsx(Q,{variant:"secondary",size:"sm",pending:Ie.isPending,pendingLabel:"Adding",onClick:()=>void Ie.mutateAsync({userId:W,domain:ne,entityType:N.entityType,entityId:N.entityId,label:N.label,description:N.description,tags:[]}),children:"Add to model"})]})]},`${N.entityType}-${N.entityId}`))})]})]}):null,de==="map"?e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Full map"}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:"Click a point to inspect why Forge believes it belongs there."})]}),e.jsxs("div",{className:"text-sm text-white/52",children:[q.map.length," plotted items"]})]}),e.jsxs("div",{className:"relative min-h-[520px] overflow-hidden rounded-[24px] border border-white/8 bg-[radial-gradient(circle_at_20%_20%,rgba(87,196,138,0.2),transparent_25%),radial-gradient(circle_at_80%_80%,rgba(255,104,130,0.2),transparent_26%),linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0.01))]",children:[e.jsx("div",{className:"absolute inset-x-0 top-1/2 h-px bg-white/8"}),e.jsx("div",{className:"absolute inset-y-0 left-1/2 w-px bg-white/8"}),q.map.map(N=>e.jsx("button",{type:"button",className:re("absolute -translate-x-1/2 -translate-y-1/2 rounded-full border px-3 py-1 text-xs transition hover:scale-[1.04]",N.itemId===(Y==null?void 0:Y.itemId)?"border-white/30 bg-white/16 text-white":N.score>=0?"border-emerald-300/30 bg-emerald-500/14 text-emerald-100":"border-rose-300/30 bg-rose-500/14 text-rose-100"),style:{left:`${50+N.x*34}%`,top:`${50-N.y*34}%`,opacity:.45+N.confidence*.55},onClick:()=>{S(N.itemId),ke({focusItem:N.itemId})},children:N.label},N.itemId))]})]}):null,de==="table"?e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.2fr)_380px]",children:[e.jsxs(ae,{className:"grid gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(bt,{className:"size-4 text-white/38"}),e.jsx(le,{value:n,onChange:N=>r(N.target.value),placeholder:"Search learned items, explanations, tags, or dominant dimensions"})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full text-left text-sm",children:[e.jsx("thead",{className:"text-[11px] uppercase tracking-[0.14em] text-white/38",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"Item"}),e.jsx("th",{className:"px-3 py-2",children:"Score"}),e.jsx("th",{className:"px-3 py-2",children:"Confidence"}),e.jsx("th",{className:"px-3 py-2",children:"Status"}),e.jsx("th",{className:"px-3 py-2",children:"Evidence"})]})}),e.jsx("tbody",{children:ee.map(N=>{var V,ge;return e.jsxs("tr",{className:re("cursor-pointer border-t border-white/6 transition hover:bg-white/[0.04]",N.itemId===(Y==null?void 0:Y.itemId)?"bg-white/[0.05]":""),onClick:()=>{S(N.itemId),ke({focusItem:N.itemId})},children:[e.jsxs("td",{className:"px-3 py-3",children:[e.jsx("div",{className:"font-medium text-white",children:((V=N.item)==null?void 0:V.label)??N.itemId}),e.jsx("div",{className:"text-xs text-white/48",children:(((ge=N.item)==null?void 0:ge.tags)??[]).join(" · ")})]}),e.jsx("td",{className:"px-3 py-3 text-white/68",children:N.latentScore.toFixed(2)}),e.jsx("td",{className:"px-3 py-3 text-white/68",children:qi(N.confidence)}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(L,{className:pc[Za(N)],children:Za(N)})}),e.jsx("td",{className:"px-3 py-3 text-white/68",children:N.evidenceCount})]},N.itemId)})})]})})]}),e.jsxs(ae,{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Item editor"}),Y!=null&&Y.item?e.jsxs(e.Fragment,{children:[e.jsx(le,{value:p.label,onChange:N=>A(V=>({...V,label:N.target.value})),placeholder:"Item label"}),e.jsx(Me,{value:p.description,onChange:N=>A(V=>({...V,description:N.target.value})),className:"min-h-24",placeholder:"Item description"}),e.jsx(le,{value:p.tags,onChange:N=>A(V=>({...V,tags:N.target.value})),placeholder:"comma, separated, tags"}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("select",{value:p.manualStatus,onChange:N=>A(V=>({...V,manualStatus:N.target.value})),className:"min-h-10 rounded-[18px] border border-white/8 bg-white/[0.05] px-3 text-sm text-white outline-none",children:[e.jsx("option",{value:"",children:"Inferred status"}),Object.keys(pc).map(N=>e.jsx("option",{value:N,children:N},N))]}),e.jsx(le,{value:p.manualScore,onChange:N=>A(V=>({...V,manualScore:N.target.value})),placeholder:"Manual score"}),e.jsx(le,{value:p.confidenceLock,onChange:N=>A(V=>({...V,confidenceLock:N.target.value})),placeholder:"Confidence lock 0-1"})]}),e.jsx("div",{className:"grid gap-2",children:Object.keys(Ja).map(N=>e.jsxs("div",{className:"grid grid-cols-[110px_minmax(0,1fr)] items-center gap-3",children:[e.jsx("div",{className:"text-sm text-white/56",children:cl[N]}),e.jsx(le,{value:p.featureWeights[N],onChange:V=>A(ge=>({...ge,featureWeights:{...ge.featureWeights,[N]:V.target.value}}))})]},N))}),e.jsx("div",{className:"grid gap-2 text-sm text-white/58",children:[["bookmarked","Bookmarked"],["compareLater","Compare later"],["frozen","Frozen"]].map(([N,V])=>e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:p[N],onChange:ge=>A(ye=>({...ye,[N]:ge.target.checked}))}),e.jsx("span",{children:V})]},N))}),e.jsx(Q,{pending:wt.isPending,pendingLabel:"Saving item",onClick:()=>void wt.mutateAsync(),children:"Save item model"}),pt?e.jsx(Ae,{className:"text-sm text-[var(--primary)]",to:pt,children:"Open linked entity"}):null]}):e.jsx("div",{className:"text-sm text-white/52",children:"Select a row to inspect or edit it."}),e.jsxs("div",{className:"mt-3 border-t border-white/8 pt-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Add custom item"}),e.jsxs("div",{className:"mt-3 grid gap-3",children:[e.jsx(le,{value:T.label,onChange:N=>k(V=>({...V,label:N.target.value})),placeholder:"Custom item label"}),e.jsx(Me,{value:T.description,onChange:N=>k(V=>({...V,description:N.target.value})),className:"min-h-24",placeholder:"What is this preference item?"}),e.jsx(le,{value:T.tags,onChange:N=>k(V=>({...V,tags:N.target.value})),placeholder:"comma, separated, tags"}),e.jsx(Q,{disabled:!T.label.trim(),pending:te.isPending,pendingLabel:"Creating item",onClick:()=>void te.mutateAsync({userId:W,domain:ne,label:T.label,description:T.description,tags:T.tags.split(",").map(N=>N.trim()).filter(Boolean),featureWeights:Ja,queueForCompare:!0}),children:"Create custom item"})]})]})]})]}):null,de==="history"?e.jsxs("div",{className:"grid gap-5 xl:grid-cols-3",children:[e.jsxs(ae,{className:"grid gap-3 xl:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Recent pairwise judgments"}),e.jsx("div",{className:"grid gap-2",children:q.history.judgments.slice(0,12).map(N=>{var ye,Ce,xt,Ds;const V=((Ce=(ye=q.scores.find(ys=>ys.itemId===N.leftItemId))==null?void 0:ye.item)==null?void 0:Ce.label)??N.leftItemId,ge=((Ds=(xt=q.scores.find(ys=>ys.itemId===N.rightItemId))==null?void 0:xt.item)==null?void 0:Ds.label)??N.rightItemId;return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm text-white/58",children:[e.jsxs("div",{className:"font-medium text-white",children:[V," vs ",ge]}),e.jsxs("div",{className:"mt-1",children:["Outcome ",N.outcome," · strength"," ",N.strength," ·"," ",new Date(N.createdAt).toLocaleString()]})]},N.id)})})]}),e.jsxs(ae,{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Signals and snapshots"}),e.jsx("div",{className:"grid gap-2",children:q.history.signals.slice(0,8).map(N=>{var ge,ye;const V=((ye=(ge=q.scores.find(Ce=>Ce.itemId===N.itemId))==null?void 0:ge.item)==null?void 0:ye.label)??N.itemId;return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-2 text-sm text-white/58",children:[V," · ",N.signalType," ·"," ",new Date(N.createdAt).toLocaleString()]},N.id)})}),e.jsx("div",{className:"grid gap-2",children:q.history.snapshots.slice(0,5).map(N=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-2 text-sm text-white/58",children:["Snapshot ",new Date(N.createdAt).toLocaleString()]},N.id))}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/58",children:["Stale items: ",q.history.staleItemIds.length," · Flipped items: ",q.history.flippedItemIds.length]})]})]}):null,de==="contexts"?e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_360px]",children:[e.jsx("div",{className:"grid gap-4",children:q.contexts.map(N=>e.jsxs(ae,{className:"grid gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-display text-2xl text-white",children:N.name}),e.jsx("div",{className:"text-sm text-white/54",children:N.description||"No description yet."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[N.isDefault?e.jsx(L,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"Default"}):null,e.jsx(L,{className:"bg-white/[0.08] text-white/70",children:N.shareMode}),N.active?null:e.jsx(L,{className:"bg-amber-500/12 text-amber-200",children:"Inactive"})]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[e.jsx(le,{value:N.name,onChange:V=>void oe.mutateAsync({contextId:N.id,patch:{name:V.target.value}}),placeholder:"Context name"}),e.jsxs("select",{value:N.shareMode,onChange:V=>void oe.mutateAsync({contextId:N.id,patch:{shareMode:V.target.value}}),className:"min-h-10 rounded-[18px] border border-white/8 bg-white/[0.05] px-3 text-sm text-white outline-none",children:[e.jsx("option",{value:"shared",children:"shared"}),e.jsx("option",{value:"blended",children:"blended"}),e.jsx("option",{value:"isolated",children:"isolated"})]}),e.jsx(le,{value:String(N.decayDays),onChange:V=>void oe.mutateAsync({contextId:N.id,patch:{decayDays:Number(V.target.value||90)}}),placeholder:"Decay days"}),e.jsx(Q,{variant:"secondary",onClick:()=>ke({contextId:N.id,tab:"overview"}),children:"Open context"})]}),e.jsx(Me,{value:N.description,onChange:V=>void oe.mutateAsync({contextId:N.id,patch:{description:V.target.value}}),className:"min-h-20"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Q,{variant:"secondary",onClick:()=>void oe.mutateAsync({contextId:N.id,patch:{active:!N.active}}),children:N.active?"Deactivate":"Activate"}),N.isDefault?null:e.jsx(Q,{variant:"secondary",onClick:()=>void oe.mutateAsync({contextId:N.id,patch:{isDefault:!0}}),children:"Make default"})]})]},N.id))}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(ae,{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Create context"}),e.jsx(le,{value:$.name,onChange:N=>g(V=>({...V,name:N.target.value})),placeholder:"Context name"}),e.jsx(Me,{value:$.description,onChange:N=>g(V=>({...V,description:N.target.value})),className:"min-h-24",placeholder:"What changes in this context?"}),e.jsxs("select",{value:$.shareMode,onChange:N=>g(V=>({...V,shareMode:N.target.value})),className:"min-h-10 rounded-[18px] border border-white/8 bg-white/[0.05] px-3 text-sm text-white outline-none",children:[e.jsx("option",{value:"blended",children:"blended"}),e.jsx("option",{value:"shared",children:"shared"}),e.jsx("option",{value:"isolated",children:"isolated"})]}),e.jsx(le,{value:$.decayDays,onChange:N=>g(V=>({...V,decayDays:N.target.value})),placeholder:"Decay days"}),e.jsx(Q,{disabled:!$.name.trim(),pending:kt.isPending,pendingLabel:"Creating context",onClick:()=>void kt.mutateAsync({userId:W,domain:ne,name:$.name,description:$.description,shareMode:$.shareMode,decayDays:Number($.decayDays||90),active:!0,isDefault:!1}),children:"Create context"})]}),e.jsxs(ae,{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Merge contexts"}),e.jsxs("select",{value:v,onChange:N=>u(N.target.value),className:"min-h-10 rounded-[18px] border border-white/8 bg-white/[0.05] px-3 text-sm text-white outline-none",children:[e.jsx("option",{value:"",children:"Source context"}),q.contexts.map(N=>e.jsx("option",{value:N.id,children:N.name},N.id))]}),e.jsxs("select",{value:f,onChange:N=>h(N.target.value),className:"min-h-10 rounded-[18px] border border-white/8 bg-white/[0.05] px-3 text-sm text-white outline-none",children:[e.jsx("option",{value:"",children:"Target context"}),q.contexts.map(N=>e.jsx("option",{value:N.id,children:N.name},N.id))]}),e.jsx(Q,{pending:Qt.isPending,pendingLabel:"Merging",disabled:!v||!f||v===f,onClick:()=>void Qt.mutateAsync({sourceContextId:v,targetContextId:f}),children:"Merge into target"})]})]})]}):null,de==="concepts"?e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_380px]",children:[e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Concept libraries"}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:"These are the lists Forge can use when you start the game in a concept domain. Seeded lists are editable, and custom lists are fully yours."})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-4",children:[["Lists",q.libraries.totalCatalogs],["Concepts",q.libraries.totalCatalogItems],["Seeded",q.libraries.seededCatalogCount],["Custom",q.libraries.customCatalogCount]].map(([N,V])=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:N}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:V})]},N))}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(bt,{className:"size-4 text-white/38"}),e.jsx(le,{value:c,onChange:N=>x(N.target.value),placeholder:"Search lists, concepts, tags, and seeded domains"})]})]}),e.jsxs(ae,{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Create concept list"}),e.jsx(le,{value:C.title,onChange:N=>F(V=>({...V,title:N.target.value})),placeholder:"List title"}),e.jsx(Me,{value:C.description,onChange:N=>F(V=>({...V,description:N.target.value})),className:"min-h-24",placeholder:"What should this list help compare?"}),e.jsx(Q,{disabled:!C.title.trim(),pending:ce.isPending,pendingLabel:"Creating list",onClick:()=>void ce.mutateAsync({userId:W,domain:ne,title:C.title,description:C.description}),children:"Create list"})]})]}),e.jsx("div",{className:"grid gap-4",children:X.map(N=>{const V=z[N.id]??{label:"",description:"",tags:""},ge=N.items.filter(ye=>c.trim()?[ye.label,ye.description,ye.tags.join(" ")].join(" ").toLowerCase().includes(Ya(c)):!0);return e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0",children:O===N.id?e.jsxs("div",{className:"grid gap-3",children:[e.jsx(le,{value:B.title,onChange:ye=>K(Ce=>({...Ce,title:ye.target.value}))}),e.jsx(Me,{value:B.description,onChange:ye=>K(Ce=>({...Ce,description:ye.target.value})),className:"min-h-24"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"font-display text-2xl text-white",children:N.title}),e.jsx(L,{className:"bg-white/[0.08] text-white/70",children:N.source}),e.jsxs(L,{className:"bg-white/[0.08] text-white/70",children:[N.items.length," items"]})]}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:N.description||"No description yet."})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Q,{variant:"secondary",size:"sm",onClick:()=>void Pe(ne,N.id),children:"Start from this list"}),O===N.id?e.jsxs(e.Fragment,{children:[e.jsx(Q,{size:"sm",pending:Se.isPending,pendingLabel:"Saving",onClick:()=>void Se.mutateAsync({catalogId:N.id,patch:{title:B.title,description:B.description}}),children:"Save"}),e.jsx(Q,{variant:"ghost",size:"sm",onClick:()=>_(null),children:"Cancel"})]}):e.jsx(Q,{variant:"ghost",size:"sm",onClick:()=>{_(N.id),K({title:N.title,description:N.description})},children:"Edit list"}),e.jsx(Q,{variant:"ghost",size:"sm",pending:he.isPending,pendingLabel:"Deleting",onClick:()=>void he.mutateAsync(N.id),children:"Delete list"})]})]}),e.jsx("div",{className:"grid gap-2",children:ge.map(ye=>e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:Z===ye.id?e.jsxs("div",{className:"grid gap-3",children:[e.jsx(le,{value:I.label,onChange:Ce=>G(xt=>({...xt,label:Ce.target.value}))}),e.jsx(Me,{value:I.description,onChange:Ce=>G(xt=>({...xt,description:Ce.target.value})),className:"min-h-20"}),e.jsx(le,{value:I.tags,onChange:Ce=>G(xt=>({...xt,tags:Ce.target.value})),placeholder:"comma, separated, tags"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Q,{size:"sm",pending:De.isPending,pendingLabel:"Saving",onClick:()=>void De.mutateAsync({catalogItemId:ye.id,patch:{label:I.label,description:I.description,tags:I.tags.split(",").map(Ce=>Ce.trim()).filter(Boolean)}}),children:"Save concept"}),e.jsx(Q,{variant:"ghost",size:"sm",onClick:()=>U(null),children:"Cancel"})]})]}):e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-white",children:ye.label}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:ye.description||"No description yet."}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:ye.tags.map(Ce=>e.jsx(L,{className:"bg-white/[0.08] text-white/70",children:Ce},`${ye.id}-${Ce}`))})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Q,{variant:"ghost",size:"sm",onClick:()=>{U(ye.id),G({label:ye.label,description:ye.description,tags:ye.tags.join(", ")})},children:"Edit"}),e.jsxs(Q,{variant:"ghost",size:"sm",pending:ue.isPending,pendingLabel:"Deleting",onClick:()=>void ue.mutateAsync(ye.id),children:[e.jsx(ct,{className:"mr-1 size-4"}),"Delete"]})]})]})},ye.id))}),e.jsxs("div",{className:"grid gap-3 rounded-[18px] border border-white/8 bg-white/[0.02] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-white/68",children:[e.jsx(zt,{className:"size-4"}),"Add concept to ",N.title]}),e.jsx(le,{value:V.label,onChange:ye=>J(Ce=>({...Ce,[N.id]:{...V,label:ye.target.value}})),placeholder:"Concept label"}),e.jsx(Me,{value:V.description,onChange:ye=>J(Ce=>({...Ce,[N.id]:{...V,description:ye.target.value}})),className:"min-h-20",placeholder:"Short description"}),e.jsx(le,{value:V.tags,onChange:ye=>J(Ce=>({...Ce,[N.id]:{...V,tags:ye.target.value}})),placeholder:"comma, separated, tags"}),e.jsx(Q,{disabled:!V.label.trim(),pending:Ge.isPending,pendingLabel:"Adding",onClick:()=>void Ge.mutateAsync({catalogId:N.id,label:V.label,description:V.description,tags:V.tags.split(",").map(ye=>ye.trim()).filter(Boolean),featureWeights:Ja}).then(()=>J(ye=>({...ye,[N.id]:{label:"",description:"",tags:""}}))),children:"Add concept"})]})]},N.id)})})]}):null]}),e.jsx(Et,{open:m.open,onOpenChange:N=>{N||M(null),b(V=>({...V,open:N}))},children:e.jsxs(Lt,{children:[e.jsx(Dt,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.74)] backdrop-blur-xl"}),e.jsxs($t,{className:"fixed inset-x-4 bottom-4 top-4 z-50 overflow-y-auto rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(17,24,39,0.98),rgba(10,14,24,0.98))] shadow-[0_30px_90px_rgba(3,8,18,0.45)] md:inset-x-10 lg:left-1/2 lg:right-auto lg:w-[min(72rem,calc(100vw-3rem))] lg:-translate-x-1/2",children:[e.jsx(Ot,{className:"sr-only",children:"Preference game"}),e.jsx(qt,{className:"sr-only",children:"Start comparison rounds from a Forge domain or concept list."}),e.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between gap-4 border-b border-white/8 bg-[rgba(10,14,24,0.92)] px-5 py-4 backdrop-blur-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Preference game"}),e.jsx("div",{className:"mt-1 font-display text-2xl text-white",children:m.phase==="domain"?"Choose a domain":m.phase==="catalog"?"Choose a concept list":"Pick the better fit"})]}),e.jsx(Ft,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":"Close preference game",className:"rounded-full bg-white/6 p-2 text-white/65 transition hover:bg-white/10 hover:text-white",children:e.jsx(mt,{className:"size-4"})})})]}),e.jsxs("div",{className:"grid gap-5 px-5 py-5",children:[w?e.jsx("div",{className:"rounded-[18px] border border-rose-400/25 bg-rose-500/10 px-4 py-3 text-sm text-rose-100",children:w}):null,m.phase==="domain"?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:Va.map(N=>e.jsxs("button",{type:"button",className:"rounded-[24px] border border-white/8 bg-white/[0.04] px-5 py-5 text-left transition hover:border-[var(--primary)]/30 hover:bg-[var(--primary)]/10",onClick:()=>void ve(N.value),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:N.label}),e.jsx(L,{className:"bg-white/[0.08] text-white/70",children:N.mode==="forge"?"Forge":"Concept"})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:N.description})]},N.value))}):null,m.phase==="catalog"?e.jsxs("div",{className:"grid gap-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Pick the concept list Forge should draw from. You do not need to assemble the items yourself."}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(bt,{className:"size-4 text-white/38"}),e.jsx(le,{value:c,onChange:N=>x(N.target.value),placeholder:"Search concept lists"})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:X.length>0?X.map(N=>e.jsxs("button",{type:"button",className:"rounded-[24px] border border-white/8 bg-white/[0.04] px-5 py-5 text-left transition hover:border-[var(--primary)]/30 hover:bg-[var(--primary)]/10",onClick:()=>void Pe(m.domain,N.id),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:N.title}),e.jsxs(L,{className:"bg-white/[0.08] text-white/70",children:[N.items.length," items"]})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:N.description||"No description yet."})]},N.id)):e.jsx("div",{className:"rounded-[24px] bg-white/[0.04] px-5 py-6 text-sm text-white/58",children:"No concept list matches that search yet."})})]}):null,m.phase==="play"?e.jsx("div",{className:"grid gap-5",children:E||P.isLoading?e.jsx(nt,{eyebrow:"Preference game",title:"Preparing the next round",description:"Forge is lining up comparison candidates."}):_t?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-white/52",children:[e.jsx(L,{className:"bg-white/[0.08] text-white/70",children:((Zs=Va.find(N=>N.value===m.domain))==null?void 0:Zs.label)??m.domain}),e.jsx("span",{children:pe==null?void 0:pe.selectedContext.name}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[(pe==null?void 0:pe.compare.pendingCount)??0," ","queued comparisons"]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx(xc,{title:_t.left.label,description:_t.left.description,sideLabel:"Left",onClick:()=>void Ee("left",1)}),e.jsx(xc,{title:_t.right.label,description:_t.right.description,sideLabel:"Right",onClick:()=>void Ee("right",1)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Q,{onClick:()=>void Ee("left",1),children:"Left"}),e.jsx(Q,{onClick:()=>void Ee("right",1),children:"Right"}),e.jsx(Q,{variant:"secondary",onClick:()=>void Ee("left",1.75),children:"Strong left"}),e.jsx(Q,{variant:"secondary",onClick:()=>void Ee("right",1.75),children:"Strong right"}),e.jsx(Q,{variant:"secondary",onClick:()=>void Ee("tie",1),children:"Tie"}),e.jsx(Q,{variant:"secondary",onClick:()=>void Ee("skip",1),children:"Skip"})]}),e.jsx("div",{className:"grid gap-4 rounded-[24px] border border-white/8 bg-white/[0.03] px-4 py-4 lg:grid-cols-2",children:[_t.left,_t.right].map(N=>e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:N.label}),e.jsx("div",{className:"text-sm text-white/56",children:"Quick signals"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:T0.map(V=>e.jsx(Q,{variant:"secondary",size:"sm",onClick:()=>void Oe(N.id,V.signalType),children:V.label},`${N.id}-${V.signalType}`))})]},N.id))})]}):e.jsx(gt,{eyebrow:"Preference game",title:"No pair is ready yet",description:"Forge needs more items in this domain before it can keep asking comparisons."})}):null]})]})]})})]})}function po(t,s,i){return Math.min(Math.max(t,s),i)}function xo(t,s,i){return Math.min(i,Math.max(1,Math.ceil(t.trim().length/s)))}function $0(t,{compact:s}){const i=xo(t,s?13:14,4),n=(s?114:156)+(i-1)*(s?12:18)+Math.min(24,Math.max(0,t.trim().length-18))*(s?.7:1);return po(n,s?118:164,s?154:210)}function O0(t,{compact:s}){const i=xo(t,s?11:13,3),n=(s?40:48)+(i-1)*(s?6:8)+Math.min(s?18:26,Math.max(0,t.trim().length-(s?12:16)))*(s?.45:.55);return po(n,s?42:50,s?56:68)}function ca(t,{compact:s,emphasis:i=!1}){const n=xo(t,s?16:i?22:20,i?3:2);return{width:po((s?i?184:152:i?224:176)+Math.min(t.length,48)*(s?1.8:2.15),s?i?188:156:i?228:184,s?i?248:208:i?300:244),height:n===1?s?64:70:n===2?s?82:92:s?98:110}}function gc(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 F0(t,{compact:s}){const i=t.map(r=>({...r,homeX:r.x,homeY:r.y,locked:r.kind==="goal"||r.kind==="ghost"})),a=s?28:40,n=s?.08:.06;for(let r=0;r<180;r+=1){for(const l of i)l.locked||(l.x+=(l.homeX-l.x)*n,l.y+=(l.homeY-l.y)*n);for(let l=0;l<i.length;l+=1)for(let o=l+1;o<i.length;o+=1){const c=i[l],x=i[o],v=gc(c),u=gc(x),f=x.x-c.x,h=x.y-c.y,m=v.halfWidth+u.halfWidth+a-Math.abs(f),b=v.halfHeight+u.halfHeight+a-Math.abs(h);if(m<=0||b<=0)continue;const w=m<b?"x":"y",M=Math.sign(w==="x"?f||o-l||1:h||o-l||1),E=(w==="x"?m:b)/(c.locked||x.locked?1:2);c.locked||(w==="x"?c.x-=M*E:c.y-=M*E),x.locked||(w==="x"?x.x+=M*E:x.y+=M*E)}}return i.map(({homeX:r,homeY:l,locked:o,...c})=>c)}function _0(){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 Zm(t,{compact:s=!1}={}){var x;if(t.length===0)return _0();const i=[],a=[],n=[],r={},l=s?560:840,o=-((t.length-1)*l)/2;t.forEach((v,u)=>{const f=o+u*l,h=u%2===0?92:146,m=v.linkedBehaviors.length+v.linkedBeliefs.length+v.linkedReports.length+v.linkedHabits.length,b=`goal:${v.goal.id}`;i.push({id:b,kind:"goal",x:f,y:h,radius:$0(v.goal.title,{compact:s}),tone:"amber",label:v.goal.title,href:`/goals/${v.goal.id}`}),r[b]={id:b,eyebrow:"Goal",title:v.goal.title,summary:v.goal.description,href:`/goals/${v.goal.id}`,ctaLabel:"Open goal",tone:"amber",entityKind:"goal",chips:v.linkedValues.slice(0,4).map(g=>g.title),stats:[`${v.linkedValues.length} linked value${v.linkedValues.length===1?"":"s"}`,`${v.linkedProjects.length} live project${v.linkedProjects.length===1?"":"s"}`,`${v.linkedHabits.length} linked habit${v.linkedHabits.length===1?"":"s"}`,`${m} friction signal${m===1?"":"s"}`]},m>0&&n.push({id:`field:${v.goal.id}`,x:f+18,y:h+20,radiusX:s?144:176,radiusY:s?104:132,tone:"rose",opacity:Math.min(.42,.14+m*.04)});const w=s?208:282;v.linkedValues.slice(0,s?4:5).forEach((g,C)=>{const F=(-95+C*(s?78:64))*(Math.PI/180),z=O0(g.title,{compact:s}),J=f+Math.cos(F)*w,O=h+Math.sin(F)*w,_=`value:${g.id}`;i.push({id:_,kind:"value",x:J,y:O,radius:z,tone:"mint",label:g.title,meta:`${g.linkedGoalIds.length} goal${g.linkedGoalIds.length===1?"":"s"}`,href:`/psyche/values?focus=${g.id}#values-atlas`}),a.push({id:`${b}->${_}`,from:b,to:_,tone:"mint",strength:"medium"}),r[_]={id:_,eyebrow:"Value",title:g.title,summary:g.valuedDirection||g.whyItMatters||g.description,href:`/psyche/values?focus=${g.id}#values-atlas`,ctaLabel:"Open values",tone:"mint",entityKind:"value",chips:g.committedActions.slice(0,3),stats:[`${g.linkedProjectIds.length} linked project${g.linkedProjectIds.length===1?"":"s"}`,`${g.linkedTaskIds.length} linked task${g.linkedTaskIds.length===1?"":"s"}`]}});const M=v.linkedProjects.slice(0,s?2:3).map(g=>({project:g,size:ca(g.title,{compact:s,emphasis:!0})})),E=s?24:30;let j=-(M.reduce((g,C)=>g+C.size.width,0)+Math.max(0,M.length-1)*E)/2;M.forEach(({project:g,size:C},F)=>{const z=`project:${g.id}`,J=f+j+C.width/2,O=h-(s?330:434)-F*(s?16:20);j+=C.width+E,i.push({id:z,kind:"project",x:J,y:O,width:C.width,height:C.height,tone:"sky",label:g.title,meta:"Project",href:`/projects/${g.id}`}),a.push({id:`${b}->${z}`,from:b,to:z,tone:"sky",strength:"medium"}),r[z]={id:z,eyebrow:"Project",title:g.title,summary:g.description,href:`/projects/${g.id}`,ctaLabel:"Open project",tone:"sky",entityKind:"project",chips:[g.status,g.goalTitle],stats:[`${g.progress}% progress`,`${g.activeTaskCount} active task${g.activeTaskCount===1?"":"s"}`]}}),v.linkedHabits.slice(0,s?2:3).forEach((g,C)=>{const F=`habit:${g.id}`,z=ca(g.title,{compact:s}),J=f-(s?44:58),O=h+(s?228:294)+C*(s?92:104);i.push({id:F,kind:"habit",x:J,y:O,width:z.width,height:z.height,tone:"mint",label:g.title,meta:g.polarity,href:"/habits"}),a.push({id:`${b}->${F}`,from:b,to:F,tone:"mint",strength:g.dueToday?"high":"medium"}),r[F]={id:F,eyebrow:"Habit",title:g.title,summary:g.description||"Recurring operating record connected directly to this goal field.",href:"/habits",ctaLabel:"Open habits",tone:"mint",entityKind:"habit",chips:[g.polarity,g.frequency,g.dueToday?"due today":"checked in"],stats:[`${g.streakCount} streak`,`${g.rewardXp}/${g.penaltyXp} xp flow`]}});let S=h+(s?132:156);v.linkedBehaviors.slice(0,s?2:3).forEach(g=>{const C=`behavior:${g.id}`,F=ca(g.title,{compact:s}),z=f-(s?272:352);i.push({id:C,kind:"behavior",x:z,y:S,width:F.width,height:F.height,tone:"orange",label:g.title,meta:g.kind,href:`/psyche/behaviors?focus=${g.id}#behavior-columns`}),a.push({id:`${b}->${C}`,from:b,to:C,tone:"orange",dashed:g.kind!=="committed",strength:g.kind==="committed"?"medium":"low"}),r[C]={id:C,eyebrow:"Behavior",title:g.title,summary:g.replacementMove||g.description||g.urgeStory,href:`/psyche/behaviors?focus=${g.id}#behavior-columns`,ctaLabel:"Open behaviors",tone:"orange",entityKind:"behavior",chips:[g.kind,...g.commonCues.slice(0,2)],stats:[g.shortTermPayoff?"Short-term payoff mapped":"Payoff still to map",g.longTermCost?"Long-term cost mapped":"Cost still to map"]},S+=F.height+(s?18:22)});let p=h+(s?8:10);v.linkedBeliefs.slice(0,s?2:3).forEach(g=>{const C=`belief:${g.id}`,F=ca(g.statement,{compact:s,emphasis:!0}),z=f+(s?278:362);i.push({id:C,kind:"belief",x:z,y:p,width:F.width,height:F.height,tone:"violet",label:g.statement,meta:"belief",href:`/psyche/schemas-beliefs?focus=${g.id}`}),a.push({id:`${b}->${C}`,from:b,to:C,tone:"violet",dashed:!0,strength:"low"}),r[C]={id:C,eyebrow:"Belief",title:g.statement,summary:g.flexibleAlternative||g.originNote||"Belief script attached to this part of the map.",href:`/psyche/schemas-beliefs?focus=${g.id}`,ctaLabel:"Open beliefs",tone:"violet",entityKind:"belief",chips:[g.beliefType,`${g.confidence}% grip`],stats:[`${g.linkedBehaviorIds.length} linked behavior${g.linkedBehaviorIds.length===1?"":"s"}`,`${g.linkedReportIds.length} linked report${g.linkedReportIds.length===1?"":"s"}`]},p+=F.height+(s?18:22)});const A=v.linkedReports.slice(0,s?2:3).map(g=>({report:g,size:ca(g.title,{compact:s})})),T=s?20:26;let $=-(A.reduce((g,C)=>g+C.size.width,0)+Math.max(0,A.length-1)*T)/2;A.forEach(({report:g,size:C})=>{const F=`report:${g.id}`,z=f+$+C.width/2,J=h+(s?332:430);$+=C.width+T,i.push({id:F,kind:"report",x:z,y:J,width:C.width,height:C.height,tone:"blue",label:g.title,meta:g.status,href:`/psyche/reports/${g.id}`}),a.push({id:`${b}->${F}`,from:b,to:F,tone:"sky",strength:"medium"}),r[F]={id:F,eyebrow:"Report",title:g.title,summary:g.eventSituation||g.customEventType||"Reflective chain linked into this goal.",href:`/psyche/reports/${g.id}`,ctaLabel:"Open report",tone:"blue",entityKind:"report",chips:[g.status,...g.nextMoves.slice(0,2)],stats:[`${g.emotions.length} emotion${g.emotions.length===1?"":"s"}`,`${g.behaviors.length} move${g.behaviors.length===1?"":"s"}`]}})});const c=((x=i[0])==null?void 0:x.id)??"ghost_goal_center";return{nodes:F0(i,{compact:s}),edges:a,fields:n,inspectors:r,defaultSelectedId:c}}const ti={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)"},Mr={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)"},si={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 eu(t){switch(t){case"goal":case"value":case"behavior":case"belief":case"report":case"project":case"habit":return t;default:return null}}function R0(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 z0(t){if(t.kind==="ghost")return t.meta??null;const s=eu(t.kind);return s?Ts(s).label:t.meta??null}function Ar(t,s,i){return Math.min(Math.max(t,s),i)}function en(t,s,i=3){const a=t.trim().split(/\s+/),n=[];let r="";for(let c=0;c<a.length;c+=1){const x=a[c],v=r?`${r} ${x}`:x;if(v.length>s&&r){if(n.push(r),n.length>=i-1){r=[x,...a.slice(c+1)].join(" ");break}r=x}else r=v}r&&n.push(r);const l=n.slice(0,i),o=l.length-1;return o>=0&&l[o].length>s&&(l[o]=`${l[o].slice(0,Math.max(1,s-1)).trimEnd()}…`),l}function q0(t,s){if(t.length===0&&s.length===0)return{minX:-360,maxX:360,minY:-240,maxY:240};let i=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,n=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(const l of t){const o=l.kind==="goal"||l.kind==="value"||l.kind==="ghost"?l.radius??32:(l.width??124)/2,c=l.kind==="goal"||l.kind==="value"||l.kind==="ghost"?l.radius??32:(l.height??56)/2,x=l.meta&&(l.kind==="goal"||l.kind==="ghost")?48:0;i=Math.min(i,l.x-o),a=Math.max(a,l.x+o),n=Math.min(n,l.y-c-x),r=Math.max(r,l.y+c)}for(const l of s)i=Math.min(i,l.x-l.radiusX),a=Math.max(a,l.x+l.radiusX),n=Math.min(n,l.y-l.radiusY),r=Math.max(r,l.y+l.radiusY);return{minX:i,maxX:a,minY:n,maxY:r}}function fc(t){return{x:t.x,y:t.y}}function B0(t){if(t.kind==="goal"){const s=t.radius??112;return en(t.label,Math.max(14,Math.floor(s/7.2)),4)}if(t.kind==="value"||t.kind==="ghost"){const s=t.radius??40;return en(t.label,Math.max(12,Math.floor(s/3)),3)}return t.kind==="project"?en(t.label,Math.max(18,Math.floor((t.width??220)/10)),3):en(t.label,Math.max(16,Math.floor((t.width??180)/10.5)),2)}function K0(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 tu({nodes:t,edges:s,fields:i=[],title:a,hint:n,action:r,legend:l,selectedNodeId:o,onSelectNode:c,minHeightClassName:x="min-h-[34rem] lg:min-h-[44rem]",compact:v=!1,testId:u}){const f=d.useRef(null),h=ut(),[m,b]=d.useState({width:0,height:0}),[w,M]=d.useState({scale:1,x:0,y:0}),[E,D]=d.useState(null),j=d.useRef(null),S=d.useRef({scale:1,x:0,y:0}),p=d.useRef(new Map),A=d.useRef(null),T=d.useRef(0),k=d.useRef(!1),$=d.useMemo(()=>new Map(t.map(I=>[I.id,I])),[t]),g=d.useMemo(()=>q0(t,i),[i,t]),C=m.width>0&&m.width<640;d.useEffect(()=>{if(!f.current||typeof ResizeObserver>"u")return;const I=new ResizeObserver(G=>{const W=G[0];b({width:W.contentRect.width,height:W.contentRect.height})});return I.observe(f.current),()=>I.disconnect()},[]);const F=d.useCallback(()=>{if(!m.width||!m.height)return;const I=C?132:v?140:190,G=Math.max(g.maxX-g.minX,1),W=Math.max(g.maxY-g.minY,1),ne=Ar(Math.min(m.width/(G+I),m.height/(W+I)),C?.24:v?.4:.46,C?.76:v?1.04:1.18),de=(g.minX+g.maxX)/2,we=(g.minY+g.maxY)/2;M({scale:ne,x:m.width/2-de*ne,y:m.height/2-we*ne})},[g.maxX,g.maxY,g.minX,g.minY,v,m.height,m.width,C]);d.useEffect(()=>{S.current=w},[w]),d.useEffect(()=>{k.current||F()},[F]);const z=d.useCallback((I,G,W)=>{const ne=Ar(I,.28,1.9);M(de=>{if(G==null||W==null)return{...de,scale:ne};const we=(G-de.x)/de.scale,Ne=(W-de.y)/de.scale;return{scale:ne,x:G-we*ne,y:W-Ne*ne}})},[]),J=d.useCallback(()=>{const I=[...p.current.values()];if(I.length<2){A.current=null;return}const[G,W]=I,ne=Math.hypot(W.x-G.x,W.y-G.y);if(!Number.isFinite(ne)||ne<=0){A.current=null;return}const de=S.current;A.current={startDistance:ne,startScale:de.scale,startViewportX:de.x,startViewportY:de.y,startMidpointX:(G.x+W.x)/2,startMidpointY:(G.y+W.y)/2}},[]),O=I=>{var ne;I.preventDefault();const G=(ne=f.current)==null?void 0:ne.getBoundingClientRect();if(!G)return;k.current=!0;const W=I.deltaY<0?1.1:.9;z(w.scale*W,I.clientX-G.left,I.clientY-G.top)},_=I=>{var de;const G=(de=f.current)==null?void 0:de.getBoundingClientRect(),W=I.clientX-((G==null?void 0:G.left)??0),ne=I.clientY-((G==null?void 0:G.top)??0);if(p.current.set(I.pointerId,{x:W,y:ne}),p.current.size===1){const we=S.current;j.current={pointerId:I.pointerId,originX:we.x,originY:we.y,startX:W,startY:ne}}else j.current=null,J();I.currentTarget.setPointerCapture(I.pointerId)},B=I=>{var Ne;const G=(Ne=f.current)==null?void 0:Ne.getBoundingClientRect(),W=I.clientX-((G==null?void 0:G.left)??0),ne=I.clientY-((G==null?void 0:G.top)??0);if(p.current.has(I.pointerId)&&p.current.set(I.pointerId,{x:W,y:ne}),A.current&&p.current.size>=2){const[H,me]=[...p.current.values()],y=Math.hypot(me.x-H.x,me.y-H.y);if(Number.isFinite(y)&&y>0){k.current=!0,T.current=Date.now()+240;const P=(H.x+me.x)/2,q=(H.y+me.y)/2,pe=A.current,ee=Ar(pe.startScale*y/pe.startDistance,.24,1.42),Y=(pe.startMidpointX-pe.startViewportX)/pe.startScale,R=(pe.startMidpointY-pe.startViewportY)/pe.startScale;M({scale:ee,x:P-Y*ee,y:q-R*ee})}return}if(!j.current||j.current.pointerId!==I.pointerId||p.current.size!==1)return;k.current=!0;const de=W-j.current.startX,we=ne-j.current.startY;(Math.abs(de)>3||Math.abs(we)>3)&&(T.current=Date.now()+240),M(H=>{var me,y;return{...H,x:(((me=j.current)==null?void 0:me.originX)??H.x)+de,y:(((y=j.current)==null?void 0:y.originY)??H.y)+we}})},K=I=>{if(p.current.delete(I.pointerId),p.current.size<2&&(A.current=null),p.current.size===1){const[G,W]=[...p.current.entries()][0]??[];if(G!=null&&W){const ne=S.current;j.current={pointerId:G,originX:ne.x,originY:ne.y,startX:W.x,startY:W.y}}}else j.current=null;I.currentTarget.hasPointerCapture(I.pointerId)&&I.currentTarget.releasePointerCapture(I.pointerId)},Z=E??o??null,U=d.useCallback(I=>{Date.now()<T.current||(c==null||c(I.id),I.href&&h(I.href))},[h,c]);return e.jsxs("section",{"data-testid":u,className:re("overflow-hidden rounded-[32px] border border-white/8 bg-[radial-gradient(circle_at_top,rgba(125,211,252,0.12),transparent_32%),linear-gradient(180deg,rgba(11,18,31,0.985),rgba(7,12,23,0.98))] shadow-[0_26px_90px_rgba(2,6,16,0.38)]","px-3 py-3 sm:px-4 sm:py-4 lg:px-5 lg:py-5"),children:[e.jsxs("div",{className:"mb-3 flex min-w-0 flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-[rgba(125,211,252,0.82)]",children:"Gravity well"}),e.jsx("h2",{className:re("mt-2 font-display leading-none text-white",v?"text-[clamp(1.25rem,2vw,1.7rem)]":"text-[clamp(1.45rem,2.8vw,2.3rem)]"),children:a}),n?e.jsx("p",{className:"mt-1.5 max-w-3xl text-sm leading-6 text-white/54",children:C?"Select a node, pan the field, and open the full map when you need the wider structure.":n}):null]}),e.jsx("div",{className:"flex min-w-0 flex-wrap items-center justify-end gap-2",children:r})]}),e.jsxs("div",{ref:f,className:re("group relative overflow-hidden rounded-[30px] border border-white/6 bg-[radial-gradient(circle_at_center,rgba(255,255,255,0.04),transparent_46%)] touch-none",x),style:{touchAction:"none"},onWheel:O,onPointerDown:_,onPointerMove:B,onPointerUp:K,onPointerCancel:K,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:I=>I.stopPropagation(),children:[e.jsx(Mp,{className:"size-3.5"}),C?"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:I=>I.stopPropagation(),children:[e.jsx(Q,{type:"button",variant:"secondary",size:"sm",className:"px-2.5 sm:px-3","aria-label":"Zoom in",onClick:()=>{k.current=!0,z(w.scale*1.12,m.width-96,72)},children:e.jsx(zt,{className:"size-4"})}),e.jsx(Q,{type:"button",variant:"secondary",size:"sm",className:"px-2.5 sm:px-3","aria-label":"Zoom out",onClick:()=>{k.current=!0,z(w.scale*.88,m.width-96,72)},children:e.jsx(Ap,{className:"size-4"})}),e.jsxs(Q,{type:"button",variant:"secondary",size:"sm",className:"px-2.5 sm:min-w-[4.75rem] sm:px-3","aria-label":"Fit graph",onClick:()=>{k.current=!0,F()},children:[e.jsx(Ep,{className:"size-4"}),C?null:"Fit"]}),e.jsxs(Q,{type:"button",variant:"secondary",size:"sm",className:"px-2.5 sm:min-w-[5.5rem] sm:px-3","aria-label":"Reset graph",onClick:()=>{k.current=!1,F()},children:[e.jsx(fh,{className:"size-4"}),C?null:"Reset"]})]}),l&&l.length>0&&!C?e.jsx("div",{className:"absolute bottom-4 left-4 z-10 flex flex-wrap items-center gap-2 rounded-[24px] border border-white/8 bg-[rgba(8,14,25,0.76)] px-3 py-2 text-xs text-white/58 backdrop-blur-xl",children:l.map(I=>{const G=I.kind?K0(I.kind):I.tone??"slate",W=I.kind?Ts(I.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:[W?e.jsx(W,{className:"size-3.5",color:si[G],strokeWidth:2.1}):e.jsx("span",{className:"size-2 rounded-full",style:{backgroundColor:ti[G]}}),I.label]},I.label)})}):null,e.jsxs("svg",{className:"relative z-[1] h-full w-full",viewBox:`0 0 ${m.width||1200} ${m.height||760}`,role:"img","aria-label":a,children:[e.jsx("defs",{children:e.jsx("filter",{id:"forge-graph-blur",children:e.jsx("feGaussianBlur",{stdDeviation:"34"})})}),e.jsxs("g",{transform:`translate(${w.x} ${w.y}) scale(${w.scale})`,children:[i.map(I=>e.jsx("ellipse",{cx:I.x,cy:I.y,rx:I.radiusX,ry:I.radiusY,fill:Mr[I.tone??"rose"],opacity:I.opacity??.42,filter:"url(#forge-graph-blur)"},I.id)),t.filter(I=>I.kind==="goal"||I.kind==="ghost").map(I=>{const G=I.radius??76;return e.jsx("g",{opacity:I.kind==="ghost"?.28:.55,children:[G+74,G+124].map((W,ne)=>e.jsx("circle",{cx:I.x,cy:I.y,r:W,fill:"none",stroke:ne===0?"rgba(255,255,255,0.08)":"rgba(255,255,255,0.045)",strokeDasharray:ne===0?"0":"10 10"},`${I.id}-ring-${W}`))},`${I.id}-orbital-lanes`)}),s.map(I=>{const G=$.get(I.from),W=$.get(I.to);if(!G||!W)return null;const ne=fc(G),de=fc(W),we=(ne.x+de.x)/2,Ne=(ne.y+de.y)/2,H=Math.max(24,Math.abs(ne.x-de.x)*.08),me=we,y=Ne-H;return e.jsx("path",{d:`M ${ne.x} ${ne.y} Q ${me} ${y} ${de.x} ${de.y}`,fill:"none",stroke:ti[I.tone??"slate"],strokeWidth:I.strength==="high"?3:I.strength==="medium"?2.2:1.6,strokeDasharray:I.dashed?"8 8":void 0,opacity:Z&&I.from!==Z&&I.to!==Z?.18:.62},I.id)}),t.map(I=>{I.id;const G=E===I.id,W=Z===I.id,ne=R0(I),de=z0(I),we=B0(I),Ne=eu(I.kind),H=Ne?Ts(Ne).icon:null;if(I.kind==="goal"||I.kind==="value"||I.kind==="ghost"){const te=I.radius??(I.kind==="goal"?76:34),ce=de?I.y-te-(I.kind==="goal"?18:10):null,Se=I.kind==="goal"?20:14.5,he=I.kind==="goal"?28:16,Ge=I.kind==="goal"?I.y-te*.34:I.kind==="value"?I.y-te*.3:I.y-te*.2,De=I.kind==="goal"?I.y+te*.2:I.y+10;return e.jsxs("g",{tabIndex:0,role:"button",onPointerEnter:()=>{D(I.id),c==null||c(I.id)},onPointerLeave:()=>D(ue=>ue===I.id?null:ue),onFocus:()=>c==null?void 0:c(I.id),onClick:()=>U(I),onKeyDown:ue=>{(ue.key==="Enter"||ue.key===" ")&&(ue.preventDefault(),U(I))},className:"cursor-pointer outline-none",children:[e.jsx("circle",{cx:I.x,cy:I.y,r:te+(W?14:0),fill:W?`${ti[ne]}22`:"transparent",stroke:W?ti[ne]:"transparent",opacity:G?.98:.9}),e.jsx("circle",{cx:I.x,cy:I.y,r:te+(G?2:0),fill:I.kind==="ghost"?"rgba(255,255,255,0.03)":Mr[ne],stroke:I.kind==="ghost"?"rgba(255,255,255,0.18)":ti[ne],strokeDasharray:I.kind==="ghost"?"8 8":void 0,strokeWidth:W?2.8:1.6}),de?e.jsx("text",{x:I.x,y:ce??I.y-12,textAnchor:"middle",fontSize:I.kind==="goal"?"11.5":"10.5",fill:I.kind==="ghost"?"rgba(255,255,255,0.62)":si[ne],style:{letterSpacing:"0.18em",textTransform:"uppercase"},children:de}):null,H?e.jsx(H,{x:I.x-he/2,y:Ge-he/2,width:he,height:he,color:si[ne],strokeWidth:2.1}):null,we.map((ue,Fe)=>e.jsx("text",{x:I.x,y:De+Fe*Se-(we.length-1)*Se/2,textAnchor:"middle",fontSize:I.kind==="goal"?21:12.8,fontWeight:I.kind==="goal"?600:500,fill:I.kind==="ghost"?"rgba(255,255,255,0.92)":si[ne],children:ue},`${I.id}-${ue}-${Fe}`))]},I.id)}const me=I.width??146,y=I.height??58,P=I.x-me/2,q=I.y-y/2,pe=I.kind==="project"?14:13,ee=P+14,Y=q+13,R=q+22,X=de?q+y*.65:q+y*.56,be=I.kind==="project"?16:15,Ie=I.kind==="project"?14.2:13.2;return e.jsxs("g",{tabIndex:0,role:"button",onPointerEnter:()=>{D(I.id),c==null||c(I.id)},onPointerLeave:()=>D(te=>te===I.id?null:te),onFocus:()=>c==null?void 0:c(I.id),onClick:()=>U(I),onKeyDown:te=>{(te.key==="Enter"||te.key===" ")&&(te.preventDefault(),U(I))},className:"cursor-pointer outline-none",children:[e.jsx("rect",{x:P-(W?6:0),y:q-(W?6:0),rx:"28",ry:"28",width:me+(W?12:0),height:y+(W?12:0),fill:W?`${ti[ne]}22`:"transparent"}),e.jsx("rect",{x:P-(G?2:0),y:q-(G?2:0),rx:"22",ry:"22",width:me+(G?4:0),height:y+(G?4:0),fill:Mr[ne],stroke:ti[ne],strokeWidth:W?2.3:1.3}),H?e.jsx(H,{x:ee,y:Y,width:pe,height:pe,color:si[ne],strokeWidth:2.1}):null,de?e.jsx("text",{x:ee+pe+8,y:R,textAnchor:"start",fontSize:"9.5",fill:si[ne],style:{letterSpacing:"0.16em",textTransform:"uppercase",opacity:.82},children:de}):null,we.map((te,ce)=>e.jsx("text",{x:I.x,y:X+ce*be-(we.length-1)*be/2,textAnchor:"middle",fontSize:Ie,fontWeight:600,fill:si[ne],children:te},`${I.id}-${te}-${ce}`))]},I.id)})]})]})]})]})}const bc={intent:"trigger_report",linkedGoalId:"",linkedProjectId:"",linkedTaskId:""};function U0({open:t,onOpenChange:s}){const i=ut(),a=Je(),[n,r]=d.useState(bc),l=[{id:"intent",eyebrow:"Reflect",title:"What do you want to reflect on?",description:"Choose the entrypoint first. Forge will route you into the right guided flow instead of dropping you into a generic form.",render:(c,x)=>e.jsx(Ze,{columns:3,value:c.intent,onChange:v=>x({intent:v}),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,x)=>e.jsx("div",{className:"grid gap-4",children:e.jsx(se,{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(Te,{kind:"goal",label:"Goal",compact:!0,gradient:!1}),e.jsx(Te,{kind:"project",label:"Project",compact:!0,gradient:!1}),e.jsx(Te,{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:v=>x({linkedGoalId:v.target.value}),children:[e.jsx("option",{value:"",children:"No goal selected"}),a.snapshot.goals.map(v=>e.jsxs("option",{value:v.id,children:["Goal · ",v.title]},v.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:v=>x({linkedProjectId:v.target.value}),children:[e.jsx("option",{value:"",children:"No project selected"}),a.snapshot.dashboard.projects.map(v=>e.jsxs("option",{value:v.id,children:["Project · ",v.title]},v.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:v=>x({linkedTaskId:v.target.value}),children:[e.jsx("option",{value:"",children:"No task selected"}),a.snapshot.tasks.slice(0,40).map(v=>e.jsxs("option",{value:v.id,children:["Task · ",v.title]},v.id))]})]})})})}],o=async()=>{const c=new URLSearchParams({create:"1",intent:n.intent});switch(n.linkedGoalId&&c.set("goalId",n.linkedGoalId),n.linkedProjectId&&c.set("projectId",n.linkedProjectId),n.linkedTaskId&&c.set("taskId",n.linkedTaskId),n.intent){case"behavior":i(`/psyche/behaviors?${c.toString()}`);break;case"belief":i(`/psyche/schemas-beliefs?${c.toString()}`);break;case"pattern":i(`/psyche/patterns?${c.toString()}`);break;case"value":i(`/psyche/values?${c.toString()}`);break;case"execution_tension":case"trigger_report":default:i(`/psyche/reports?${c.toString()}`);break}s(!1),r(bc)};return e.jsx(rt,{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:n,onChange:r,steps:l,submitLabel:"Open guided reflection",onSubmit:o})}function Er({to:t,children:s,className:i}){return e.jsx(Ae,{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(ae,{className:re("transition-[transform,box-shadow,background] duration-[var(--motion-medium)] ease-[var(--ease-standard)] group-hover:bg-white/[0.06] group-hover:shadow-[var(--card-shadow-hover)] group-focus-visible:shadow-[var(--card-shadow-hover)]",i),children:s})})}function Q0(){var D,j;const t=Je(),[s,i]=Pt(),[a,n]=d.useState(s.get("reflect")==="1"),[r,l]=d.useState(null),o=fe({queryKey:["forge-psyche-overview"],queryFn:Wn}),c=fe({queryKey:["forge-psyche-questionnaires-hub"],queryFn:()=>Ah()}),x=(D=o.data)==null?void 0:D.overview,v=d.useMemo(()=>x?t.snapshot.goals.slice(0,3).map(S=>{const p=x.values.filter(C=>C.linkedGoalIds.includes(S.id)),A=t.snapshot.dashboard.projects.filter(C=>C.goalId===S.id),T=t.snapshot.habits.filter(C=>C.linkedGoalIds.includes(S.id)||C.linkedValueIds.some(F=>p.some(z=>z.id===F))),k=x.reports.filter(C=>C.linkedGoalIds.includes(S.id)),$=x.behaviors.filter(C=>C.linkedValueIds.some(F=>p.some(z=>z.id===F))),g=x.beliefs.filter(C=>C.linkedValueIds.some(F=>p.some(z=>z.id===F)));return{goal:S,linkedValues:p,linkedProjects:A,linkedHabits:T,linkedReports:k,linkedBehaviors:$,linkedBeliefs:g}}):[],[x,t.snapshot.dashboard.projects,t.snapshot.goals,t.snapshot.habits]),u=d.useMemo(()=>Zm(v,{compact:!0}),[v]);if(d.useEffect(()=>{l(u.defaultSelectedId)},[u.defaultSelectedId]),o.isLoading)return e.jsx(It,{});if(o.isError||!x)return e.jsx(ze,{eyebrow:"Psyche",error:o.error,onRetry:()=>void o.refetch()});const f=u.inspectors[r??u.defaultSelectedId]??u.inspectors[u.defaultSelectedId],h=x.patterns[0]??null,m=x.reports[0]??null,b=[...((j=c.data)==null?void 0:j.instruments)??[]].sort((S,p)=>{const A=S.latestRunAt?new Date(S.latestRunAt).getTime():0;return(p.latestRunAt?new Date(p.latestRunAt).getTime():0)-A})[0]??null,w="Values, patterns, behaviors, beliefs, habits, and reports in one live field.",M=e.jsx(Ae,{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=[{id:"hero",title:"Psyche",description:"Top route composition",defaultWidth:12,defaultHeight:1,removable:!1,surfaceChrome:"none",defaultTitleVisible:!1,defaultDescriptionVisible:!1,render:()=>e.jsx(qe,{title:"Psyche",titleText:"Psyche",description:w,actions:M})},{id:"sections",title:"Psyche sections",description:"Section switcher",defaultWidth:12,defaultHeight:1,surfaceChrome:"none",defaultTitleVisible:!1,defaultDescriptionVisible:!1,render:()=>e.jsx(Bt,{})},{id:"field",title:"Live field",description:"Graph and inspector stay as movable widgets.",defaultWidth:8,defaultHeight:5,minWidth:6,render:()=>e.jsx(tu,{testId:"psyche-hub-graph",compact:!0,title:"Reflective pulse and live entity field",hint:"Select any goal, value, habit, belief, behavior, project, or report.",nodes:u.nodes,edges:u.edges,fields:u.fields,selectedNodeId:r,onSelectNode:l,minHeightClassName:"min-h-[20rem] sm:min-h-[24rem] lg:min-h-[34rem]",legend:[{label:"Goals",kind:"goal"},{label:"Values",kind:"value"},{label:"Habits",kind:"habit"},{label:"Behaviors",kind:"behavior"}],action:e.jsxs(e.Fragment,{children:[e.jsx(Ae,{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(Q,{size:"sm",className:"min-w-0 sm:min-w-[6.5rem]",onClick:()=>n(!0),children:"Reflect"})]})})},{id:"inspector",title:"Inspector",description:"Selected-node inspector widget.",defaultWidth:4,defaultHeight:5,minWidth:4,render:()=>e.jsxs(ae,{className:"h-full min-w-0",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:f.entityKind?e.jsx(Te,{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(Xe,{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(S=>e.jsx(L,{className:"bg-white/[0.08] text-white/74",children:S},S))}):null,f.stats.length>0?e.jsx("div",{className:"mt-4 grid gap-2",children:f.stats.map(S=>e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/68",children:S},S))}):null,e.jsx("div",{className:"mt-5",children:e.jsx(Ae,{to:f.href,className:re("inline-flex min-h-11 w-full items-center justify-center rounded-[var(--radius-control)] px-4 py-2.5 text-sm font-medium whitespace-nowrap shadow-[0_12px_30px_rgba(192,193,255,0.08)]",f.entityKind?ja(f.entityKind,!0):"bg-[linear-gradient(135deg,rgba(192,193,255,0.36),rgba(192,193,255,0.22))] text-white"),children:f.ctaLabel})})]})},{id:"actions",title:"Open threads",description:"Action and pulse cards.",defaultWidth:12,defaultHeight:3,render:()=>e.jsxs("div",{className:"grid min-w-0 gap-4 lg:grid-cols-[minmax(0,1.05fr)_minmax(0,0.95fr)]",children:[e.jsxs(Er,{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:(h==null?void 0:h.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:(h==null?void 0:h.targetBehavior)||"When the loop is explicit, the return path stops feeling abstract."})]}),e.jsxs(Er,{to:m?`/psyche/reports/${m.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:x.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:x.openNotes})]})]})]})]})},{id:"questionnaires",title:"Questionnaire pulse",description:"Recent questionnaire state.",defaultWidth:12,defaultHeight:2,render:()=>{var S;return e.jsxs(Er,{to:b!=null&&b.latestRunId?`/psyche/questionnaire-runs/${b.latestRunId}`:"/psyche/questionnaires",className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(17,31,39,0.97),rgba(10,18,24,0.95))] p-5",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-sky-100/72",children:"Questionnaire pulse"}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"font-display text-[clamp(1.4rem,2.2vw,2rem)] leading-none text-white",children:(b==null?void 0:b.title)??"Questionnaire library ready"}),e.jsxs(L,{className:"bg-white/[0.08] text-white/78",children:[(((S=c.data)==null?void 0:S.instruments)??[]).length," available"]})]})]})}}];return e.jsxs("div",{className:"grid min-w-0 gap-4 overflow-x-clip",children:[e.jsx(_a,{surfaceId:"psyche",baseWidgets:E}),e.jsx(U0,{open:a,onOpenChange:S=>{n(S);const p=new URLSearchParams(s);p.delete("reflect"),i(p,{replace:!0})}})]})}function Ps({eyebrow:t,title:s,description:i,titleHelp:a,tone:n="default",children:r,className:l}){const o={default:"bg-[linear-gradient(180deg,rgba(17,24,35,0.96),rgba(11,16,24,0.94))]",mint:"bg-[radial-gradient(circle_at_top_left,rgba(110,231,183,0.14),transparent_42%),linear-gradient(180deg,rgba(14,28,31,0.96),rgba(10,20,24,0.94))]",sky:"bg-[radial-gradient(circle_at_top_left,rgba(125,211,252,0.14),transparent_42%),linear-gradient(180deg,rgba(16,25,34,0.96),rgba(10,17,24,0.94))]",violet:"bg-[radial-gradient(circle_at_top_left,rgba(196,181,253,0.14),transparent_42%),linear-gradient(180deg,rgba(20,19,35,0.96),rgba(12,13,24,0.94))]",rose:"bg-[radial-gradient(circle_at_top_left,rgba(251,113,133,0.14),transparent_42%),linear-gradient(180deg,rgba(31,18,24,0.96),rgba(18,11,16,0.94))]",amber:"bg-[radial-gradient(circle_at_top_left,rgba(251,191,36,0.14),transparent_42%),linear-gradient(180deg,rgba(32,24,16,0.96),rgba(20,15,10,0.94))]"};return e.jsxs("section",{className:re("min-w-0 overflow-hidden rounded-[30px] border border-white/8 px-4 py-5 shadow-[0_24px_70px_rgba(4,8,18,0.28)] sm:px-5 lg:px-6",o[n],l),children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:t}),e.jsxs("div",{className:"mt-3 flex min-w-0 items-start gap-2",children:[e.jsx("h2",{className:"min-w-0 font-display text-[clamp(1.8rem,3.2vw,3rem)] leading-none text-white",children:s}),a?e.jsx(it,{content:a,label:`Explain ${s.toLowerCase()}`,className:"mt-1 shrink-0"}):null]}),i?e.jsx("p",{className:"mt-3 max-w-3xl text-sm leading-7 text-white/60",children:i}):null,e.jsx("div",{className:"mt-5 min-w-0",children:r})]})}function W0({entries:t}){const s={away:"border-rose-400/20 bg-[rgba(251,113,133,0.08)]",committed:"border-emerald-400/20 bg-[rgba(110,231,183,0.08)]",recovery:"border-amber-400/20 bg-[rgba(251,191,36,0.08)]"};return e.jsx("div",{className:"grid gap-3 lg:grid-cols-3",children:t.map(i=>e.jsxs(Ae,{to:i.href,className:`rounded-[22px] border px-4 py-4 transition hover:-translate-y-0.5 ${s[i.tone]}`,children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:i.tone}),e.jsx("div",{className:"mt-2 font-medium text-white",children:i.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:i.summary}),e.jsxs("div",{className:"mt-4 inline-flex items-center gap-2 text-sm text-white/54",children:["Open",e.jsx(Gt,{className:"size-3.5"})]})]},i.id))})}const H0={maladaptive:"Maladaptive schema",adaptive:"Adaptive schema"},G0={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."},X0={disconnection_rejection:"Disconnection & rejection",impaired_autonomy:"Autonomy & competence",other_directedness:"Boundaries & mutuality",overvigilance_inhibition:"Standards & inhibition",healthy_selfhood:"Healthy selfhood"};function ar(t){return H0[t]}function ka(t){return G0[t]}function go(t){return X0[t]??t.replaceAll("_"," ")}function Gi(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 vc(t){return t.trim().toLowerCase()}function su(t,s){const i=vc(s);return[t.id,t.slug,t.title].some(a=>vc(a)===i)}function Xi(t,s){return s.find(i=>su(i,t))??null}function iu(t,s){const i=t.filter(a=>!su(s,a));return i.length===t.length?[...i,s.id]:i}function Ws({label:t,schemaType:s,compact:i=!1,showType:a=!1,className:n}){const r=Gi(s);return e.jsxs("span",{className:re("inline-flex max-w-full min-w-0 items-center gap-2 rounded-full border px-3 py-1.5 text-sm leading-tight shadow-[inset_0_1px_0_rgba(255,255,255,0.04)]",i?"min-h-8":"min-h-9",r.badgeTone,n),children:[a?e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/58",children:ar(s)}):null,e.jsx("span",{className:"min-w-0 break-words whitespace-normal",children:t})]})}function At(t,s,i,a){t.setQueryData(s,n=>{const r=(n==null?void 0:n[i])??[];return r.some(l=>l.id===a.id)?n:{...n??{},[i]:[a,...r]}})}const He=je().trim(),ht=He.min(1),V0=_e(ht).transform(t=>Array.from(new Set(t))),Ls=je().trim().min(1).nullable().optional(),wc=Ve({title:ht,description:He,valuedDirection:ht,whyItMatters:He,linkedGoalIds:_e(je()).default([]),linkedProjectIds:_e(je()).default([]),linkedTaskIds:_e(je()).default([]),committedActions:_e(He).default([]),userId:Ls}),yc=Ve({title:ht,description:He,targetBehavior:ht,cueContexts:_e(He).default([]),shortTermPayoff:He,longTermCost:He,preferredResponse:ht,linkedValueIds:_e(je()).default([]),linkedSchemaLabels:V0.default([]),linkedModeIds:_e(je()).default([]),linkedBeliefIds:_e(je()).default([]),userId:Ls}),jc=Ve({kind:vt(["away","committed","recovery"]),title:ht,description:He,commonCues:_e(He).default([]),urgeStory:He,shortTermPayoff:He,longTermCost:He,replacementMove:He,repairPlan:He,linkedPatternIds:_e(je()).default([]),linkedValueIds:_e(je()).default([]),linkedSchemaIds:_e(je()).default([]),linkedModeIds:_e(je()).default([]),userId:Ls}),Nc=Ve({schemaId:je().nullable(),statement:ht,beliefType:vt(["absolute","conditional"]),originNote:He,confidence:wl().int().min(0).max(100),evidenceFor:_e(He).default([]),evidenceAgainst:_e(He).default([]),flexibleAlternative:He,linkedValueIds:_e(je()).default([]),linkedBehaviorIds:_e(je()).default([]),linkedModeIds:_e(je()).default([]),linkedReportIds:_e(je()).default([]),userId:Ls}),kc=Ve({family:vt(["coping","child","critic_parent","healthy_adult","happy_child"]),archetype:He,title:ht,persona:He,imagery:He,symbolicForm:He,facialExpression:He,fear:He,burden:He,protectiveJob:He,originContext:He,firstAppearanceAt:je().trim().nullable(),linkedPatternIds:_e(je()).default([]),linkedBehaviorIds:_e(je()).default([]),linkedValueIds:_e(je()).default([]),userId:Ls}),J0=Ve({summary:ht,answers:_e(Ve({questionKey:ht,value:ht})).min(1),userId:Ls});Ve({label:ht,description:He,userId:Ls});Ve({label:ht,description:He,category:He,userId:Ls});const Y0=Ve({id:ht,emotionDefinitionId:je().nullable(),label:ht,intensity:wl().int().min(0).max(100),note:He}),Z0=Ve({id:ht,text:ht,parentMode:He,criticMode:He,beliefId:je().nullable()}),ej=Ve({id:ht,text:ht,mode:He,behaviorId:je().nullable()}),tj=Ve({id:ht,stage:ht,modeId:je().nullable(),label:ht,note:He}),hl=Ve({title:ht,status:vt(["draft","reviewed","integrated"]).default("draft"),eventTypeId:je().nullable(),customEventType:He,eventSituation:ht,occurredAt:je().trim().nullable(),emotions:_e(Y0).default([]),thoughts:_e(Z0).default([]),behaviors:_e(ej).default([]),consequences:Ve({selfShortTerm:_e(He).default([]),selfLongTerm:_e(He).default([]),othersShortTerm:_e(He).default([]),othersLongTerm:_e(He).default([])}),linkedPatternIds:_e(je()).default([]),linkedValueIds:_e(je()).default([]),linkedGoalIds:_e(je()).default([]),linkedProjectIds:_e(je()).default([]),linkedTaskIds:_e(je()).default([]),linkedBehaviorIds:_e(je()).default([]),linkedBeliefIds:_e(je()).default([]),linkedModeIds:_e(je()).default([]),modeOverlays:_e(He).default([]),schemaLinks:_e(He).default([]),modeTimeline:_e(tj).default([]),nextMoves:_e(He).default([]),userId:Ls}),ha={kind:"away",title:"",description:"",commonCues:[],urgeStory:"",shortTermPayoff:"",longTermCost:"",replacementMove:"",repairPlan:"",linkedPatternIds:[],linkedValueIds:[],linkedSchemaIds:[],linkedModeIds:[],userId:null};function sj(t){return{kind:t.kind,title:t.title,description:t.description,commonCues:t.commonCues,urgeStory:t.urgeStory,shortTermPayoff:t.shortTermPayoff,longTermCost:t.longTermCost,replacementMove:t.replacementMove,repairPlan:t.repairPlan,linkedPatternIds:t.linkedPatternIds,linkedValueIds:t.linkedValueIds,linkedSchemaIds:t.linkedSchemaIds,linkedModeIds:t.linkedModeIds,userId:t.userId??null}}const Sc={away:"Away moves",committed:"Committed actions",recovery:"Recovery moves"};function ij(){var Z,U,I,G,W,ne,de,we,Ne,H,me;const t=Je(),s=We(),[i,a]=Pt(),[n,r]=d.useState(!1),[l,o]=d.useState(null),[c,x]=d.useState(ha),[v,u]=d.useState(null),f=fe({queryKey:["forge-psyche-behaviors"],queryFn:xs}),h=fe({queryKey:["forge-psyche-patterns"],queryFn:Vs}),m=fe({queryKey:["forge-psyche-values"],queryFn:ps}),b=fe({queryKey:["forge-psyche-schema-catalog"],queryFn:La}),w=fe({queryKey:["forge-psyche-modes"],queryFn:Es}),M=((Z=f.data)==null?void 0:Z.behaviors)??[],E=((U=h.data)==null?void 0:U.patterns)??[],D=((I=m.data)==null?void 0:I.values)??[],j=((G=b.data)==null?void 0:G.schemas)??[],S=((W=w.data)==null?void 0:W.modes)??[],p=Mt(t.selectedUserIds),A=i.get("focus"),T=t.snapshot.dashboard.notesSummaryByEntity;ta(A),d.useEffect(()=>{if(i.get("create")==="1"){r(!0),o(null),x({...ha,userId:p});const y=new URLSearchParams(i);y.delete("create"),a(y,{replace:!0})}},[p,i,a]);const k=xe({mutationFn:async y=>{const P=jc.parse(y);return l?pg(l.id,P):Hn(P)},onSuccess:async()=>{r(!1),o(null),x({...ha,userId:p}),u(null),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-behaviors"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]})])}}),$=E.map(y=>({value:y.id,label:st(y.title,y.user),description:Ke(y.preferredResponse||y.targetBehavior,y.user),searchText:Be([y.title,y.preferredResponse,y.targetBehavior,y.description],y),kind:"pattern"})),g=D.map(y=>({value:y.id,label:st(y.title,y.user),description:Ke(y.valuedDirection,y.user),searchText:Be([y.title,y.valuedDirection,y.description],y),kind:"value"})),C=j.map(y=>({value:y.id,label:y.title,description:`${y.description} ${go(y.family)}`,searchText:`${y.slug} ${y.family} ${y.schemaType}`,badge:e.jsx(Ws,{label:y.title,schemaType:y.schemaType,compact:!0}),menuBadge:e.jsx(Ws,{label:y.title,schemaType:y.schemaType,compact:!0})})),F=S.map(y=>({value:y.id,label:st(y.title,y.user),description:Ke(y.archetype||y.family,y.user),searchText:Be([y.title,y.archetype,y.family,y.persona],y),kind:"mode"})),z=async y=>{const{pattern:P}=await zl({title:y,description:"",targetBehavior:y,cueContexts:[],shortTermPayoff:"",longTermCost:"",preferredResponse:"",linkedValueIds:[],linkedSchemaLabels:[],linkedModeIds:[],linkedBeliefIds:[],userId:c.userId});return At(s,["forge-psyche-patterns"],"patterns",P),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:P.id,label:P.title,description:P.preferredResponse||P.targetBehavior,kind:"pattern"}},J=async y=>{const{value:P}=await ea({title:y,description:"",valuedDirection:y,whyItMatters:"",linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],committedActions:[],userId:c.userId});return At(s,["forge-psyche-values"],"values",P),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:P.id,label:P.title,description:P.valuedDirection,kind:"value"}},O=async y=>{const{mode:P}=await Da({family:"coping",archetype:"",title:y,persona:"",imagery:"",symbolicForm:"",facialExpression:"",fear:"",burden:"",protectiveJob:"",originContext:"",firstAppearanceAt:null,linkedPatternIds:[],linkedBehaviorIds:[],linkedValueIds:[],userId:c.userId});return At(s,["forge-psyche-modes"],"modes",P),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:P.id,label:P.title,description:P.archetype||P.family,kind:"mode"}},_=[{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:(y,P)=>e.jsxs(e.Fragment,{children:[e.jsx(ss,{value:y.userId??null,users:t.snapshot.users,onChange:q=>P({userId:q}),defaultLabel:ts(t.snapshot.users.find(q=>q.id===p)??null,"Choose behavior owner"),help:"Behaviors can belong to a human or bot user while still linking across shared patterns, schemas, and modes."}),e.jsx(se,{label:"Behavior title",children:e.jsx(le,{value:y.title,onChange:q=>P({title:q.target.value}),placeholder:"Scroll to numb the impact"})}),e.jsx(se,{label:"What does the move look like?",children:e.jsx(Me,{value:y.description,onChange:q=>P({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:(y,P)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Common cues",children:e.jsx(Me,{value:y.commonCues.join(`
|
|
13
|
-
`),onChange:q=>P({commonCues:q.target.value.split(`
|
|
14
|
-
`).map(pe=>pe.trim()).filter(Boolean)}),placeholder:`One line per cue
|
|
15
|
-
Late-night ambiguity
|
|
16
|
-
Feedback after a hard week`})}),e.jsx(se,{label:"What inner push or story shows up?",children:e.jsx(Me,{value:y.urgeStory,onChange:q=>P({urgeStory:q.target.value}),placeholder:"What inner push or justification tends to appear?"})}),e.jsx(se,{label:"What do you get right away from this move?",children:e.jsx(Me,{value:y.shortTermPayoff,onChange:q=>P({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:(y,P)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{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 ${y.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:()=>P({kind:q}),children:Sc[q]},q))})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(se,{label:"What does it cost over time?",children:e.jsx(Me,{value:y.longTermCost,onChange:q=>P({longTermCost:q.target.value}),placeholder:"What does this move cost over time?"})}),e.jsx(se,{label:"What move should replace or steady it?",children:e.jsx(Me,{value:y.replacementMove,onChange:q=>P({replacementMove:q.target.value}),placeholder:"What move should replace this one when possible?"})})]}),e.jsx(se,{label:"If the slip happens, how do you repair and return?",children:e.jsx(Me,{value:y.repairPlan,onChange:q=>P({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:(y,P)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Linked patterns",children:e.jsx(et,{options:$,selectedValues:y.linkedPatternIds,onChange:q=>P({linkedPatternIds:q}),placeholder:"Search or create a pattern…",emptyMessage:"No patterns match yet.",createLabel:"Create pattern",onCreate:z})}),e.jsx(se,{label:"Linked values",children:e.jsx(et,{options:g,selectedValues:y.linkedValueIds,onChange:q=>P({linkedValueIds:q}),placeholder:"Search or create a value…",emptyMessage:"No values match yet.",createLabel:"Create value",onCreate:J})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(se,{label:"Linked schemas",children:e.jsx(et,{options:C,selectedValues:y.linkedSchemaIds,onChange:q=>P({linkedSchemaIds:q}),placeholder:"Search schema themes…",emptyMessage:"No schema themes match."})}),e.jsx(se,{label:"Linked modes",children:e.jsx(et,{options:F,selectedValues:y.linkedModeIds,onChange:q=>P({linkedModeIds:q}),placeholder:"Search or create a mode…",emptyMessage:"No modes match yet.",createLabel:"Create mode",onCreate:O})})]})]})}];if(f.isLoading||h.isLoading||m.isLoading||b.isLoading||w.isLoading)return e.jsx(nt,{eyebrow:"Behaviors",title:"Loading behaviors",description:"Getting behaviors, patterns, values, schemas, and modes ready."});const B=f.error??h.error??m.error??b.error??w.error;if(B)return e.jsx(ze,{eyebrow:"Psyche behaviors",error:B,onRetry:()=>void Promise.all([f.refetch(),h.refetch(),m.refetch(),b.refetch(),w.refetch()])});const K={away:M.filter(y=>y.kind==="away"),committed:M.filter(y=>y.kind==="committed"),recovery:M.filter(y=>y.kind==="recovery")};return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{entityKind:"behavior",title:e.jsx(Xe,{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:`${M.length} mapped`,actions:e.jsx(Q,{onClick:()=>{o(null),x({...ha,userId:p}),r(!0)},children:"Add behavior"})}),e.jsx(Bt,{}),e.jsx(Ps,{eyebrow:"Overview",title:"Behavior summary",description:"This summary keeps the three behavior types visible together: away, committed, and recovery.",tone:"amber",children:e.jsx(W0,{entries:[{id:"away",title:((ne=K.away[0])==null?void 0:ne.title)??"No away move mapped yet",summary:((de=K.away[0])==null?void 0:de.replacementMove)||"Map the move that tends to pull you away first.",href:"#behavior-columns",tone:"away"},{id:"committed",title:((we=K.committed[0])==null?void 0:we.title)??"No committed action mapped yet",summary:((Ne=K.committed[0])==null?void 0:Ne.replacementMove)||"Map the move you want to practice instead.",href:"#behavior-columns",tone:"committed"},{id:"recovery",title:((H=K.recovery[0])==null?void 0:H.title)??"No recovery move mapped yet",summary:((me=K.recovery[0])==null?void 0:me.repairPlan)||"Map how you return after a slip without turning it into collapse.",href:"#behavior-columns",tone:"recovery"}]})}),e.jsx(Ps,{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(y=>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:Sc[y]}),e.jsx(L,{children:K[y].length})]}),K[y].length===0?e.jsx("div",{className:"flex",children:e.jsxs(Q,{variant:"secondary",onClick:()=>{o(null),x({...ha,userId:p}),r(!0)},children:["Add ",y==="away"?"away move":y==="committed"?"committed action":"recovery move"]})}):K[y].map(P=>e.jsxs("div",{"data-psyche-focus-id":P.id,className:`rounded-[22px] border border-white/8 bg-white/[0.04] p-4 text-left transition hover:bg-white/[0.08] ${sa(A===P.id)}`,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"font-medium text-white",children:P.title}),P.user?e.jsx(Ue,{user:P.user,compact:!0}):null]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Vt,{entityType:"behavior",entityId:P.id,count:is(T,"behavior",P.id).count}),e.jsx(Q,{variant:"secondary",size:"sm",onClick:()=>{o(P),x(sj(P)),r(!0)},children:"Edit"})]})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:P.description}),e.jsx("div",{className:"mt-3 text-sm text-white/46",children:P.replacementMove||P.repairPlan||"No recovery step recorded yet."})]},P.id))]},y))})}),e.jsx(rt,{open:n,onOpenChange:r,eyebrow:"Behavior",title:l?"Refine behavior path":"Create behavior",description:"Use this guided flow to describe the behavior, when it shows up, what it gives you, and what kind of move it is.",value:c,onChange:x,steps:_,submitLabel:l?"Save behavior":"Create behavior",pending:k.isPending,error:v,onSubmit:async()=>{u(null);const y=jc.safeParse(c);if(!y.success){u("This behavior still needs a kind and a title before it can be saved.");return}try{await k.mutateAsync(y.data)}catch(P){u(P instanceof Error?P.message:"Unable to save this behavior right now.")}}})]})}function aj(){var c;const t=Je(),[s,i]=d.useState(null),a=fe({queryKey:["forge-psyche-overview"],queryFn:Wn}),n=(c=a.data)==null?void 0:c.overview,r=d.useMemo(()=>n?t.snapshot.goals.map(x=>{const v=n.values.filter(w=>w.linkedGoalIds.includes(x.id)),u=t.snapshot.dashboard.projects.filter(w=>w.goalId===x.id),f=t.snapshot.habits.filter(w=>w.linkedGoalIds.includes(x.id)||w.linkedValueIds.some(M=>v.some(E=>E.id===M))),h=n.reports.filter(w=>w.linkedGoalIds.includes(x.id)),m=n.behaviors.filter(w=>w.linkedValueIds.some(M=>v.some(E=>E.id===M))),b=n.beliefs.filter(w=>w.linkedValueIds.some(M=>v.some(E=>E.id===M)));return{goal:x,linkedValues:v,linkedProjects:u,linkedHabits:f,linkedReports:h,linkedBehaviors:m,linkedBeliefs:b}}):[],[n,t.snapshot.dashboard.projects,t.snapshot.goals,t.snapshot.habits]),l=d.useMemo(()=>Zm(r),[r]);if(d.useEffect(()=>{i(l.defaultSelectedId)},[l.defaultSelectedId]),a.isLoading)return e.jsx(nt,{eyebrow:"Goal map",title:"Loading the gravity well",description:"Linking goals, values, reports, beliefs, behaviors, and projects back into execution."});if(a.isError||!n)return e.jsx(ze,{eyebrow:"Goal map",error:a.error??new Error("Forge returned an empty Psyche overview payload."),onRetry:()=>void a.refetch()});const o=l.inspectors[s??l.defaultSelectedId]??l.inspectors[l.defaultSelectedId];return e.jsxs("div",{className:"grid min-w-0 gap-4",children:[e.jsx(qe,{title:"Goal Map",titleText:"Goal Map",description:"Values orbit each goal. Habits, reports, beliefs, behaviors, and projects reveal where the orbit gets disrupted and how execution reconnects.",badge:`${r.length} goal${r.length===1?"":"s"}`,actions:e.jsxs(e.Fragment,{children:[e.jsx(Ae,{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(Ae,{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(Bt,{}),e.jsxs("section",{className:"grid min-w-0 gap-4 xl:grid-cols-[minmax(0,1fr)_20rem]",children:[e.jsx(tu,{testId:"goal-gravity-graph",title:"Life direction, value orbit, and execution field",hint:"Drag to inspect the whole field. Select any goal, value, belief, behavior, project, or report to see what it means and where to act next.",nodes:l.nodes,edges:l.edges,fields:l.fields,selectedNodeId:s,onSelectNode:i,minHeightClassName:"min-h-[25rem] sm:min-h-[34rem] lg:min-h-[56rem]",legend:[{label:"Goals",kind:"goal"},{label:"Values",kind:"value"},{label:"Beliefs",kind:"belief"},{label:"Behaviors",kind:"behavior"},{label:"Habits",kind:"habit"},{label:"Projects",kind:"project"},{label:"Reports",kind:"report"}],action:r.length===0?e.jsx(Ae,{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(Ae,{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(ae,{className:"min-w-0 h-fit xl:sticky xl:top-24",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:o.entityKind?e.jsx(Te,{kind:o.entityKind,compact:!0,gradient:!1,iconOnly:!0}):e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:o.eyebrow})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[o.entityKind?e.jsx(Xe,{kind:o.entityKind,label:o.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:o.title}),o.entityKind?null:e.jsx(L,{className:"bg-white/[0.08]",style:{color:"white"},children:o.tone})]}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/60",children:o.summary}),o.stats.length>0?e.jsx("div",{className:"mt-4 grid gap-2",children:o.stats.map(x=>e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3 text-sm text-white/68",children:x},x))}):null,o.chips.length>0?e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:o.chips.map(x=>e.jsx(L,{className:"bg-white/[0.08] text-white/74",children:x},x))}):null,e.jsx("div",{className:"mt-5",children:e.jsx(Ae,{to:o.href,className:re("inline-flex min-h-11 w-full items-center justify-center rounded-[var(--radius-control)] px-4 py-2.5 text-sm font-medium whitespace-nowrap shadow-[0_12px_30px_rgba(192,193,255,0.08)]",o.entityKind?ja(o.entityKind,!0):"bg-[linear-gradient(135deg,rgba(192,193,255,0.36),rgba(192,193,255,0.22))] text-white"),children:o.ctaLabel})})]})]})]})}function nj(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 rj(t){const s=t.find(i=>i.isError);return{isLoading:t.some(i=>i.isPending||i.isLoading),error:s?nj(s.error):null}}async function lj(t){await Promise.all(t.map(s=>s.refetch()))}const tn={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 oj(){var o,c,x,v,u,f;const t=We(),s=fe({queryKey:["forge-psyche-mode-guide-sessions"],queryFn:fg}),i=vn({defaultValues:{summary:"What mode was most present in this moment?",copingResponse:"none",childState:"none",criticStyle:"none",healthyContact:"none"}}),a=xe({mutationFn:async h=>{const m=J0.parse({summary:h.summary,answers:[{questionKey:"coping_response",value:h.copingResponse},{questionKey:"child_state",value:h.childState},{questionKey:"critic_style",value:h.criticStyle},{questionKey:"healthy_contact",value:h.healthyContact}]});return bg(m)},onSuccess:async()=>{await t.invalidateQueries({queryKey:["forge-psyche-mode-guide-sessions"]})}}),n=[s],r=rj(n),l=((o=a.data)==null?void 0:o.session)??((x=(c=s.data)==null?void 0:c.sessions)==null?void 0:x[0]);return r.isLoading?e.jsx(nt,{eyebrow:"Mode guide",title:"Loading guided sessions",description:"Hydrating previous mode-guide runs and the latest stored readings."}):r.error?e.jsx(ze,{eyebrow:"Mode guide",error:r.error,onRetry:()=>void lj(n)}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{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:`${((v=s.data)==null?void 0:v.sessions.length)??0} sessions`,actions:e.jsx(Ae,{to:"/psyche/modes",children:e.jsx(Q,{variant:"secondary",children:"Back to mode map"})})}),e.jsx(Bt,{}),e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]",children:[e.jsxs(ae,{className:"bg-[linear-gradient(180deg,rgba(16,20,30,0.96),rgba(11,15,24,0.94))]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Guided questionnaire"}),e.jsxs("form",{className:"mt-4 grid gap-5",onSubmit:i.handleSubmit(async h=>a.mutateAsync(h)),children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Prompt"}),e.jsx("input",{className:"w-full rounded-2xl border border-white/8 bg-white/6 px-4 py-3 text-sm text-white outline-none placeholder:text-white/35",...i.register("summary")})]}),e.jsxs(ae,{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:tn.copingResponse.map(h=>e.jsxs("label",{className:"flex items-center gap-3 rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("input",{type:"radio",value:h.value,...i.register("copingResponse")}),e.jsx("span",{className:"text-white/74",children:h.label})]},h.value))})]}),e.jsxs(ae,{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:tn.childState.map(h=>e.jsxs("label",{className:"flex items-center gap-3 rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("input",{type:"radio",value:h.value,...i.register("childState")}),e.jsx("span",{className:"text-white/74",children:h.label})]},h.value))})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(ae,{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:tn.criticStyle.map(h=>e.jsxs("label",{className:"flex items-center gap-3 rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("input",{type:"radio",value:h.value,...i.register("criticStyle")}),e.jsx("span",{className:"text-white/74",children:h.label})]},h.value))})]}),e.jsxs(ae,{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:tn.healthyContact.map(h=>e.jsxs("label",{className:"flex items-center gap-3 rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("input",{type:"radio",value:h.value,...i.register("healthyContact")}),e.jsx("span",{className:"text-white/74",children:h.label})]},h.value))})]})]}),e.jsx(Q,{type:"submit",children:"Run guide"})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ae,{className:"bg-[linear-gradient(180deg,rgba(15,21,34,0.96),rgba(10,15,23,0.94))]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Latest reading"}),l?e.jsxs("div",{className:"mt-4 grid gap-3",children:[l.results.map(h=>e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:h.label}),e.jsxs(L,{className:"text-white/70",children:[Math.round(h.confidence*100),"%"]})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:h.family.replaceAll("_"," ")}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/66",children:h.reasoning})]},`${h.family}:${h.label}`)),e.jsx(Ae,{to:"/psyche/modes",children:e.jsx(Q,{variant:"secondary",children:"Use this in the mode map"})})]}):e.jsx("div",{className:"mt-4",children:e.jsx(gt,{eyebrow:"Guided reading",title:"No guided sessions yet",description:"Run the guide once to separate coping response, child state, critic pressure, and reachable healthy contact."})})]}),e.jsxs(ae,{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:(((u=s.data)==null?void 0:u.sessions)??[]).length===0?e.jsx(gt,{eyebrow:"Session history",title:"No stored guide history",description:"Completed guide sessions will accumulate here so later mode-map work can build from real prior readings."}):(((f=s.data)==null?void 0:f.sessions)??[]).map(h=>e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:h.summary}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:h.results.map(m=>e.jsx(L,{className:"text-white/72",children:m.label},`${h.id}:${m.label}`))})]},h.id))})]})]})]})]})}const dj={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 cj({family:t,label:s,className:i}){return e.jsx("span",{className:re("inline-flex items-center rounded-full px-3 py-1.5 text-xs",dj[t],i),children:s})}const ki={family:"coping",archetype:"",title:"",persona:"",imagery:"",symbolicForm:"",facialExpression:"",fear:"",burden:"",protectiveJob:"",originContext:"",firstAppearanceAt:null,linkedPatternIds:[],linkedBehaviorIds:[],linkedValueIds:[],userId:null};function hj(t){return{family:t.family,archetype:t.archetype,title:t.title,persona:t.persona,imagery:t.imagery,symbolicForm:t.symbolicForm,facialExpression:t.facialExpression,fear:t.fear,burden:t.burden,protectiveJob:t.protectiveJob,originContext:t.originContext,firstAppearanceAt:t.firstAppearanceAt,linkedPatternIds:t.linkedPatternIds,linkedBehaviorIds:t.linkedBehaviorIds,linkedValueIds:t.linkedValueIds,userId:t.userId??null}}const Lr={coping:"Coping",child:"Child",critic_parent:"Critic / parent",healthy_adult:"Healthy adult",happy_child:"Happy child"};function mj(){var _,B,K,Z;const t=Je(),s=We(),[i,a]=Pt(),[n,r]=d.useState(!1),[l,o]=d.useState(null),[c,x]=d.useState(ki),[v,u]=d.useState(null),f=fe({queryKey:["forge-psyche-modes"],queryFn:Es}),h=fe({queryKey:["forge-psyche-patterns"],queryFn:Vs}),m=fe({queryKey:["forge-psyche-behaviors"],queryFn:xs}),b=fe({queryKey:["forge-psyche-values"],queryFn:ps}),w=((_=f.data)==null?void 0:_.modes)??[],M=((B=h.data)==null?void 0:B.patterns)??[],E=((K=m.data)==null?void 0:K.behaviors)??[],D=((Z=b.data)==null?void 0:Z.values)??[],j=Mt(t.selectedUserIds),S=i.get("focus"),p=t.snapshot.dashboard.notesSummaryByEntity;ta(S),d.useEffect(()=>{if(i.get("create")==="1"){r(!0),o(null),x({...ki,userId:j});const U=new URLSearchParams(i);U.delete("create"),a(U,{replace:!0})}},[j,i,a]);const A=xe({mutationFn:async U=>{const I=kc.parse(U);return l?gg(l.id,I):Da(I)},onSuccess:async()=>{r(!1),o(null),x({...ki,userId:j}),u(null),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-modes"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]})])}}),T=M.map(U=>({value:U.id,label:st(U.title,U.user),description:Ke(U.preferredResponse||U.targetBehavior,U.user),searchText:Be([U.title,U.preferredResponse,U.targetBehavior,U.description],U),kind:"pattern"})),k=E.map(U=>({value:U.id,label:st(U.title,U.user),description:Ke(U.kind,U.user),searchText:Be([U.title,U.kind,U.description],U),kind:"behavior"})),$=D.map(U=>({value:U.id,label:st(U.title,U.user),description:Ke(U.valuedDirection,U.user),searchText:Be([U.title,U.valuedDirection,U.description],U),kind:"value"})),g=async U=>{const{pattern:I}=await zl({title:U,description:"",targetBehavior:U,cueContexts:[],shortTermPayoff:"",longTermCost:"",preferredResponse:"",linkedValueIds:[],linkedSchemaLabels:[],linkedModeIds:[],linkedBeliefIds:[],userId:c.userId});return At(s,["forge-psyche-patterns"],"patterns",I),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:I.id,label:I.title,description:I.preferredResponse||I.targetBehavior,kind:"pattern"}},C=async U=>{const{behavior:I}=await Hn({kind:"away",title:U,description:"",commonCues:[],urgeStory:"",shortTermPayoff:"",longTermCost:"",replacementMove:"",repairPlan:"",linkedPatternIds:[],linkedValueIds:[],linkedSchemaIds:[],linkedModeIds:[],userId:c.userId});return At(s,["forge-psyche-behaviors"],"behaviors",I),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:I.id,label:I.title,description:I.kind,kind:"behavior"}},F=async U=>{const{value:I}=await ea({title:U,description:"",valuedDirection:U,whyItMatters:"",linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],committedActions:[],userId:c.userId});return At(s,["forge-psyche-values"],"values",I),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:I.id,label:I.title,description:I.valuedDirection,kind:"value"}},z=[{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:(U,I)=>e.jsxs(e.Fragment,{children:[e.jsx(ss,{value:U.userId??null,users:t.snapshot.users,onChange:G=>I({userId:G}),defaultLabel:ts(t.snapshot.users.find(G=>G.id===j)??null,"Choose mode owner"),help:"Modes can belong to a human or bot user while still linking across shared patterns, behaviors, and values."}),e.jsx(se,{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(G=>e.jsx("button",{type:"button",className:`rounded-[22px] border px-4 py-4 text-left transition ${U.family===G?"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:()=>I({family:G}),children:Lr[G]},G))})}),e.jsx(se,{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(le,{value:U.title,onChange:G=>I({title:G.target.value}),placeholder:"The Friday Vigil, The Scanner, The Good Son"})}),e.jsx(se,{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(le,{value:U.archetype,onChange:G=>I({archetype:G.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:(U,I)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(se,{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(Me,{value:U.persona,onChange:G=>I({persona:G.target.value}),placeholder:"Quiet, hyper-alert, always scanning for threat and trying to stay one step ahead."})}),e.jsx(se,{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(Me,{value:U.imagery,onChange:G=>I({imagery:G.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(se,{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(le,{value:U.symbolicForm,onChange:G=>I({symbolicForm:G.target.value}),placeholder:"A locked visor, a fox, a steel shield"})}),e.jsx(se,{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(le,{value:U.facialExpression,onChange:G=>I({facialExpression:G.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:(U,I)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(se,{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(Me,{value:U.fear,onChange:G=>I({fear:G.target.value}),placeholder:"If I relax, I will miss the threat and get hurt."})}),e.jsx(se,{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(Me,{value:U.burden,onChange:G=>I({burden:G.target.value}),placeholder:"It believes it must never let the guard down, even when that means constant tension."})}),e.jsx(se,{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(Me,{value:U.protectiveJob,onChange:G=>I({protectiveJob:G.target.value}),placeholder:"Keeps me prepared so I never get blindsided or look naive."})})]}),e.jsx(se,{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(Me,{value:U.originContext,onChange:G=>I({originContext:G.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:(U,I)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Linked patterns",description:"Choose the loops this mode tends to activate or maintain.",children:e.jsx(et,{options:T,selectedValues:U.linkedPatternIds,onChange:G=>I({linkedPatternIds:G}),placeholder:"Search or create a pattern…",emptyMessage:"No patterns match yet.",createLabel:"Create pattern",onCreate:g})}),e.jsx(se,{label:"Linked behaviors",description:"Choose the moves this mode tends to trigger, justify, or amplify.",children:e.jsx(et,{options:k,selectedValues:U.linkedBehaviorIds,onChange:G=>I({linkedBehaviorIds:G}),placeholder:"Search or create a behavior…",emptyMessage:"No behaviors match yet.",createLabel:"Create behavior",onCreate:C})}),e.jsx(se,{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(et,{options:$,selectedValues:U.linkedValueIds,onChange:G=>I({linkedValueIds:G}),placeholder:"Search or create a value…",emptyMessage:"No values match yet.",createLabel:"Create value",onCreate:F})})]})}];if(f.isLoading||h.isLoading||m.isLoading||b.isLoading)return e.jsx(nt,{eyebrow:"Modes",title:"Loading modes",description:"Getting modes, linked patterns, behaviors, and values ready."});const J=f.error??h.error??m.error??b.error;if(J)return e.jsx(ze,{eyebrow:"Modes",error:J,onRetry:()=>void Promise.all([f.refetch(),h.refetch(),m.refetch(),b.refetch()])});const O={coping:w.filter(U=>U.family==="coping"),child:w.filter(U=>U.family==="child"),critic_parent:w.filter(U=>U.family==="critic_parent"),healthy_adult:w.filter(U=>U.family==="healthy_adult"),happy_child:w.filter(U=>U.family==="happy_child")};return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{entityKind:"mode",title:e.jsx(Xe,{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:`${w.length} modes`,actions:e.jsx(Q,{onClick:()=>{o(null),x({...ki,userId:j}),r(!0)},children:"Add mode"})}),e.jsx(Bt,{}),e.jsx(Ps,{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:w.length===0?e.jsx("div",{className:"flex justify-start",children:e.jsx(Q,{onClick:()=>{o(null),x({...ki,userId:j}),r(!0)},children:"Add mode"})}):e.jsx("div",{className:"grid gap-4 xl:grid-cols-2",children:Object.keys(O).map(U=>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(cj,{family:U,label:Lr[U]}),e.jsx(L,{children:O[U].length})]}),O[U].length===0?e.jsx("div",{className:"flex",children:e.jsxs(Q,{variant:"secondary",onClick:()=>{o(null),x({...ki,userId:j}),r(!0)},children:["Add ",Lr[U].toLowerCase()]})}):O[U].map(I=>e.jsxs("div",{"data-psyche-focus-id":I.id,className:`rounded-[22px] bg-white/[0.04] p-4 text-left transition hover:bg-white/[0.08] ${sa(S===I.id)}`,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(Te,{kind:"mode",compact:!0,gradient:!1}),e.jsx(Xe,{kind:"mode",label:I.title,variant:"heading",size:"lg"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Vt,{entityType:"mode_profile",entityId:I.id,count:is(p,"mode_profile",I.id).count}),e.jsx(Q,{variant:"secondary",size:"sm",onClick:()=>{o(I),x(hj(I)),r(!0)},children:"Edit"})]})]}),e.jsx("div",{className:"mt-2 text-sm text-white/52",children:I.archetype}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/62",children:I.persona||I.protectiveJob||"Open the mode to add persona and protective details."})]},I.id))]},U))})}),e.jsx(rt,{open:n,onOpenChange:r,eyebrow:"Mode",title:l?"Refine cast member":"Create mode",description:"Use this guided flow to define the mode, how it shows up, what it is protecting, and where it comes from.",value:c,onChange:x,steps:z,submitLabel:l?"Save mode":"Create mode",pending:A.isPending,error:v,onSubmit:async()=>{u(null);const U=kc.safeParse(c);if(!U.success){u("This mode still needs a family and a name before it can be saved.");return}try{await A.mutateAsync(U.data)}catch(I){u(I instanceof Error?I.message:"Unable to save this mode right now.")}}})]})}const uj={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 Dr(t,s,i){return Math.min(Math.max(t,s),i)}function pj(t){const s=t.detail.trim().length;return s>84?130:s>44?118:106}function xj(t,s,i){const a=s/2,n=i/2,r=Dr(Math.min(s/620,i/430),.64,1.06),l=t.map(f=>{const h=f.angle*Math.PI/180,m=f.radius*r,b=Math.min(184,Math.max(154,s-48)),w=pj(f),M=a+Math.cos(h)*m,E=n+Math.sin(h)*m;return{...f,x:M,y:E,width:b,height:w,homeX:M,homeY:E}}),o=s<720?16:22,c=20,x=s-20,v=18,u=i-18;for(let f=0;f<220;f+=1){for(const h of l)h.x+=(h.homeX-h.x)*.065,h.y+=(h.homeY-h.y)*.065;for(let h=0;h<l.length;h+=1)for(let m=h+1;m<l.length;m+=1){const b=l[h],w=l[m],M=w.x-b.x,E=w.y-b.y,D=b.width/2+w.width/2+o-Math.abs(M),j=b.height/2+w.height/2+o-Math.abs(E);if(D<=0||j<=0)continue;const S=D<j?"x":"y",p=Math.sign(S==="x"?M||m-h||1:E||m-h||1),A=(S==="x"?D:j)/2;S==="x"?(b.x-=p*A,w.x+=p*A):(b.y-=p*A,w.y+=p*A)}for(const h of l)h.x=Dr(h.x,c+h.width/2,x-h.width/2),h.y=Dr(h.y,v+h.height/2,u-h.height/2)}return l}function au({title:t,description:s,centerLabel:i,centerValue:a,nodes:n,action:r}){const l=d.useRef(null),[o,c]=d.useState({width:0,height:0});d.useEffect(()=>{if(!l.current||typeof ResizeObserver>"u")return;const u=new ResizeObserver(f=>{const h=f[0];c({width:h.contentRect.width,height:h.contentRect.height})});return u.observe(l.current),()=>u.disconnect()},[]);const x=n.length>0?n:[{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"}],v=d.useMemo(()=>xj(x,Math.max(o.width,320),Math.max(o.height,320)),[x,o.height,o.width]);return e.jsxs("section",{className:"overflow-hidden rounded-[32px] border border-white/8 bg-[radial-gradient(circle_at_top,rgba(110,231,183,0.14),transparent_42%),linear-gradient(180deg,rgba(15,30,34,0.98),rgba(10,21,25,0.98))] px-4 py-4 shadow-[0_24px_70px_rgba(4,8,18,0.28)] lg:px-5",children:[e.jsxs("div",{className:"mb-4 flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-[rgba(110,231,183,0.8)]",children:"Reflective map"}),e.jsx("h2",{className:"mt-2 font-display text-[clamp(1.35rem,2.3vw,2rem)] leading-none text-white",children:t}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-white/60",children:s})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"inline-flex items-center gap-3 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2",children:[e.jsx("span",{className:"text-xs uppercase tracking-[0.18em] text-white/38",children:i}),e.jsx("span",{className:"text-sm font-medium text-white",children:a})]}),r?e.jsx("div",{className:"shrink-0",children:r}):null]})]}),e.jsxs("div",{ref:l,className:"relative min-h-[20rem] overflow-hidden rounded-[30px] border border-white/6 bg-[radial-gradient(circle_at_center,rgba(255,255,255,0.05),transparent_42%)] lg:min-h-[22rem]",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_center,rgba(110,231,183,0.08),transparent_32%),linear-gradient(180deg,transparent,rgba(8,13,24,0.24))]"}),[112,168,224].map(u=>e.jsx("div",{className:"absolute left-1/2 top-1/2 rounded-full border border-white/[0.05]",style:{width:`${u*2}px`,height:`${u*2}px`,transform:"translate(-50%, -50%)"}},u)),e.jsx("div",{className:"absolute inset-1/2 size-32 -translate-x-1/2 -translate-y-1/2 rounded-full border border-white/10 bg-[radial-gradient(circle,rgba(255,255,255,0.08),rgba(255,255,255,0.02))] shadow-[0_0_0_18px_rgba(255,255,255,0.02),0_0_0_56px_rgba(255,255,255,0.015)]",children:e.jsxs("div",{className:"flex h-full flex-col items-center justify-center text-center",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:i}),e.jsx("div",{className:"mt-2 font-display text-2xl text-white",children:a})]})}),v.map((u,f)=>e.jsx(Kt.div,{initial:{opacity:0,scale:.96},animate:{opacity:1,scale:1},transition:{duration:.35,delay:f*.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:`${u.x}px`,top:`${u.y}px`},whileHover:{y:-6,scale:1.03},children:e.jsxs(Ae,{to:u.href,className:re("block rounded-[22px] border px-3.5 py-3 shadow-[0_18px_38px_rgba(4,8,18,0.28)] backdrop-blur-sm transition hover:-translate-y-0.5 hover:bg-white/[0.1] hover:shadow-[0_24px_44px_rgba(4,8,18,0.34)]",uj[u.tone??"mint"]),children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/45",children:u.label}),e.jsx("div",{className:"mt-1.5 font-medium text-white",children:u.title}),e.jsx("div",{className:"mt-1.5 text-sm leading-5 text-white/62",children:u.detail})]})},u.id))]})]})}const Si={title:"",description:"",targetBehavior:"",cueContexts:[],shortTermPayoff:"",longTermCost:"",preferredResponse:"",linkedValueIds:[],linkedSchemaLabels:[],linkedModeIds:[],linkedBeliefIds:[],userId:null};function gj(t){return{title:t.title,description:t.description,targetBehavior:t.targetBehavior,cueContexts:t.cueContexts,shortTermPayoff:t.shortTermPayoff,longTermCost:t.longTermCost,preferredResponse:t.preferredResponse,linkedValueIds:t.linkedValueIds,linkedSchemaLabels:t.linkedSchemaLabels,linkedModeIds:t.linkedModeIds,linkedBeliefIds:t.linkedBeliefIds,userId:t.userId??null}}function fj(t){const s=new Set;return t.filter(i=>{const a=`${i.entityType}:${i.entityId}:${i.anchorKey??""}`;return s.has(a)?!1:(s.add(a),!0)})}function bj(t){const s=t.replace(/\s+/g," ").trim();return s.length<=180?s:`${s.slice(0,177).trimEnd()}...`}function vj(){var de,we,Ne,H,me,y;const t=Je(),s=We(),[i,a]=Pt(),[n,r]=d.useState(!1),[l,o]=d.useState(null),[c,x]=d.useState(null),[v,u]=d.useState(Si),[f,h]=d.useState(null),m=fe({queryKey:["forge-psyche-patterns"],queryFn:Vs}),b=fe({queryKey:["forge-psyche-values"],queryFn:ps}),w=fe({queryKey:["forge-psyche-schema-catalog"],queryFn:La}),M=fe({queryKey:["forge-psyche-modes"],queryFn:Es}),E=fe({queryKey:["forge-psyche-beliefs"],queryFn:As}),D=fe({queryKey:["forge-psyche-behaviors"],queryFn:xs}),j=((de=m.data)==null?void 0:de.patterns)??[],S=((we=b.data)==null?void 0:we.values)??[],p=((Ne=w.data)==null?void 0:Ne.schemas)??[],A=((H=M.data)==null?void 0:H.modes)??[],T=((me=E.data)==null?void 0:me.beliefs)??[],k=((y=D.data)==null?void 0:y.behaviors)??[],$=Mt(t.selectedUserIds),g=i.get("focus"),C=t.snapshot.dashboard.notesSummaryByEntity,F=fe({enabled:c!==null,queryKey:["forge-note",c],queryFn:()=>Zo(c)});ta(g),d.useEffect(()=>{if(i.get("create")==="1"){r(!0),o(null),u({...Si,userId:i.get("userId")??$}),x(i.get("sourceObservationNoteId"));const P=new URLSearchParams(i);P.delete("create"),P.delete("sourceObservationNoteId"),P.delete("userId"),a(P,{replace:!0})}},[$,i,a]);const z=xe({mutationFn:async P=>{var ee,Y;const q=yc.parse(P);if(l)return ug(l.id,q);const pe=await zl(q);if(c){const R=((Y=(ee=F.data)==null?void 0:ee.note)==null?void 0:Y.id)===c?F.data.note:(await Zo(c)).note;await Ta(c,{links:fj([...R.links,{entityType:"behavior_pattern",entityId:pe.pattern.id,anchorKey:null}])})}return pe},onSuccess:async()=>{r(!1),o(null),x(null),u({...Si,userId:$}),h(null),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-patterns"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]}),s.invalidateQueries({queryKey:["forge-psyche-self-observation-calendar"]}),s.invalidateQueries({queryKey:["forge-snapshot"]}),s.invalidateQueries({queryKey:["notes-index"]})])}}),J=S.map(P=>({value:P.id,label:st(P.title,P.user),description:Ke(P.valuedDirection,P.user),searchText:Be([P.title,P.valuedDirection,P.description],P),kind:"value"})),O=p.map(P=>({value:P.title,label:P.title,description:`${P.description} ${go(P.family)}`,searchText:`${P.slug} ${P.family} ${P.schemaType}`,badge:e.jsx(Ws,{label:P.title,schemaType:P.schemaType,compact:!0}),menuBadge:e.jsx(Ws,{label:P.title,schemaType:P.schemaType,compact:!0})})),_=A.map(P=>({value:P.id,label:st(P.title,P.user),description:Ke(P.archetype||P.family,P.user),searchText:Be([P.title,P.archetype,P.family,P.persona],P),kind:"mode"})),B=T.map(P=>({value:P.id,label:st(P.statement,P.user),description:Ke(P.flexibleAlternative||P.originNote,P.user),searchText:Be([P.statement,P.flexibleAlternative,P.originNote,P.beliefType],P),kind:"belief"})),K=async P=>{const{mode:q}=await Da({family:"coping",archetype:"",title:P,persona:"",imagery:"",symbolicForm:"",facialExpression:"",fear:"",burden:"",protectiveJob:"",originContext:"",firstAppearanceAt:null,linkedPatternIds:[],linkedBehaviorIds:[],linkedValueIds:[],userId:v.userId});return At(s,["forge-psyche-modes"],"modes",q),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:q.id,label:q.title,description:q.archetype||q.family,kind:"mode"}},Z=async P=>{const{value:q}=await ea({title:P,description:"",valuedDirection:P,whyItMatters:"",linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],committedActions:[],userId:v.userId});return At(s,["forge-psyche-values"],"values",q),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:q.id,label:q.title,description:q.valuedDirection,kind:"value"}},U=async P=>{const{belief:q}=await ql({schemaId:null,statement:P,beliefType:"absolute",originNote:"",confidence:60,evidenceFor:[],evidenceAgainst:[],flexibleAlternative:"",linkedValueIds:[],linkedBehaviorIds:[],linkedModeIds:[],linkedReportIds:[],userId:v.userId});return At(s,["forge-psyche-beliefs"],"beliefs",q),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:q.id,label:q.statement,description:q.flexibleAlternative||q.originNote,kind:"belief"}},I=d.useMemo(()=>j.filter(P=>!k.some(q=>q.kind==="away"&&q.linkedPatternIds.includes(P.id))),[j,k]),G=j.slice(0,5).map((P,q)=>({id:P.id,label:`${P.linkedValueIds.length} values`,title:P.title,detail:P.preferredResponse,href:`/psyche/patterns?focus=${P.id}#pattern-lanes`,angle:-92+q*70,radius:150+q%2*14,tone:["rose","sky","violet","mint"][q%4]})),W=[{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:(P,q)=>{var pe;return e.jsxs(e.Fragment,{children:[c?e.jsxs("div",{className:"rounded-[22px] border border-[rgba(110,231,183,0.18)] bg-[rgba(110,231,183,0.08)] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-[rgba(110,231,183,0.82)]",children:"Source observation"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/78",children:F.isLoading?"Loading the saved observation note...":(pe=F.data)!=null&&pe.note?bj(F.data.note.contentPlain||F.data.note.contentMarkdown):"Forge will link this pattern back to the saved observation when you submit it."})]}):null,e.jsx(ss,{value:P.userId??null,users:t.snapshot.users,onChange:ee=>q({userId:ee}),defaultLabel:ts(t.snapshot.users.find(ee=>ee.id===$)??null,"Choose pattern owner"),help:"Patterns can belong to a human or bot user even when linked values, modes, or beliefs cross owners."}),e.jsx(se,{label:"Pattern name",description:"Give the loop a name you will recognize quickly later.",children:e.jsx(le,{value:P.title,onChange:ee=>q({title:ee.target.value}),placeholder:"Anxious reassurance loop"})}),e.jsx(se,{label:"What happens in the loop",description:"Describe the actual sequence of behavior, not the diagnosis.",children:e.jsx(Me,{value:P.targetBehavior,onChange:ee=>q({targetBehavior:ee.target.value}),placeholder:"What do you actually do when the trigger hits?"})}),e.jsx(se,{label:"Description",description:"Write the loop in plain language so it stays usable in the future.",children:e.jsx(Me,{value:P.description,onChange:ee=>q({description:ee.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:(P,q)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Common cues",description:"Add one cue per line so the trigger pattern stays easy to scan.",children:e.jsx(Me,{value:P.cueContexts.join(`
|
|
17
|
-
`),onChange:pe=>q({cueContexts:pe.target.value.split(`
|
|
18
|
-
`).map(ee=>ee.trim()).filter(Boolean)}),placeholder:`One line per cue
|
|
19
|
-
Silence after vulnerability
|
|
20
|
-
Late-night social comparison`})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(se,{label:"Short-term payoff",description:"What relief, certainty, control, or distance do you get right away?",children:e.jsx(Me,{value:P.shortTermPayoff,onChange:pe=>q({shortTermPayoff:pe.target.value}),placeholder:"What relief do you get right away?"})}),e.jsx(se,{label:"Long-term cost",description:"What does the loop cost you later in closeness, energy, values, or progress?",children:e.jsx(Me,{value:P.longTermCost,onChange:pe=>q({longTermCost:pe.target.value}),placeholder:"What does this cost over time?"})})]}),e.jsx(se,{label:"Preferred response",description:"Name the return-path response you want to practice instead.",children:e.jsx(Me,{value:P.preferredResponse,onChange:pe=>q({preferredResponse:pe.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:(P,q)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Linked values",description:"Choose the values this loop pulls against or tries to protect badly.",children:e.jsx(et,{options:J,selectedValues:P.linkedValueIds,onChange:pe=>q({linkedValueIds:pe}),placeholder:"Search or create a value…",emptyMessage:"No values match yet.",createLabel:"Create value",onCreate:Z})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(se,{label:"Schema labels",description:"Attach the schema themes that define the pressure in this loop.",children:e.jsx(et,{options:O,selectedValues:P.linkedSchemaLabels,onChange:pe=>q({linkedSchemaLabels:pe}),placeholder:"Search schema themes…",emptyMessage:"No schema themes match."})}),e.jsx(se,{label:"Linked modes",description:"Search for an existing mode or press Enter to create and link one immediately.",children:e.jsx(et,{options:_,selectedValues:P.linkedModeIds,onChange:pe=>q({linkedModeIds:pe}),placeholder:"Search or create a mode…",emptyMessage:"No modes match yet.",createLabel:"Create mode",onCreate:K})})]}),e.jsx(se,{label:"Linked beliefs",description:"Search for a belief, or type a new one and press Enter to create it inline.",children:e.jsx(et,{options:B,selectedValues:P.linkedBeliefIds,onChange:pe=>q({linkedBeliefIds:pe}),placeholder:"Search or create a belief…",emptyMessage:"No beliefs match yet.",createLabel:"Create belief",onCreate:U})})]})}];if(m.isLoading||b.isLoading||w.isLoading||M.isLoading||E.isLoading||D.isLoading)return e.jsx(nt,{eyebrow:"Patterns",title:"Loading patterns",description:"Getting patterns, values, schemas, beliefs, modes, and linked behaviors ready."});const ne=m.error??b.error??w.error??M.error??E.error??D.error;return ne?e.jsx(ze,{eyebrow:"Psyche patterns",error:ne,onRetry:()=>void Promise.all([m.refetch(),b.refetch(),w.refetch(),M.refetch(),E.refetch(),D.refetch()])}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{entityKind:"pattern",title:e.jsx(Xe,{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:`${j.length} patterns`,actions:e.jsx(Q,{onClick:()=>{o(null),x(null),u({...Si,userId:$}),r(!0)},children:"Add pattern"})}),e.jsx(Bt,{}),e.jsx(au,{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:`${j.length} tracked`,nodes:G,action:e.jsx(Q,{onClick:()=>{o(null),x(null),u({...Si,userId:$}),r(!0)},children:"Add pattern"})}),I.length>0?e.jsx(Ps,{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:I.slice(0,8).map(P=>e.jsx(Te,{kind:"pattern",label:P.title,compact:!0},P.id))})}):null,e.jsx(Ps,{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:j.length===0?e.jsx("div",{className:"flex justify-start",children:e.jsx(Q,{onClick:()=>{o(null),u({...Si,userId:$}),r(!0)},children:"Add pattern"})}):j.map(P=>{const q=S.filter(X=>P.linkedValueIds.includes(X.id)),pe=A.filter(X=>P.linkedModeIds.includes(X.id)),ee=T.filter(X=>P.linkedBeliefIds.includes(X.id)),Y=g===P.id,R=is(C,"behavior_pattern",P.id).count;return e.jsxs("div",{"data-psyche-focus-id":P.id,className:`rounded-[28px] border border-white/8 bg-white/[0.04] p-5 transition ${sa(Y)}`,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(Xe,{kind:"pattern",label:P.title,variant:"heading",size:"xl"}),e.jsx("div",{className:"mt-2 text-sm leading-7 text-white/58",children:P.description})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[P.user?e.jsx(Ue,{user:P.user,compact:!0}):null,e.jsx(Vt,{entityType:"behavior_pattern",entityId:P.id,count:R}),e.jsx(Q,{variant:"secondary",onClick:()=>{o(P),x(null),u(gj(P)),r(!0)},children:"Edit"})]})]}),e.jsxs("div",{className:"mt-5 grid gap-3 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Cue"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/68",children:P.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:P.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:P.shortTermPayoff||"No payoff note yet."}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/52",children:P.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:P.preferredResponse})]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[q.map(X=>e.jsx(Te,{kind:"value",label:X.title,compact:!0},X.id)),pe.map(X=>e.jsx(Te,{kind:"mode",label:X.title,compact:!0},X.id)),P.linkedModeLabels.map(X=>e.jsx(L,{className:"text-violet-100",children:X},`legacy-${X}`)),P.linkedSchemaLabels.map(X=>{var be,Ie;return e.jsx(Ws,{label:((be=Xi(X,p))==null?void 0:be.title)??X,schemaType:((Ie=Xi(X,p))==null?void 0:Ie.schemaType)??"maladaptive",compact:!0},X)}),ee.map(X=>e.jsx(Te,{kind:"belief",label:X.statement,compact:!0},X.id))]})]},P.id)})})}),e.jsx(rt,{open:n,onOpenChange:P=>{r(P),!P&&!l&&x(null)},eyebrow:"Behavior pattern",title:l?"Refine pattern lane":"Create pattern",description:c&&!l?"This pattern is being created from a saved observation. Submitting the dialog will link the new pattern back to that observation note.":"Pattern capture should feel like mapping a loop, not filling an admin form.",value:v,onChange:u,steps:W,submitLabel:l?"Save pattern":"Create pattern",pending:z.isPending,error:f,onSubmit:async()=>{h(null);const P=yc.safeParse(v);if(!P.success){h("This pattern still needs a title, a loop description, and a preferred response.");return}try{await z.mutateAsync(P.data)}catch(q){h(q instanceof Error?q.message:"Unable to save this pattern right now.")}}})]})}const wj={locale:"en",instructions:"Add questionnaire instructions here.",completionNote:"",presentationMode:"single_question",responseStyle:"four_point_frequency",itemIds:["item_1"],items:[{id:"item_1",prompt:"Sample question",shortLabel:"",description:"",helperText:"",required:!0,visibility:null,tags:[],options:[{key:"0",label:"Not at all",value:0,description:""},{key:"1",label:"Several days",value:1,description:""},{key:"2",label:"More than half the days",value:2,description:""},{key:"3",label:"Nearly every day",value:3,description:""}]}],sections:[{id:"section_1",title:"Section 1",description:"",visibility:null,itemIds:["item_1"]}],pageSize:null},yj={scores:[{key:"total",label:"Total score",description:"",valueType:"number",expression:{kind:"sum",itemIds:["item_1"]},dependsOnItemIds:["item_1"],missingPolicy:{mode:"require_all"},bands:[],roundTo:null,unitLabel:""}]},jj={retrievalDate:"2026-04-06",sourceClass:"secondary_verified",scoringNotes:"Describe the scoring method and provenance here.",sources:[{label:"Primary source",url:"https://example.com",citation:"Replace with a real citation.",notes:""}]};function sn(t){const s=(t==null?void 0:t.draftVersion)??(t==null?void 0:t.currentVersion);return{title:(t==null?void 0:t.title)??"",subtitle:(t==null?void 0:t.subtitle)??"",description:(t==null?void 0:t.description)??"",aliases:(t==null?void 0:t.aliases.join(", "))??"",symptomDomains:(t==null?void 0:t.symptomDomains.join(", "))??"",tags:(t==null?void 0:t.tags.join(", "))??"",sourceClass:(t==null?void 0:t.sourceClass)??"secondary_verified",availability:(t==null?void 0:t.availability)??"custom",isSelfReport:(t==null?void 0:t.isSelfReport)??!0,label:(s==null?void 0:s.label)??"Draft 1",definitionJson:JSON.stringify((s==null?void 0:s.definition)??wj,null,2),scoringJson:JSON.stringify((s==null?void 0:s.scoring)??yj,null,2),provenanceJson:JSON.stringify((s==null?void 0:s.provenance)??jj,null,2)}}function $r(t){return t.split(",").map(s=>s.trim()).filter(Boolean)}function Cc(t){return{title:t.title.trim(),subtitle:t.subtitle.trim(),description:t.description.trim(),aliases:$r(t.aliases),symptomDomains:$r(t.symptomDomains),tags:$r(t.tags),sourceClass:t.sourceClass,availability:t.availability,isSelfReport:t.isSelfReport,versionLabel:t.label.trim()||"Draft 1",definition:JSON.parse(t.definitionJson),scoring:JSON.parse(t.scoringJson),provenance:JSON.parse(t.provenanceJson),userId:"user_operator"}}const Nj=[{id:"metadata",label:"Metadata",icon:Tl},{id:"structure",label:"Structure",icon:Lp},{id:"scoring",label:"Scoring",icon:Dp},{id:"publish",label:"Publish",icon:$p}];function Ic(){var E,D;const{instrumentId:t}=es(),s=ut(),[i,a]=d.useState("metadata"),[n,r]=d.useState(()=>sn(null)),[l,o]=d.useState(null),c=fe({queryKey:["forge-psyche-questionnaire-builder",t],queryFn:()=>Eh(t),enabled:!!t}),x=xe({mutationFn:async()=>{var S;if(!t)throw new Error("Missing questionnaire id");const j=(S=c.data)==null?void 0:S.instrument;return j!=null&&j.isSystem?ag(t,{userId:"user_operator"}):ng(t)},onSuccess:j=>{r(sn(j.instrument)),j.instrument.id!==t&&s(`/psyche/questionnaires/${j.instrument.id}/edit`,{replace:!0})}}),v=xe({mutationFn:async()=>ig(Cc(n)),onSuccess:j=>{s(`/psyche/questionnaires/${j.instrument.id}/edit`,{replace:!0})}}),u=xe({mutationFn:async()=>{if(!t)throw new Error("Missing questionnaire id");const j=Cc(n);return rg(t,{...j,label:j.versionLabel})}}),f=xe({mutationFn:async()=>{if(!t)throw new Error("Missing questionnaire id");return lg(t,{label:n.label})},onSuccess:j=>{s(`/psyche/questionnaires/${j.instrument.id}`)}});d.useEffect(()=>{var S;if(!t){r(sn(null));return}const j=(S=c.data)==null?void 0:S.instrument;if(j){if(!j.draftVersion&&!x.isPending){x.mutate();return}r(sn(j))}},[(E=c.data)==null?void 0:E.instrument,t,x]);const h=t?"Edit questionnaire":"Build questionnaire",m=((D=c.data)==null?void 0:D.instrument)??null,b=c.isLoading||x.isPending||v.isPending||u.isPending||f.isPending,w=d.useMemo(()=>{try{return{definition:JSON.parse(n.definitionJson),scoring:JSON.parse(n.scoringJson)}}catch{return null}},[n.definitionJson,n.scoringJson]);if(t&&c.isLoading&&!m)return e.jsx(nt,{eyebrow:"Questionnaire builder",title:"Loading editable draft",description:"Preparing the current questionnaire draft so the builder can open on real versioned data."});if(c.isError)return e.jsx(ze,{eyebrow:"Questionnaire builder",error:c.error,onRetry:()=>void c.refetch()});const M=async()=>{try{o(null),t?await u.mutateAsync():await v.mutateAsync()}catch(j){o(j instanceof Error?j.message:"Unable to save questionnaire draft.")}};return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{eyebrow:"Psyche",title:h,description:"Edit versioned questionnaire metadata, structure, scoring, and publication state directly in the app. Seeded instruments branch into editable drafts before any change is made.",badge:t?(m==null?void 0:m.title)??"Draft":"New draft",actions:t?e.jsx(Ae,{to:`/psyche/questionnaires/${t}`,children:e.jsx(Q,{variant:"secondary",children:"Back to detail"})}):null}),e.jsx(Bt,{}),e.jsx(ae,{className:"bg-[linear-gradient(180deg,rgba(15,23,34,0.98),rgba(8,13,20,0.98))]",children:e.jsx("div",{className:"grid gap-3 md:grid-cols-4",children:Nj.map(j=>e.jsxs("button",{type:"button",className:re("rounded-[22px] border px-4 py-4 text-left transition",i===j.id?"border-[rgba(110,231,183,0.24)] bg-[rgba(110,231,183,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/64 hover:bg-white/[0.05]"),onClick:()=>a(j.id),children:[e.jsx(j.icon,{className:"size-4"}),e.jsx("div",{className:"mt-3 text-sm font-medium",children:j.label})]},j.id))})}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.1fr)_minmax(18rem,0.9fr)]",children:[e.jsxs(ae,{className:"bg-[linear-gradient(180deg,rgba(16,24,34,0.98),rgba(10,15,24,0.96))]",children:[i==="metadata"?e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/72",children:"Title"}),e.jsx("input",{value:n.title,onChange:j=>r(S=>({...S,title:j.target.value})),className:"rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 text-sm text-white outline-none"})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/72",children:"Subtitle"}),e.jsx("input",{value:n.subtitle,onChange:j=>r(S=>({...S,subtitle:j.target.value})),className:"rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 text-sm text-white outline-none"})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/72",children:"Description"}),e.jsx("textarea",{value:n.description,onChange:j=>r(S=>({...S,description:j.target.value})),className:"min-h-28 rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 text-sm text-white outline-none"})]}),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/72",children:"Aliases"}),e.jsx("input",{value:n.aliases,onChange:j=>r(S=>({...S,aliases:j.target.value})),className:"rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 text-sm text-white outline-none"})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/72",children:"Symptom domains"}),e.jsx("input",{value:n.symptomDomains,onChange:j=>r(S=>({...S,symptomDomains:j.target.value})),className:"rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 text-sm text-white outline-none"})]})]}),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/72",children:"Tags"}),e.jsx("input",{value:n.tags,onChange:j=>r(S=>({...S,tags:j.target.value})),className:"rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 text-sm text-white outline-none"})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/72",children:"Source class"}),e.jsx("select",{value:n.sourceClass,onChange:j=>r(S=>({...S,sourceClass:j.target.value})),className:"rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 text-sm text-white outline-none",children:["public_domain","free_use","open_access","open_noncommercial","free_clinician","secondary_verified"].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/72",children:"Availability"}),e.jsx("select",{value:n.availability,onChange:j=>r(S=>({...S,availability:j.target.value})),className:"rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 text-sm text-white outline-none",children:["open","free_clinician","custom"].map(j=>e.jsx("option",{value:j,children:j.replaceAll("_"," ")},j))})]})]})]}):null,i==="structure"?e.jsxs("div",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/72",children:"Definition JSON"}),e.jsxs("div",{className:"text-sm leading-6 text-white/56",children:["Items and sections can declare",e.jsx("code",{className:"mx-1 rounded bg-white/[0.06] px-1.5 py-0.5 text-xs text-white",children:"visibility.script"}),"rules such as",e.jsx("code",{className:"mx-1 rounded bg-white/[0.06] px-1.5 py-0.5 text-xs text-white",children:"audit_1 > 0"}),"or",e.jsx("code",{className:"mx-1 rounded bg-white/[0.06] px-1.5 py-0.5 text-xs text-white",children:'answered(question_12) and option(question_12) == "yes"'}),"."]}),e.jsx("textarea",{value:n.definitionJson,onChange:j=>r(S=>({...S,definitionJson:j.target.value})),className:"min-h-[32rem] rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 font-mono text-sm text-white outline-none"})]}):null,i==="scoring"?e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/72",children:"Scoring JSON"}),e.jsx("textarea",{value:n.scoringJson,onChange:j=>r(S=>({...S,scoringJson:j.target.value})),className:"min-h-[24rem] rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 font-mono text-sm text-white outline-none"})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/72",children:"Provenance JSON"}),e.jsx("textarea",{value:n.provenanceJson,onChange:j=>r(S=>({...S,provenanceJson:j.target.value})),className:"min-h-[16rem] rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 font-mono text-sm text-white outline-none"})]})]}):null,i==="publish"?e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/72",children:"Version label"}),e.jsx("input",{value:n.label,onChange:j=>r(S=>({...S,label:j.target.value})),className:"rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 text-sm text-white outline-none"})]}),w?e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Items"}),e.jsx("div",{className:"mt-2 text-2xl font-semibold text-white",children:w.definition.items.length})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Sections"}),e.jsx("div",{className:"mt-2 text-2xl font-semibold text-white",children:w.definition.sections.length})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Scores"}),e.jsx("div",{className:"mt-2 text-2xl font-semibold text-white",children:w.scoring.scores.length})]})]}):null,e.jsx("p",{className:"text-sm leading-6 text-white/58",children:"Publishing freezes the current draft into an immutable version for future runs. Past run history will always keep the version it was scored against."})]}):null]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(ae,{className:"bg-[linear-gradient(180deg,rgba(14,21,31,0.98),rgba(9,14,22,0.96))]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Draft posture"}),m!=null&&m.isSystem?e.jsx("div",{className:"mt-4",children:e.jsx(gt,{eyebrow:"System seed",title:"This started as a read-only seed",description:"The builder branched it into a user-owned draft before exposing any editable state."})}):e.jsxs("div",{className:"mt-4 grid gap-2",children:[e.jsx(L,{className:"w-fit bg-white/[0.08] text-white/78",children:m!=null&&m.draftVersion?"Draft available":"New draft"}),e.jsx("div",{className:"text-sm leading-6 text-white/60",children:"Save updates whenever the metadata or JSON changes, then publish once the definition is ready for scoring and longitudinal history."})]})]}),e.jsxs(ae,{className:"bg-[linear-gradient(180deg,rgba(15,23,33,0.98),rgba(9,15,23,0.96))]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Actions"}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsx(Q,{onClick:()=>void M(),disabled:b,children:"Save draft"}),t?e.jsx(Q,{variant:"secondary",onClick:()=>f.mutate(),disabled:b||!!l,children:"Publish version"}):null,l?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:l}):null]})]})]})]})]})}function kj(){var r;const{instrumentId:t=""}=es(),s=fe({queryKey:["forge-psyche-questionnaire",t],queryFn:()=>Eh(t),enabled:t.length>0});if(s.isLoading)return e.jsx(nt,{eyebrow:"Questionnaire",title:"Loading questionnaire detail",description:"Hydrating the versioned definition, source provenance, and run history."});if(s.isError||!((r=s.data)!=null&&r.instrument))return e.jsx(ze,{eyebrow:"Questionnaire",error:s.error,onRetry:()=>void s.refetch()});const i=s.data.instrument,a=i.currentVersion??i.draftVersion,n=!i.isSystem;return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{eyebrow:"Psyche",title:i.title,description:i.description,badge:`${i.itemCount} items`,actions:e.jsxs(e.Fragment,{children:[e.jsx(Ae,{to:`/psyche/questionnaires/${i.id}/take`,children:e.jsxs(Q,{children:[e.jsx(Cs,{className:"mr-2 size-4"}),"Start run"]})}),n?e.jsx(Ae,{to:`/psyche/questionnaires/${i.id}/edit`,children:e.jsxs(Q,{variant:"secondary",children:[e.jsx(Tl,{className:"mr-2 size-4"}),"Edit draft"]})}):e.jsx(Ae,{to:`/psyche/questionnaires/${i.id}/edit`,children:e.jsxs(Q,{variant:"secondary",children:[e.jsx(Op,{className:"mr-2 size-4"}),"Clone to draft"]})})]})}),e.jsx(Bt,{}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.05fr)_minmax(18rem,0.95fr)]",children:[e.jsxs(ae,{className:"bg-[linear-gradient(180deg,rgba(15,23,34,0.98),rgba(9,14,22,0.96))]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-[rgba(110,231,183,0.74)]",children:"Guided definition"}),e.jsxs("div",{className:"mt-4 grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Flow"}),e.jsx("div",{className:"mt-2 text-sm text-white/84",children:i.presentationMode.replaceAll("_"," ")})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Response style"}),e.jsx("div",{className:"mt-2 text-sm text-white/84",children:i.responseStyle.replaceAll("_"," ")})]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Version"}),e.jsx("div",{className:"mt-2 text-sm text-white/84",children:i.currentVersionNumber?`v${i.currentVersionNumber}`:"Draft"})]})]}),a?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"mt-5 text-sm leading-6 text-white/62",children:a.definition.instructions}),e.jsx("div",{className:"mt-5 grid gap-3",children:a.definition.sections.map(l=>e.jsx("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-white",children:l.title}),l.description?e.jsx("div",{className:"mt-1 text-sm text-white/54",children:l.description}):null]}),e.jsxs(L,{className:"bg-white/[0.08] text-white/78",children:[l.itemIds.length," items"]})]})},l.id))})]}):null]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(ae,{className:"bg-[linear-gradient(180deg,rgba(17,25,34,0.98),rgba(10,15,24,0.96))]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Provenance"}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(L,{className:"bg-[rgba(125,211,252,0.12)] text-sky-100/88",children:i.sourceClass.replaceAll("_"," ")}),e.jsx(L,{className:"bg-[rgba(192,193,255,0.12)] text-white/84",children:i.availability.replaceAll("_"," ")}),i.symptomDomains.map(l=>e.jsx(L,{className:"bg-white/[0.06] text-white/72",children:l},l))]}),a?e.jsx("div",{className:"mt-4 grid gap-3",children:a.provenance.sources.map(l=>e.jsxs("a",{href:l.url,target:"_blank",rel:"noreferrer",className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-4 transition hover:bg-white/[0.05]",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:l.label}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:l.citation})]},l.url))}):null]}),e.jsxs(ae,{className:"bg-[linear-gradient(180deg,rgba(15,23,33,0.98),rgba(9,15,23,0.96))]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"History over time"}),i.history.length===0?e.jsx("div",{className:"mt-4",children:e.jsx(gt,{eyebrow:"Run history",title:"No completed runs yet",description:"Complete the first guided run and the longitudinal score trace will appear here."})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 h-56",children:e.jsx(Kn,{width:"100%",height:"100%",children:e.jsxs(dx,{data:[...i.history].reverse(),children:[e.jsx(Un,{dataKey:"completedAt",tickFormatter:l=>new Date(l).toLocaleDateString(void 0,{month:"short",day:"numeric"}),stroke:"rgba(255,255,255,0.38)"}),e.jsx(Qn,{stroke:"rgba(255,255,255,0.38)"}),e.jsx(Sh,{contentStyle:{background:"rgba(10,15,24,0.96)",border:"1px solid rgba(255,255,255,0.08)",borderRadius:18},labelFormatter:l=>new Date(String(l)).toLocaleString()}),e.jsx(cx,{type:"monotone",dataKey:"primaryScore",stroke:"rgba(110,231,183,0.95)",strokeWidth:3,dot:{r:4}})]})})}),e.jsx("div",{className:"mt-4 grid gap-3",children:i.history.slice(0,5).map(l=>e.jsx(Ae,{to:`/psyche/questionnaire-runs/${l.runId}`,className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-4 transition hover:bg-white/[0.05]",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-white",children:l.primaryScoreLabel||"Primary score"}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:new Date(l.completedAt).toLocaleString()})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-lg font-semibold text-white",children:l.primaryScore??"—"}),l.bandLabel?e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-[rgba(110,231,183,0.78)]",children:l.bandLabel}):null]})]})},l.runId))})]})]})]})]})]})}function Sj(){const{runId:t=""}=es(),s=fe({queryKey:["forge-psyche-questionnaire-run",t],queryFn:()=>dg(t),enabled:t.length>0});if(s.isLoading)return e.jsx(nt,{eyebrow:"Questionnaire result",title:"Loading scored run",description:"Hydrating the recorded answers, stored scores, and longitudinal context."});if(s.isError||!s.data)return e.jsx(ze,{eyebrow:"Questionnaire result",error:s.error,onRetry:()=>void s.refetch()});const i=s.data,a=new Map(i.answers.map(n=>[n.itemId,n]));return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{eyebrow:"Questionnaire result",title:i.instrument.title,description:"Stored raw answers, computed scores, and score history all remain attached to the exact version used for this run.",badge:i.run.completedAt?"Completed":"Draft",actions:e.jsxs(e.Fragment,{children:[e.jsx(Ae,{to:`/psyche/questionnaires/${i.instrument.id}`,children:e.jsx(Q,{variant:"secondary",children:"Back to questionnaire"})}),e.jsx(Ae,{to:`/psyche/questionnaires/${i.instrument.id}/take`,children:e.jsx(Q,{children:"Take again"})})]})}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(18rem,1.1fr)]",children:[e.jsxs(ae,{className:"bg-[linear-gradient(180deg,rgba(16,24,34,0.98),rgba(10,15,24,0.96))]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Stored scores"}),i.scores.length===0?e.jsx("div",{className:"mt-4",children:e.jsx(gt,{eyebrow:"Scores",title:"No scores stored yet",description:"This run has not been completed, so there are no persisted score rows yet."})}):e.jsx("div",{className:"mt-4 grid gap-3",children:i.scores.map(n=>e.jsx("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-white",children:n.label}),n.bandLabel?e.jsx("div",{className:"mt-2 text-xs uppercase tracking-[0.16em] text-[rgba(110,231,183,0.74)]",children:n.bandLabel}):null]}),e.jsx("div",{className:"text-right text-lg font-semibold text-white",children:n.valueText??n.valueNumeric??"—"})]})},n.scoreKey))})]}),e.jsxs(ae,{className:"bg-[linear-gradient(180deg,rgba(15,23,33,0.98),rgba(9,15,23,0.96))]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Answer ledger"}),e.jsx("div",{className:"mt-4 grid gap-3",children:i.version.definition.items.map(n=>{const r=a.get(n.id);return e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-sm font-medium leading-6 text-white",children:n.prompt}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:n.options.map(l=>{const o=(r==null?void 0:r.optionKey)===l.key;return e.jsx(L,{className:o?"bg-[rgba(110,231,183,0.16)] text-[rgba(187,247,208,0.94)]":"bg-white/[0.05] text-white/54",children:l.label},`${n.id}-${l.key}`)})})]},n.id)})})]})]})]})}const Tc=new Map;function ri(t){return new Error(t)}function Cj(t){const s=[];let i=0;for(;i<t.length;){const a=t[i];if(/\s/.test(a)){i+=1;continue}const n=t.slice(i,i+2);if(n==="=="||n==="!="||n===">="||n==="<="||n==="&&"||n==="||"){s.push({type:n}),i+=2;continue}if("(),><+-*/!".includes(a)){s.push({type:a}),i+=1;continue}if(a==="'"||a==='"'){const r=a;i+=1;let l="";for(;i<t.length&&t[i]!==r;){const o=t[i];if(o==="\\"&&i+1<t.length){l+=t[i+1],i+=2;continue}l+=o,i+=1}if(t[i]!==r)throw ri(`Unterminated string in flow rule: ${t}`);i+=1,s.push({type:"string",value:l});continue}if(/\d/.test(a)){let r=a;for(i+=1;i<t.length&&/[\d.]/.test(t[i]);)r+=t[i],i+=1;s.push({type:"number",value:Number(r)});continue}if(/[A-Za-z_]/.test(a)){let r=a;for(i+=1;i<t.length&&/[A-Za-z0-9_]/.test(t[i]);)r+=t[i],i+=1;const l=r.toLowerCase();l==="and"?s.push({type:"&&"}):l==="or"?s.push({type:"||"}):l==="not"?s.push({type:"!"}):l==="true"?s.push({type:"boolean",value:!0}):l==="false"?s.push({type:"boolean",value:!1}):l==="null"?s.push({type:"null"}):s.push({type:"identifier",value:r});continue}throw ri(`Unexpected token '${a}' in flow rule: ${t}`)}return s}function Ij(t,s){let i=0;function a(){return t[i]}function n(m){const b=t[i];return!b||m&&b.type!==m?null:(i+=1,b)}function r(m){const b=n(m);if(!b)throw ri(`Expected '${m}' in flow rule: ${s}`);return b}function l(){const m=a();if(!m)throw ri(`Unexpected end of flow rule: ${s}`);if(n("(")){const b=f();return r(")"),b}if(m.type==="number")return n("number"),{kind:"literal",value:m.value};if(m.type==="string")return n("string"),{kind:"literal",value:m.value};if(m.type==="boolean")return n("boolean"),{kind:"literal",value:m.value};if(m.type==="null")return n("null"),{kind:"literal",value:null};if(m.type==="identifier"){const b=n("identifier").value;if(n("(")){const w=[];if(!n(")")){do w.push(f());while(n(","));r(")")}if(b!=="answered"&&b!=="option"&&b!=="label"&&b!=="value")throw ri(`Unknown flow function '${b}' in rule: ${s}`);return{kind:"call",name:b,args:w}}return{kind:"reference",itemId:b}}throw ri(`Unexpected token '${m.type}' in flow rule: ${s}`)}function o(){return n("!")?{kind:"unary",operator:"!",operand:o()}:n("-")?{kind:"unary",operator:"-",operand:o()}:l()}function c(){let m=o();for(;;){if(n("*")){m={kind:"binary",operator:"*",left:m,right:o()};continue}if(n("/")){m={kind:"binary",operator:"/",left:m,right:o()};continue}return m}}function x(){let m=c();for(;;){if(n("+")){m={kind:"binary",operator:"+",left:m,right:c()};continue}if(n("-")){m={kind:"binary",operator:"-",left:m,right:c()};continue}return m}}function v(){let m=x();for(;;){const b=a(),w=b&&(b.type==="=="||b.type==="!="||b.type===">="||b.type==="<="||b.type===">"||b.type==="<")?b.type:null;if(!w)return m;i+=1,m={kind:"binary",operator:w,left:m,right:x()}}}function u(){let m=v();for(;n("&&");)m={kind:"binary",operator:"&&",left:m,right:v()};return m}function f(){let m=u();for(;n("||");)m={kind:"binary",operator:"||",left:m,right:u()};return m}const h=f();if(i<t.length)throw ri(`Unexpected trailing tokens in flow rule: ${s}`);return h}function Tj(t){const s=Tc.get(t);if(s)return s;const i=Ij(Cj(t),t);return Tc.set(t,i),i}function Pj(t){return t.kind==="reference"?t.itemId:t.kind==="literal"&&typeof t.value=="string"&&t.value.trim().length>0?t.value.trim():null}function _i(t){return typeof t=="boolean"?t:typeof t=="number"?t!==0:typeof t=="string"?t.length>0:!1}function ds(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="boolean")return t?1:0;if(typeof t=="string"){const s=Number(t);return Number.isFinite(s)?s:null}return null}function Mj(t,s,i){const a=ds(t),n=ds(i);if(a!==null&&n!==null)switch(s){case"==":return a===n;case"!=":return a!==n;case">":return a>n;case">=":return a>=n;case"<":return a<n;case"<=":return a<=n}return s==="=="||s==="!="?s==="=="?t===i:t!==i:!1}function gn(t,s){switch(t.kind){case"literal":return t.value;case"reference":return s.getAnswerValue(t.itemId);case"unary":{const i=gn(t.operand,s);if(t.operator==="!")return!_i(i);const a=ds(i);return a===null?null:-a}case"binary":{const i=gn(t.left,s),a=gn(t.right,s);switch(t.operator){case"&&":return _i(i)&&_i(a);case"||":return _i(i)||_i(a);case"+":return i===null||a===null?null:(ds(i)??0)+(ds(a)??0);case"-":return i===null||a===null?null:(ds(i)??0)-(ds(a)??0);case"*":return i===null||a===null?null:(ds(i)??0)*(ds(a)??0);case"/":{const n=ds(a);return i===null||n===null||n===0?null:(ds(i)??0)/n}default:return Mj(i,t.operator,a)}}case"call":{const i=t.args[0]?Pj(t.args[0]):null;if(!i)return null;switch(t.name){case"answered":return s.isAnswered(i);case"option":return s.getOptionKey(i);case"label":return s.getLabel(i);case"value":return s.getAnswerValue(i)}}}}function Aj(t){return new Map(t.map(s=>[s.itemId,{optionKey:s.optionKey??null,numericValue:s.numericValue??null,valueText:s.valueText??null}]))}function Pc(t,s,i){const a=Tj(t),n=Aj(s),r=gn(a,{getAnswerValue:l=>{if(!i.has(l))return null;const o=n.get(l);return(o==null?void 0:o.numericValue)??(o==null?void 0:o.optionKey)??(o==null?void 0:o.valueText)??null},getOptionKey:l=>{var o;return i.has(l)?((o=n.get(l))==null?void 0:o.optionKey)??null:null},getLabel:l=>{var o;return i.has(l)?((o=n.get(l))==null?void 0:o.valueText)??null:null},isAnswered:l=>{if(!i.has(l))return!1;const o=n.get(l);return!!(o&&(o.optionKey!==null||o.numericValue!==null||(o.valueText??"").trim().length>0))}});return _i(r)}function Ej(t,s){const i=new Set,a=new Set,n=new Map(t.items.map(l=>[l.id,l])),r=new Map;for(const l of t.sections){if(!(!l.visibility||Pc(l.visibility.script,s,i)))continue;const c=l.itemIds.filter(x=>{const v=n.get(x);if(!v)return!1;const u=!v.visibility||Pc(v.visibility.script,s,i);return u&&i.add(v.id),u});c.length>0&&(a.add(l.id),r.set(l.id,c))}return{visibleItemIds:i,visibleSectionIds:a,visibleItemIdsBySection:r}}function Lj(t,s){const i=t.options.find(a=>a.key===s);return i?{itemId:t.id,optionKey:i.key,valueText:i.label,numericValue:i.value,answer:{label:i.label,value:i.value}}:null}function Dj(){const{instrumentId:t=""}=es(),s=ut(),[i,a]=d.useState(null),n=xe({mutationFn:()=>og(t,{userId:"user_operator"}),onSuccess:p=>a(p)}),r=xe({mutationFn:p=>cg(i.run.id,p),onSuccess:p=>a(p)}),l=xe({mutationFn:()=>hg(i.run.id),onSuccess:p=>{a(p),s(`/psyche/questionnaire-runs/${p.run.id}`)}});d.useEffect(()=>{t&&n.mutate()},[t]);const o=i,c=d.useMemo(()=>new Map(((o==null?void 0:o.answers)??[]).map(p=>[p.itemId,p.optionKey??""])),[o]),x=(o==null?void 0:o.version.definition.sections)??[],v=(o==null?void 0:o.version.definition.items)??[],u=d.useMemo(()=>o?Ej(o.version.definition,o.answers):{visibleItemIds:new Set,visibleSectionIds:new Set,visibleItemIdsBySection:new Map},[o]),f=d.useMemo(()=>v.filter(p=>u.visibleItemIds.has(p.id)),[v,u]),h=d.useMemo(()=>x.filter(p=>u.visibleSectionIds.has(p.id)).map(p=>({...p,itemIds:u.visibleItemIdsBySection.get(p.id)??[]})),[x,u]),m=(o==null?void 0:o.version.definition.presentationMode)==="single_question"?f.length:h.length,b=m>0?Math.min((o==null?void 0:o.run.progressIndex)??0,m-1):0,w=h[b]??null,M=(o==null?void 0:o.version.definition.presentationMode)==="single_question"?f[b]??null:null,E=f.every(p=>!p.required||c.has(p.id)),D=async p=>{o&&(a(A=>A&&{...A,run:{...A.run,progressIndex:p}}),await r.mutateAsync({answers:[],progressIndex:p}))},j=async(p,A,T)=>{const k=Lj(p,A);!k||!o||(a($=>{if(!$)return $;const g=$.answers.filter(C=>C.itemId!==p.id);return{...$,run:{...$.run,progressIndex:T},answers:[...g,{...k,optionKey:k.optionKey??null,numericValue:k.numericValue??null,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}]}}),await r.mutateAsync({answers:[k],progressIndex:T}))};if(n.isPending||!o)return e.jsx(nt,{eyebrow:"Questionnaire run",title:"Preparing guided run",description:"Opening the current questionnaire version, loading any draft answers, and restoring your place."});if(n.isError)return e.jsx(ze,{eyebrow:"Questionnaire run",error:n.error,onRetry:()=>n.mutate()});const S=m>0?(b+1)/m*100:0;return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{eyebrow:"Guided questionnaire",title:o.instrument.title,description:o.version.definition.instructions,badge:`v${o.version.versionNumber}`,actions:e.jsx(Ae,{to:`/psyche/questionnaires/${o.instrument.id}`,children:e.jsx(Q,{variant:"secondary",children:"Back to detail"})})}),e.jsxs(ae,{className:"overflow-hidden bg-[linear-gradient(180deg,rgba(15,23,34,0.98),rgba(8,13,20,0.98))] p-0",children:[e.jsxs("div",{className:"border-b border-white/8 px-5 py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Progress"}),e.jsxs("div",{className:"mt-2 text-sm text-white/72",children:["Step ",b+1," of ",m]})]}),e.jsx("div",{className:"flex items-center gap-2 text-sm text-white/56",children:r.isPending?e.jsxs(e.Fragment,{children:[e.jsx(_n,{className:"size-4 animate-spin"}),"Autosaving"]}):e.jsxs(e.Fragment,{children:[e.jsx(Pl,{className:"size-4 text-[var(--tertiary)]"}),"Saved"]})})]}),e.jsx("div",{className:"mt-3 h-1.5 rounded-full bg-white/[0.06]",children:e.jsx("div",{className:"h-full rounded-full bg-[linear-gradient(90deg,rgba(110,231,183,0.92),rgba(125,211,252,0.86))] transition-[width] duration-300",style:{width:`${S}%`}})})]}),o.version.definition.presentationMode==="single_question"&&M?e.jsx("div",{className:"px-5 py-6 sm:px-6",children:e.jsxs("div",{className:"mx-auto max-w-3xl",children:[e.jsx("div",{className:"font-display text-[clamp(1.7rem,3vw,2.4rem)] leading-tight text-white",children:M.prompt}),e.jsx("div",{className:"mt-6 grid gap-3",children:M.options.map(p=>{const A=c.get(M.id)===p.key;return e.jsx("button",{type:"button",className:re("rounded-[24px] border px-5 py-5 text-left transition",A?"border-[rgba(110,231,183,0.35)] bg-[rgba(110,231,183,0.14)] text-white":"border-white/8 bg-white/[0.03] text-white/74 hover:bg-white/[0.06]"),onClick:()=>void j(M,p.key,b),children:e.jsx("div",{className:"text-base font-medium",children:p.label})},p.key)})}),e.jsxs("div",{className:"mt-6 flex flex-wrap items-center justify-between gap-3",children:[e.jsxs(Q,{variant:"secondary",disabled:b===0,onClick:()=>void D(Math.max(0,b-1)),children:[e.jsx(fn,{className:"mr-2 size-4"}),"Previous"]}),b<f.length-1?e.jsxs(Q,{onClick:()=>void D(Math.min(f.length-1,b+1)),children:["Next",e.jsx(Gt,{className:"ml-2 size-4"})]}):e.jsx(Q,{disabled:!E||l.isPending,onClick:()=>l.mutate(),children:"Finish and score"})]})]})}):w?e.jsx("div",{className:"px-5 py-6 sm:px-6",children:e.jsxs("div",{className:"mx-auto max-w-5xl",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-[rgba(110,231,183,0.72)]",children:w.title}),w.description?e.jsx("div",{className:"mt-2 text-sm text-white/56",children:w.description}):null]}),e.jsxs(L,{className:"bg-white/[0.08] text-white/78",children:[w.itemIds.length," items"]})]}),e.jsx("div",{className:"mt-6 grid gap-4",children:w.itemIds.map(p=>{const A=f.find(T=>T.id===p);return A?e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-sm leading-6 text-white",children:A.prompt}),e.jsx("div",{className:"mt-4 grid gap-2 md:grid-cols-3 xl:grid-cols-6",children:A.options.map(T=>{const k=c.get(A.id)===T.key;return e.jsx("button",{type:"button",className:re("rounded-[18px] border px-3 py-3 text-sm transition",k?"border-[rgba(110,231,183,0.35)] bg-[rgba(110,231,183,0.14)] text-white":"border-white/8 bg-white/[0.03] text-white/66 hover:bg-white/[0.06]"),onClick:()=>void j(A,T.key,b),children:T.label},T.key)})})]},A.id):null})}),e.jsxs("div",{className:"mt-6 flex flex-wrap items-center justify-between gap-3",children:[e.jsxs(Q,{variant:"secondary",disabled:b===0,onClick:()=>void D(Math.max(0,b-1)),children:[e.jsx(fn,{className:"mr-2 size-4"}),"Previous section"]}),b<h.length-1?e.jsxs(Q,{onClick:()=>void D(Math.min(h.length-1,b+1)),children:["Next section",e.jsx(Gt,{className:"ml-2 size-4"})]}):e.jsx(Q,{disabled:!E||l.isPending,onClick:()=>l.mutate(),children:"Finish and score"})]})]})}):null]})]})}function Fs(t,s){return`${t}: ${s}`}function $j(t){const s=new Map;for(const i of t){const a=(n,r,l)=>{s.has(n)||s.set(n,{id:n,label:r,description:l})};for(const n of i.aliases)a(`alias:${n}`,Fs("Alias",n),"Filter by questionnaire alias.");for(const n of i.symptomDomains)a(`domain:${n}`,Fs("Domain",n),"Filter by symptom domain.");a(`source:${i.sourceClass}`,Fs("Source",i.sourceClass.replaceAll("_"," ")),"Filter by source and licence class."),a(`presentation:${i.presentationMode}`,Fs("Flow",i.presentationMode.replaceAll("_"," ")),"Filter by runner presentation mode."),a(`response:${i.responseStyle}`,Fs("Response",i.responseStyle.replaceAll("_"," ")),"Filter by response style."),a(`availability:${i.availability}`,Fs("Availability",i.availability.replaceAll("_"," ")),"Filter by availability."),a(`size:${i.itemCount>=50?"long":i.itemCount>=15?"medium":"short"}`,Fs("Length",i.itemCount>=50?"long":i.itemCount>=15?"medium":"short"),"Filter by approximate questionnaire length."),a(`self:${i.isSelfReport?"self_report":"other"}`,Fs("Type",i.isSelfReport?"self report":"other"),"Filter by self-report availability.")}return Array.from(s.values()).sort((i,a)=>i.label.localeCompare(a.label))}function Oj(t,s){return t.every(i=>{const[a,n]=i.split(":",2);if(!a||!n)return!0;switch(a){case"alias":return s.aliases.includes(n);case"domain":return s.symptomDomains.includes(n);case"source":return s.sourceClass===n;case"presentation":return s.presentationMode===n;case"response":return s.responseStyle===n;case"availability":return s.availability===n;case"size":return n==="long"?s.itemCount>=50:n==="medium"?s.itemCount>=15&&s.itemCount<50:s.itemCount<15;case"self":return n==="self_report"?s.isSelfReport:!s.isSelfReport;default:return!0}})}function Fj(){var c;const[t,s]=d.useState(""),[i,a]=d.useState([]),n=fe({queryKey:["forge-psyche-questionnaires"],queryFn:()=>Ah()}),r=((c=n.data)==null?void 0:c.instruments)??[],l=d.useMemo(()=>$j(r),[r]),o=d.useMemo(()=>{const x=t.trim().toLowerCase();return r.filter(v=>(x.length===0||`${v.title} ${v.subtitle} ${v.description} ${v.aliases.join(" ")} ${v.symptomDomains.join(" ")} ${v.tags.join(" ")}`.toLowerCase().includes(x))&&Oj(i,v))},[r,t,i]);return n.isLoading?e.jsx(nt,{eyebrow:"Questionnaires",title:"Loading the questionnaire library",description:"Hydrating the seeded assessment catalog, versions, and latest run history."}):n.isError?e.jsx(ze,{eyebrow:"Questionnaires",error:n.error,onRetry:()=>void n.refetch()}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{eyebrow:"Psyche",title:"Questionnaires",description:"Browse the seeded mental health questionnaire library, narrow it with facet chips, launch guided runs, and build your own versioned instruments.",badge:`${r.length} instruments`,actions:e.jsx(Ae,{to:"/psyche/questionnaires/new",children:e.jsx(Q,{children:"Build questionnaire"})})}),e.jsx(Bt,{}),e.jsx(Fa,{title:"Questionnaire filters",description:"Search by title or alias, then pin chips for symptom domain, source class, item count, response style, flow mode, self-report status, or availability.",query:t,onQueryChange:s,options:l,selectedOptionIds:i,onSelectedOptionIdsChange:a,resultSummary:`${o.length} of ${r.length} questionnaires visible`}),o.length===0?e.jsx(gt,{eyebrow:"Questionnaire library",title:"No questionnaires match the current filters",description:"Clear one or two chips and the seeded catalog will come back into view."}):e.jsx("section",{className:"grid gap-4 xl:grid-cols-2",children:o.map(x=>e.jsxs(ae,{className:"overflow-hidden bg-[linear-gradient(180deg,rgba(16,24,34,0.97),rgba(10,16,24,0.95))]",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-[rgba(110,231,183,0.74)]",children:x.subtitle||"Questionnaire"}),e.jsx("h2",{className:"mt-3 font-display text-[clamp(1.35rem,2vw,1.9rem)] leading-none text-white",children:x.title}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/60",children:x.description})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.04] px-3 py-3 text-right",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Latest"}),e.jsx("div",{className:"mt-2 text-sm text-white/78",children:x.latestRunAt?new Date(x.latestRunAt).toLocaleDateString():"Not taken yet"})]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsxs(L,{className:"bg-white/[0.08] text-white/80",children:[x.itemCount," items"]}),e.jsx(L,{className:"bg-[rgba(110,231,183,0.12)] text-[rgba(187,247,208,0.9)]",children:x.presentationMode.replaceAll("_"," ")}),e.jsx(L,{className:"bg-[rgba(125,211,252,0.12)] text-sky-100/90",children:x.responseStyle.replaceAll("_"," ")}),e.jsx(L,{className:"bg-[rgba(192,193,255,0.12)] text-white/84",children:x.sourceClass.replaceAll("_"," ")})]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:x.symptomDomains.map(v=>e.jsx(L,{className:"bg-white/[0.05] text-white/66",children:v},`${x.id}-${v}`))}),e.jsxs("div",{className:"mt-5 grid gap-3 sm:grid-cols-[minmax(0,1fr)_auto_auto]",children:[e.jsx("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-3 text-sm text-white/60",children:x.completedRunCount>0?`${x.completedRunCount} completed runs saved in history`:"No saved history yet"}),e.jsx(Ae,{to:`/psyche/questionnaires/${x.id}`,children:e.jsx(Q,{variant:"secondary",className:"w-full sm:w-auto",children:"Open detail"})}),e.jsx(Ae,{to:`/psyche/questionnaires/${x.id}/take`,children:e.jsx(Q,{className:"w-full sm:w-auto",children:"Start guided run"})})]})]},x.id))}),e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[minmax(0,1.05fr)_minmax(0,0.95fr)]",children:[e.jsxs(ae,{className:"bg-[linear-gradient(180deg,rgba(15,22,34,0.98),rgba(9,14,22,0.96))]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Fp,{className:"size-5 text-[var(--tertiary)]"}),e.jsx("div",{className:"font-display text-2xl text-white",children:"Seeded first wave"})]}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/62",children:"The current library ships a verified first wave: PHQ-9, GAD-7, WHO-5, PCL-5, AUDIT, SRQ-20, and YSQ-R, each stored in SQLite as a versioned definition with scoring and provenance."})]}),e.jsxs(ae,{className:"bg-[linear-gradient(180deg,rgba(18,26,36,0.98),rgba(11,17,26,0.96))]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Aa,{className:"size-5 text-[var(--secondary)]"}),e.jsx("div",{className:"font-display text-2xl text-white",children:"Builder ready"})]}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/62",children:"System questionnaires stay read-only. Custom drafts can branch from any seed, edit structure and scoring JSON safely, and publish new immutable versions without rewriting past runs."}),e.jsx("div",{className:"mt-4",children:e.jsx(Ae,{to:"/psyche/questionnaires/new",children:e.jsx(Q,{variant:"secondary",className:re("w-full sm:w-auto"),children:"Open builder"})})})]})]})]})}const Mc="(max-width: 1023px)";function _j(){const[t,s]=d.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(Mc).matches);return d.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const i=window.matchMedia(Mc),a=n=>s(n.matches);return s(i.matches),typeof i.addEventListener=="function"?(i.addEventListener("change",a),()=>i.removeEventListener("change",a)):(i.addListener(a),()=>i.removeListener(a))},[]),t}function Rj({stages:t,activeStageId:s,onStageChange:i,stageContent:a,inspector:n}){const r=_j(),[l,o]=d.useState(!1),c=t.find(x=>x.id===s);return d.useEffect(()=>{o(!r)},[r]),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1fr)_18rem]",children:[e.jsxs("div",{className:"rounded-[30px] border border-white/8 bg-[radial-gradient(circle_at_top,rgba(196,181,253,0.12),transparent_38%),linear-gradient(180deg,rgba(21,20,38,0.98),rgba(10,12,22,0.96))] p-4",children:[e.jsxs("div",{className:"mb-4 flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/38",children:"Tracing the chain"}),e.jsx("div",{className:"mt-1 text-sm text-white/58",children:c==null?void 0:c.summary})]}),n?e.jsxs(Q,{variant:"secondary",size:"sm",onClick:()=>o(x=>!x),children:[l?e.jsx(_p,{className:"size-4"}):e.jsx(Rp,{className:"size-4"}),"Inspector"]}):null]}),e.jsx("div",{className:"mb-4 overflow-x-auto pb-1",children:e.jsx("div",{className:"flex min-w-max items-center gap-3",children:t.map((x,v)=>e.jsxs("button",{type:"button",className:re("rounded-[22px] px-4 py-3 text-left transition",x.id===s?"bg-[rgba(196,181,253,0.18)] text-white shadow-[0_18px_40px_rgba(15,12,28,0.28)]":"bg-white/[0.04] text-white/58 hover:bg-white/[0.07] hover:text-white"),onClick:()=>i(x.id),children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/34",children:[v+1,". ",x.label]}),r?null:e.jsx("div",{className:"mt-1.5 text-sm leading-5",children:x.summary})]},x.id))})}),e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(255,255,255,0.04),rgba(255,255,255,0.02))] p-4 md:p-5",children:[e.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"rounded-full bg-white/[0.07] px-3 py-1.5 text-[11px] uppercase tracking-[0.18em] text-white/42",children:c==null?void 0:c.label}),e.jsx("span",{className:"text-sm text-white/54",children:c==null?void 0:c.summary})]}),e.jsx(wn,{mode:"wait",children:e.jsx(Kt.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},exit:{opacity:0,y:-14},transition:{duration:.26,ease:"easeOut"},children:a},s)})]})]}),n?e.jsx(wn,{initial:!1,children:l?e.jsxs(Kt.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:n})]}):null}):null]})}function nr(t){return`${t}_${Math.random().toString(36).slice(2,10)}`}function zj(){return{id:nr("emotion"),emotionDefinitionId:null,label:"",intensity:55,note:""}}function qj(){return{id:nr("thought"),text:"",parentMode:"",criticMode:"",beliefId:null}}function Bj(){return{id:nr("behavior"),text:"",mode:"",behaviorId:null}}function Kj(){return{id:nr("timeline"),stage:"",modeId:null,label:"",note:""}}function Ra({title:t,description:s,onAdd:i,addLabel:a}){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(Q,{type:"button",variant:"secondary",size:"sm",onClick:i,children:[e.jsx(zt,{className:"size-4"}),a]})]})}function za({onClick:t}){return e.jsx("button",{type:"button",className:"rounded-full bg-white/[0.06] p-2 text-white/55 transition hover:bg-white/[0.12] hover:text-white",onClick:t,"aria-label":"Remove row",children:e.jsx(mt,{className:"size-4"})})}function gs({title:t,description:s,addLabel:i,items:a,onChange:n,placeholder:r}){return e.jsxs("div",{className:"grid gap-3",children:[e.jsx(Ra,{title:t,description:s,addLabel:i,onAdd:()=>n([...a,""])}),e.jsx("div",{className:"grid gap-3",children:a.map((l,o)=>e.jsxs("div",{className:"flex items-start gap-3 rounded-[22px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsx(le,{value:l,onChange:c=>n(a.map((x,v)=>v===o?c.target.value:x)),placeholder:r}),e.jsx(za,{onClick:()=>n(a.filter((c,x)=>x!==o))})]},`${t}-${o}`))})]})}function nu({items:t,onChange:s,definitions:i}){return e.jsxs("div",{className:"grid gap-3",children:[e.jsx(Ra,{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,zj()])}),e.jsx("div",{className:"grid gap-3",children:t.map(a=>e.jsxs("div",{className:"grid gap-4 rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"grid flex-1 gap-4 md:grid-cols-[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:a.emotionDefinitionId??"",onChange:n=>{const r=i.find(l=>l.id===n.target.value);s(t.map(l=>l.id===a.id?{...l,emotionDefinitionId:n.target.value||null,label:(r==null?void 0:r.label)??l.label}:l))},children:[e.jsx("option",{value:"",children:"Choose or type your own"}),i.map(n=>e.jsx("option",{value:n.id,children:n.label},n.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:a.intensity,onChange:n=>s(t.map(r=>r.id===a.id?{...r,intensity:Number(n.target.value)}:r))}),e.jsxs("div",{className:"mt-2 text-sm text-white/52",children:[a.intensity,"%"]})]})]})]}),e.jsx(za,{onClick:()=>s(t.filter(n=>n.id!==a.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(le,{value:a.label,onChange:n=>s(t.map(r=>r.id===a.id?{...r,label:n.target.value}:r)),placeholder:"Tight sadness, panic, shame, relief..."})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"What was notable about this emotion?"}),e.jsx(Me,{value:a.note,onChange:n=>s(t.map(r=>r.id===a.id?{...r,note:n.target.value}:r)),placeholder:"Short note about what made this emotion stand out."})]})]},a.id))})]})}function ru({items:t,onChange:s,beliefs:i,modes:a}){return e.jsxs("div",{className:"grid gap-3",children:[e.jsx(Ra,{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,qj()])}),e.jsx("div",{className:"grid gap-3",children:t.map(n=>e.jsxs("div",{className:"grid gap-4 rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("label",{className:"grid flex-1 gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"Thought"}),e.jsx(Me,{value:n.text,onChange:r=>s(t.map(l=>l.id===n.id?{...l,text:r.target.value}:l)),placeholder:"What sentence, image, or conclusion showed up?"})]}),e.jsx(za,{onClick:()=>s(t.filter(r=>r.id!==n.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:n.parentMode,onChange:r=>s(t.map(l=>l.id===n.id?{...l,parentMode:r.target.value}:l)),children:[e.jsx("option",{value:"",children:"None"}),a.map(r=>e.jsx("option",{value:r.title,children:r.title},r.id))]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"Critic mode influence"}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:n.criticMode,onChange:r=>s(t.map(l=>l.id===n.id?{...l,criticMode:r.target.value}:l)),children:[e.jsx("option",{value:"",children:"None"}),a.map(r=>e.jsx("option",{value:r.title,children:r.title},r.id))]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"Linked belief"}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:n.beliefId??"",onChange:r=>s(t.map(l=>l.id===n.id?{...l,beliefId:r.target.value||null}:l)),children:[e.jsx("option",{value:"",children:"None"}),i.map(r=>e.jsx("option",{value:r.id,children:r.statement},r.id))]})]})]})]},n.id))})]})}function lu({items:t,onChange:s,behaviors:i,modes:a}){return e.jsxs("div",{className:"grid gap-3",children:[e.jsx(Ra,{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,Bj()])}),e.jsx("div",{className:"grid gap-3",children:t.map(n=>e.jsxs("div",{className:"grid gap-4 rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("label",{className:"grid flex-1 gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"Behavior or urge"}),e.jsx(Me,{value:n.text,onChange:r=>s(t.map(l=>l.id===n.id?{...l,text:r.target.value}:l)),placeholder:"What did you do, or what move did you feel pulled toward?"})]}),e.jsx(za,{onClick:()=>s(t.filter(r=>r.id!==n.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:n.behaviorId??"",onChange:r=>{const l=i.find(o=>o.id===r.target.value);s(t.map(o=>o.id===n.id?{...o,behaviorId:r.target.value||null,text:l&&!o.text?l.title:o.text}:o))},children:[e.jsx("option",{value:"",children:"None"}),i.map(r=>e.jsx("option",{value:r.id,children:r.title},r.id))]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"Mode or urge context"}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:n.mode,onChange:r=>s(t.map(l=>l.id===n.id?{...l,mode:r.target.value}:l)),children:[e.jsx("option",{value:"",children:"None"}),a.map(r=>e.jsx("option",{value:r.title,children:r.title},r.id))]})]})]})]},n.id))})]})}function ou({items:t,onChange:s,modes:i,stages:a}){return e.jsxs("div",{className:"grid gap-3",children:[e.jsx(Ra,{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,Kj()])}),e.jsx("div",{className:"grid gap-3",children:t.map(n=>e.jsxs("div",{className:"grid gap-4 rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"grid flex-1 gap-4 md:grid-cols-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:n.stage,onChange:r=>s(t.map(l=>l.id===n.id?{...l,stage:r.target.value}:l)),children:[e.jsx("option",{value:"",children:"Choose stage"}),a.map(r=>e.jsx("option",{value:r,children:r},r))]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"Mode"}),e.jsxs("select",{className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-sm text-white",value:n.modeId??"",onChange:r=>{const l=i.find(o=>o.id===r.target.value);s(t.map(o=>o.id===n.id?{...o,modeId:r.target.value||null,label:l&&!o.label?l.title:o.label}:o))},children:[e.jsx("option",{value:"",children:"Choose mode"}),i.map(r=>e.jsx("option",{value:r.id,children:r.title},r.id))]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/62",children:"Moment label"}),e.jsx(le,{value:n.label,onChange:r=>s(t.map(l=>l.id===n.id?{...l,label:r.target.value}:l)),placeholder:"What was happening in this moment?"})]})]}),e.jsx(za,{onClick:()=>s(t.filter(r=>r.id!==n.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(Me,{value:n.note,onChange:r=>s(t.map(l=>l.id===n.id?{...l,note:r.target.value}:l)),placeholder:"Short note about how the mode showed up or what it was protecting."})]})]},n.id))})]})}function Uj(t){return t.join(`
|
|
21
|
-
`)}function Or(t,s){return t.includes(s)?t.filter(i=>i!==s):[...t,s]}function Qj(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:Uj(t.modeOverlays),schemaLinks:t.schemaLinks,modeTimeline:t.modeTimeline,nextMoves:t.nextMoves,linkedBehaviorIds:t.linkedBehaviorIds,linkedBeliefIds:t.linkedBeliefIds,linkedModeIds:t.linkedModeIds}}function Wj(){var F,z,J,O,_,B;const{reportId:t}=es(),s=We(),[i,a]=d.useState("spark"),[n,r]=d.useState(null),[l,o]=d.useState(!1),c=fe({queryKey:["forge-psyche-report",t],queryFn:()=>vg(t),enabled:!!t}),x=fe({queryKey:["forge-psyche-behaviors"],queryFn:xs}),v=fe({queryKey:["forge-psyche-beliefs"],queryFn:As}),u=fe({queryKey:["forge-psyche-modes"],queryFn:Es}),f=fe({queryKey:["forge-psyche-schema-catalog"],queryFn:La}),h=fe({queryKey:["forge-psyche-event-types"],queryFn:Lh}),m=fe({queryKey:["forge-psyche-emotions"],queryFn:Dh});d.useEffect(()=>{var K;(K=c.data)!=null&&K.report&&r(Qj(c.data.report))},[c.data]);const b=xe({mutationFn:async K=>{var I;const Z=(I=c.data)==null?void 0:I.report,U=hl.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(G=>G.label.trim().length>0),thoughts:K.thoughts.filter(G=>G.text.trim().length>0),behaviors:K.behaviors.filter(G=>G.text.trim().length>0),consequences:{selfShortTerm:K.selfShortTerm,selfLongTerm:K.selfLongTerm,othersShortTerm:K.othersShortTerm,othersLongTerm:K.othersLongTerm},linkedPatternIds:(Z==null?void 0:Z.linkedPatternIds)??[],linkedValueIds:(Z==null?void 0:Z.linkedValueIds)??[],linkedGoalIds:(Z==null?void 0:Z.linkedGoalIds)??[],linkedProjectIds:(Z==null?void 0:Z.linkedProjectIds)??[],linkedTaskIds:(Z==null?void 0:Z.linkedTaskIds)??[],linkedBehaviorIds:K.linkedBehaviorIds,linkedBeliefIds:K.linkedBeliefIds,linkedModeIds:K.linkedModeIds,modeOverlays:K.modeOverlaysText.split(`
|
|
22
|
-
`).map(G=>G.trim()).filter(Boolean),schemaLinks:K.schemaLinks.filter(Boolean),modeTimeline:K.modeTimeline.filter(G=>G.stage.trim().length>0&&G.label.trim().length>0),nextMoves:K.nextMoves.filter(Boolean)});return wg(t,U)},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"]})])}}),w=xe({mutationFn:zh,onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-psyche-report",t]}),await s.invalidateQueries({queryKey:["forge-insights"]})}}),M=c.error??x.error??v.error??u.error??f.error??h.error??m.error??null;if(c.isLoading||!n)return e.jsx(It,{});if(M)return e.jsx(ze,{eyebrow:"Trigger report",error:M,onRetry:()=>void Promise.all([c.refetch(),x.refetch(),v.refetch(),u.refetch(),f.refetch(),h.refetch(),m.refetch()])});if(!c.data)return e.jsx(ze,{eyebrow:"Trigger report",error:new Error("Forge returned an empty trigger report payload."),onRetry:()=>void c.refetch()});const E=c.data,D=E.report,j=((F=x.data)==null?void 0:F.behaviors)??[],S=((z=v.data)==null?void 0:z.beliefs)??[],p=((J=u.data)==null?void 0:J.modes)??[],A=((O=f.data)==null?void 0:O.schemas)??[],T=((_=h.data)==null?void 0:_.eventTypes)??[],k=((B=m.data)==null?void 0:B.emotions)??[],$=[{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?"}],g={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(le,{value:n.title,onChange:K=>r({...n,title:K.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:n.status,onChange:K=>r({...n,status:K.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:n.eventTypeId,onChange:K=>r({...n,eventTypeId:K.target.value}),children:[e.jsx("option",{value:"",children:"Custom or uncategorized"}),T.map(K=>e.jsx("option",{value:K.id,children:K.label},K.id))]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Occurred at"}),e.jsx(le,{type:"datetime-local",value:n.occurredAt,onChange:K=>r({...n,occurredAt:K.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(le,{value:n.customEventType,onChange:K=>r({...n,customEventType:K.target.value})})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Situation"}),e.jsx(Me,{value:n.eventSituation,onChange:K=>r({...n,eventSituation:K.target.value})})]})]}),wave:e.jsx(nu,{items:n.emotions,onChange:K=>r({...n,emotions:K}),definitions:k}),script:e.jsx(ru,{items:n.thoughts,onChange:K=>r({...n,thoughts:K}),beliefs:S,modes:p}),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(it,{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(Hs,{children:"Choose the schemas that were active here or that you want the repair move to strengthen."}),[{title:"Maladaptive schemas",schemas:A.filter(K=>K.schemaType==="maladaptive"),schemaType:"maladaptive",description:"Recurring old patterns that felt active in this moment."},{title:"Adaptive schemas",schemas:A.filter(K=>K.schemaType==="adaptive"),schemaType:"adaptive",description:"Healthier stable themes you want this chain to strengthen."}].map(K=>{const Z=Gi(K.schemaType);return e.jsxs("div",{className:`rounded-[22px] border p-4 ${Z.cardTone}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:K.title}),e.jsx(it,{content:ka(K.schemaType),label:`Explain ${ar(K.schemaType)}`})]}),e.jsx(Hs,{className:"mt-2",children:K.description}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:K.schemas.map(U=>{const I=n.schemaLinks.some(G=>{var W;return((W=Xi(G,[U]))==null?void 0:W.id)===U.id});return e.jsx("button",{type:"button",className:`rounded-full border px-3 py-2 text-sm transition ${I?`${Z.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({...n,schemaLinks:iu(n.schemaLinks,U)}),children:U.title},U.id)})})]},K.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:S.map(K=>{const Z=n.linkedBeliefIds.includes(K.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${Z?"bg-[rgba(196,181,253,0.18)] text-violet-100":"bg-white/[0.05] text-white/58 hover:bg-white/[0.08] hover:text-white"}`,onClick:()=>r({...n,linkedBeliefIds:Or(n.linkedBeliefIds,K.id)}),children:K.statement},K.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(Me,{value:n.modeOverlaysText,onChange:K=>r({...n,modeOverlaysText:K.target.value})})]}),e.jsx(ou,{items:n.modeTimeline,onChange:K=>r({...n,modeTimeline:K}),modes:p,stages:$.map(K=>K.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:p.map(K=>{const Z=n.linkedModeIds.includes(K.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${Z?"bg-[rgba(251,191,36,0.18)] text-amber-100":"bg-white/[0.05] text-white/58 hover:bg-white/[0.08] hover:text-white"}`,onClick:()=>r({...n,linkedModeIds:Or(n.linkedModeIds,K.id)}),children:K.title},K.id)})})]})]}),move:e.jsxs("div",{className:"grid gap-4",children:[e.jsx(lu,{items:n.behaviors,onChange:K=>r({...n,behaviors:K}),behaviors:j,modes:p}),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:j.map(K=>{const Z=n.linkedBehaviorIds.includes(K.id);return e.jsx("button",{type:"button",className:`rounded-full px-3 py-2 text-sm transition ${Z?"bg-[rgba(251,113,133,0.16)] text-rose-100":"bg-white/[0.05] text-white/58 hover:bg-white/[0.08] hover:text-white"}`,onClick:()=>r({...n,linkedBehaviorIds:Or(n.linkedBehaviorIds,K.id)}),children:K.title},K.id)})})]})]}),horizon:e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(gs,{title:"Short-term impact on you",description:"What happened to you right away?",addLabel:"Add self effect",items:n.selfShortTerm,onChange:K=>r({...n,selfShortTerm:K}),placeholder:"I shut down and lost the evening."}),e.jsx(gs,{title:"Long-term impact on you",description:"What does this cost if it keeps repeating?",addLabel:"Add self cost",items:n.selfLongTerm,onChange:K=>r({...n,selfLongTerm:K}),placeholder:"It keeps training the same abandonment script."}),e.jsx(gs,{title:"Short-term impact on others",description:"What happened to other people right away?",addLabel:"Add other effect",items:n.othersShortTerm,onChange:K=>r({...n,othersShortTerm:K}),placeholder:"They felt shut out."}),e.jsx(gs,{title:"Long-term impact on others",description:"What pattern does this create over time?",addLabel:"Add other cost",items:n.othersLongTerm,onChange:K=>r({...n,othersLongTerm:K}),placeholder:"Trust gets thinner each time."})]}),pivot:e.jsxs("div",{className:"grid gap-4",children:[e.jsx(gs,{title:"What is the next move now?",description:"Finish with concrete repairs, boundaries, or committed actions.",addLabel:"Add next move",items:n.nextMoves,onChange:K=>r({...n,nextMoves:K}),placeholder:"Send one honest repair message tomorrow morning."}),e.jsx("div",{className:"flex justify-end",children:e.jsx(Q,{pending:b.isPending,onClick:()=>void b.mutateAsync(n),children:"Save chain"})})]})},C=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:[p.filter(K=>n.linkedModeIds.includes(K.id)).map(K=>e.jsx(Te,{kind:"mode",label:K.title,compact:!0},K.id)),n.linkedModeIds.length===0?e.jsx(Q,{variant:"secondary",size:"sm",onClick:()=>a("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:[S.filter(K=>n.linkedBeliefIds.includes(K.id)).map(K=>e.jsx("div",{className:"rounded-[16px] bg-white/[0.04] px-3 py-3",children:e.jsx(Te,{kind:"belief",label:K.statement,compact:!0})},K.id)),n.linkedBeliefIds.length===0?e.jsx(Q,{variant:"secondary",size:"sm",onClick:()=>a("lens"),children:"Link belief"}):null]})]}),e.jsx(Zn,{entityType:"trigger_report",entityId:D.id,anchorKey:i,includeAnchorlessWhenAnchored:!0,compact:!0,title:`Stage notes on ${i}`,description:"Use anchored Markdown notes to capture what became clear at this stage of the chain.",invalidateQueryKeys:[["forge-psyche-report",t],["forge-psyche-reports"],["forge-psyche-overview"]]}),e.jsxs("div",{className:"rounded-[22px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Insights"}),e.jsxs("div",{className:"mt-3 grid gap-2",children:[E.insights.map(K=>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:K.title}),e.jsx("div",{className:"mt-2 text-white/62",children:K.summary})]},K.id)),e.jsx(Q,{variant:"secondary",pending:w.isPending,onClick:()=>o(!0),children:"Store insight"})]})]})]});return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{eyebrow:"Trigger report",title:D.title,description:"Move through Spark to Pivot in one chain canvas.",badge:D.status}),e.jsx(Bt,{}),e.jsx(Rj,{stages:$,activeStageId:i,onStageChange:a,stageContent:g[i],inspector:C}),e.jsx(Em,{open:l,onOpenChange:o,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:w.isPending,lockedEntity:{entityType:"trigger_report",entityId:D.id,kind:"report",label:D.title,description:`Anchored to the ${i} stage of this reflective chain.`},initialValue:{originType:"user",originLabel:"Forge Psyche",timeframeLabel:"Current trigger report",rationale:`Captured from the ${i} stage of the Psyche chain canvas.`},onSubmit:async K=>{await w.mutateAsync(K)}})]})}const an={title:"",status:"draft",eventTypeId:"",customEventType:"",eventSituation:"",occurredAt:"",emotions:[],thoughts:[],behaviors:[],selfShortTerm:[],selfLongTerm:[],othersShortTerm:[],othersLongTerm:[],linkedValueIds:[],linkedBehaviorIds:[],linkedBeliefIds:[],linkedModeIds:[],linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],schemaLinks:[],modeTimeline:[],nextMoves:[],userId:null};function Hj(t){const s=new Date(t);if(Number.isNaN(s.getTime()))return"";const i=s.getFullYear(),a=String(s.getMonth()+1).padStart(2,"0"),n=String(s.getDate()).padStart(2,"0"),r=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${i}-${a}-${n}T${r}:${l}`}function Gj(){var G,W,ne,de,we,Ne,H,me;const t=Je(),s=We(),[i,a]=Pt(),[n,r]=d.useState(!1),[l,o]=d.useState(an),[c,x]=d.useState(null),v=fe({queryKey:["forge-psyche-reports"],queryFn:bi}),u=fe({queryKey:["forge-psyche-values"],queryFn:ps}),f=fe({queryKey:["forge-psyche-behaviors"],queryFn:xs}),h=fe({queryKey:["forge-psyche-beliefs"],queryFn:As}),m=fe({queryKey:["forge-psyche-modes"],queryFn:Es}),b=fe({queryKey:["forge-psyche-schema-catalog"],queryFn:La}),w=fe({queryKey:["forge-psyche-event-types"],queryFn:Lh}),M=fe({queryKey:["forge-psyche-emotions"],queryFn:Dh}),E=((G=v.data)==null?void 0:G.reports)??[],D=((W=u.data)==null?void 0:W.values)??[],j=((ne=f.data)==null?void 0:ne.behaviors)??[],S=((de=h.data)==null?void 0:de.beliefs)??[],p=((we=m.data)==null?void 0:we.modes)??[],A=((Ne=b.data)==null?void 0:Ne.schemas)??[],T=((H=w.data)==null?void 0:H.eventTypes)??[],k=((me=M.data)==null?void 0:me.emotions)??[],$=Mt(t.selectedUserIds),g=t.snapshot.dashboard.notesSummaryByEntity;d.useEffect(()=>{if(i.get("create")==="1"){r(!0),o({...an,userId:i.get("userId")??$,occurredAt:i.get("occurredAt")?Hj(i.get("occurredAt")):"",customEventType:i.get("intent")==="execution_tension"?"Execution tension":i.get("intent")==="belief"?"Belief script activation":i.get("intent")==="behavior"?"Behavior spike":i.get("intent")==="pattern"?"Recurring pattern":i.get("intent")==="value"?"Blocked value":"",linkedValueIds:i.get("valueId")?[i.get("valueId")]:[],linkedBehaviorIds:i.get("behaviorId")?[i.get("behaviorId")]:[],linkedBeliefIds:i.get("beliefId")?[i.get("beliefId")]:[],linkedGoalIds:i.get("goalId")?[i.get("goalId")]:[],linkedProjectIds:i.get("projectId")?[i.get("projectId")]:[],linkedTaskIds:i.get("taskId")?[i.get("taskId")]:[]});const y=new URLSearchParams(i);y.delete("create"),y.delete("intent"),y.delete("occurredAt"),y.delete("userId"),y.delete("valueId"),y.delete("behaviorId"),y.delete("beliefId"),y.delete("goalId"),y.delete("projectId"),y.delete("taskId"),a(y,{replace:!0})}},[i,a]);const C=xe({mutationFn:async y=>{const P=hl.parse({title:y.title,status:y.status,eventTypeId:y.eventTypeId||null,customEventType:y.customEventType,eventSituation:y.eventSituation,occurredAt:y.occurredAt?new Date(y.occurredAt).toISOString():null,emotions:y.emotions.filter(q=>q.label.trim().length>0),thoughts:y.thoughts.filter(q=>q.text.trim().length>0),behaviors:y.behaviors.filter(q=>q.text.trim().length>0),consequences:{selfShortTerm:y.selfShortTerm,selfLongTerm:y.selfLongTerm,othersShortTerm:y.othersShortTerm,othersLongTerm:y.othersLongTerm},linkedPatternIds:[],linkedValueIds:y.linkedValueIds,linkedGoalIds:y.linkedGoalIds,linkedProjectIds:y.linkedProjectIds,linkedTaskIds:y.linkedTaskIds,linkedBehaviorIds:y.linkedBehaviorIds,linkedBeliefIds:y.linkedBeliefIds,linkedModeIds:y.linkedModeIds,modeOverlays:[],schemaLinks:y.schemaLinks.filter(Boolean),modeTimeline:y.modeTimeline.filter(q=>q.stage.trim().length>0&&q.label.trim().length>0),nextMoves:y.nextMoves.filter(Boolean),userId:y.userId});return $h(P)},onSuccess:async()=>{r(!1),o({...an,userId:$}),x(null),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-reports"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]}),s.invalidateQueries({queryKey:["forge-xp-metrics"]})])}}),F=D.map(y=>({value:y.id,label:st(y.title,y.user),description:Ke(y.valuedDirection,y.user),searchText:Be([y.title,y.valuedDirection,y.description],y),kind:"value"})),z=j.map(y=>({value:y.id,label:st(y.title,y.user),description:Ke(y.kind,y.user),searchText:Be([y.title,y.kind,y.description],y),kind:"behavior"})),J=S.map(y=>({value:y.id,label:st(y.statement,y.user),description:Ke(y.flexibleAlternative||y.originNote,y.user),searchText:Be([y.statement,y.flexibleAlternative,y.originNote,y.beliefType],y),kind:"belief"})),O=p.map(y=>({value:y.id,label:st(y.title,y.user),description:Ke(y.archetype||y.family,y.user),searchText:Be([y.title,y.archetype,y.family,y.persona],y),kind:"mode"})),_=async y=>{const{value:P}=await ea({title:y,description:"",valuedDirection:y,whyItMatters:"",linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],committedActions:[],userId:l.userId});return At(s,["forge-psyche-values"],"values",P),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:P.id,label:P.title,description:P.valuedDirection,kind:"value"}},B=async y=>{const{behavior:P}=await Hn({kind:"away",title:y,description:"",commonCues:[],urgeStory:"",shortTermPayoff:"",longTermCost:"",replacementMove:"",repairPlan:"",linkedPatternIds:[],linkedValueIds:[],linkedSchemaIds:[],linkedModeIds:[],userId:l.userId});return At(s,["forge-psyche-behaviors"],"behaviors",P),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:P.id,label:P.title,description:P.kind,kind:"behavior"}},K=async y=>{const{belief:P}=await ql({schemaId:null,statement:y,beliefType:"absolute",originNote:"",confidence:60,evidenceFor:[],evidenceAgainst:[],flexibleAlternative:"",linkedValueIds:[],linkedBehaviorIds:[],linkedModeIds:[],linkedReportIds:[],userId:l.userId});return At(s,["forge-psyche-beliefs"],"beliefs",P),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:P.id,label:P.statement,description:P.flexibleAlternative||P.originNote,kind:"belief"}},Z=async y=>{const{mode:P}=await Da({family:"coping",archetype:"",title:y,persona:"",imagery:"",symbolicForm:"",facialExpression:"",fear:"",burden:"",protectiveJob:"",originContext:"",firstAppearanceAt:null,linkedPatternIds:[],linkedBehaviorIds:[],linkedValueIds:[],userId:l.userId});return At(s,["forge-psyche-modes"],"modes",P),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:P.id,label:P.title,description:P.archetype||P.family,kind:"mode"}},U=[{id:"spark",eyebrow:"Spark",title:"Capture the trigger and the situation",description:"Start with what happened concretely before interpretation takes over.",render:(y,P)=>e.jsxs(e.Fragment,{children:[e.jsx(ss,{value:y.userId,users:t.snapshot.users,onChange:q=>P({userId:q}),defaultLabel:ts(t.snapshot.users.find(q=>q.id===$)??null,"Choose report owner"),help:"Trigger reports can belong to a human or bot user while still linking to shared values, behaviors, beliefs, and modes."}),e.jsx(se,{label:"Report title",children:e.jsx(le,{value:y.title,onChange:q=>P({title:q.target.value}),placeholder:"Friday silence spiral"})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(se,{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:y.eventTypeId,onChange:q=>P({eventTypeId:q.target.value}),children:[e.jsx("option",{value:"",children:"Custom or uncategorized"}),T.map(q=>e.jsx("option",{value:q.id,children:q.label},q.id))]})}),e.jsx(se,{label:"Occurred at",children:e.jsx(le,{type:"datetime-local",value:y.occurredAt,onChange:q=>P({occurredAt:q.target.value})})})]}),e.jsx(se,{label:"Custom event label",children:e.jsx(le,{value:y.customEventType,onChange:q=>P({customEventType:q.target.value}),placeholder:"Unexpected distance after vulnerability"})}),e.jsx(se,{label:"Situation",children:e.jsx(Me,{value:y.eventSituation,onChange:q=>P({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:(y,P)=>e.jsxs(e.Fragment,{children:[e.jsx(nu,{items:y.emotions,onChange:q=>P({emotions:q}),definitions:k}),e.jsx(ru,{items:y.thoughts,onChange:q=>P({thoughts:q}),beliefs:S,modes:p}),e.jsx(lu,{items:y.behaviors,onChange:q=>P({behaviors:q}),behaviors:j,modes:p})]})},{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:(y,P)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Linked values",children:e.jsx(et,{options:F,selectedValues:y.linkedValueIds,onChange:q=>P({linkedValueIds:q}),placeholder:"Search or create a value…",emptyMessage:"No values match yet.",createLabel:"Create value",onCreate:_})}),e.jsx(se,{label:"Linked behaviors",children:e.jsx(et,{options:z,selectedValues:y.linkedBehaviorIds,onChange:q=>P({linkedBehaviorIds:q}),placeholder:"Search or create a behavior…",emptyMessage:"No behaviors match yet.",createLabel:"Create behavior",onCreate:B})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(se,{label:"Linked beliefs",children:e.jsx(et,{options:J,selectedValues:y.linkedBeliefIds,onChange:q=>P({linkedBeliefIds:q}),placeholder:"Search or create a belief…",emptyMessage:"No beliefs match yet.",createLabel:"Create belief",onCreate:K})}),e.jsx(se,{label:"Linked modes",children:e.jsx(et,{options:O,selectedValues:y.linkedModeIds,onChange:q=>P({linkedModeIds:q}),placeholder:"Search or create a mode…",emptyMessage:"No modes match yet.",createLabel:"Create mode",onCreate:Z})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[y.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 ",y.linkedGoalIds.length," goal tension"]}):null,y.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 ",y.linkedProjectIds.length," project tension"]}):null,y.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 ",y.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:(y,P)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(gs,{title:"Short-term impact on you",description:"Add the immediate effects on your body, mood, or direction.",addLabel:"Add self effect",items:y.selfShortTerm,onChange:q=>P({selfShortTerm:q}),placeholder:"I shut down and lost the rest of the evening."}),e.jsx(gs,{title:"Long-term impact on you",description:"Capture what this pattern costs when it keeps repeating.",addLabel:"Add self cost",items:y.selfLongTerm,onChange:q=>P({selfLongTerm:q}),placeholder:"It keeps reinforcing the same abandonment story."}),e.jsx(gs,{title:"Short-term impact on others",description:"Note what happened to the people around you right away.",addLabel:"Add other effect",items:y.othersShortTerm,onChange:q=>P({othersShortTerm:q}),placeholder:"They felt pushed away and confused."}),e.jsx(gs,{title:"Long-term impact on others",description:"Capture the longer pattern this creates in relationships.",addLabel:"Add other cost",items:y.othersLongTerm,onChange:q=>P({othersLongTerm:q}),placeholder:"Trust gets thinner every time this loop takes over."})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsx(se,{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:A.filter(q=>q.schemaType==="maladaptive"),schemaType:"maladaptive",description:"Recurring old patterns that felt active in this moment."},{title:"Adaptive schemas",schemas:A.filter(q=>q.schemaType==="adaptive"),schemaType:"adaptive",description:"Healthier stable themes you want this repair move to strengthen."}].map(q=>{const pe=Gi(q.schemaType);return e.jsxs("div",{className:`rounded-[24px] border p-4 ${pe.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(it,{content:ka(q.schemaType),label:`Explain ${ar(q.schemaType)}`})]}),e.jsx(Hs,{className:"mt-2",children:q.description}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:q.schemas.map(ee=>{const Y=y.schemaLinks.some(R=>{var X;return((X=Xi(R,[ee]))==null?void 0:X.id)===ee.id});return e.jsx("button",{type:"button",className:`rounded-full border px-3 py-2 text-sm transition ${Y?`${pe.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:()=>P({schemaLinks:iu(y.schemaLinks,ee)}),children:ee.title},ee.id)})})]},q.schemaType)})})}),e.jsx(ou,{items:y.modeTimeline,onChange:q=>P({modeTimeline:q}),modes:p,stages:["Spark","Wave","Script","Lens","State","Move","Horizon","Pivot"]}),e.jsx(gs,{title:"Next moves",description:"Finish with concrete next moves that protect the value or repair the situation.",addLabel:"Add next move",items:y.nextMoves,onChange:q=>P({nextMoves:q}),placeholder:"Send one honest repair message tomorrow morning."})]})]})}];if(v.isLoading||u.isLoading||f.isLoading||h.isLoading||m.isLoading||b.isLoading||w.isLoading||M.isLoading)return e.jsx(nt,{eyebrow:"Reports",title:"Loading reports",description:"Getting reports, values, behaviors, beliefs, modes, event labels, and emotions ready."});const I=v.error??u.error??f.error??h.error??m.error??b.error??w.error??M.error;return I?e.jsx(ze,{eyebrow:"Trigger reports",error:I,onRetry:()=>void Promise.all([v.refetch(),u.refetch(),f.refetch(),h.refetch(),m.refetch(),b.refetch(),w.refetch(),M.refetch()])}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{entityKind:"report",title:e.jsx(Xe,{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:`${E.length} reports`,actions:e.jsx(Q,{onClick:()=>{o({...an,userId:$}),r(!0)},children:"Reflect"})}),e.jsx(Bt,{}),e.jsx(Ps,{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:E.length===0?e.jsx(gt,{eyebrow:"Trigger reports",title:"No reports yet",description:"Start a first Spark-to-Pivot chain so Forge can track the full reflective arc instead of isolated notes."}):E.map(y=>{var P;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(Xe,{kind:"report",label:y.title,variant:"heading",size:"xl"}),e.jsx("div",{className:"mt-2 text-sm text-white/54",children:y.customEventType||y.eventSituation})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.user?e.jsx(Ue,{user:y.user,compact:!0}):null,e.jsx(Vt,{entityType:"trigger_report",entityId:y.id,count:is(g,"trigger_report",y.id).count}),e.jsx(L,{children:y.status}),e.jsx(Ae,{to:`/psyche/reports/${y.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:y.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:((P=y.emotions[0])==null?void 0:P.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:y.schemaLinks[0]?(()=>{const q=Xi(y.schemaLinks[0],A);return q?e.jsx(Ws,{label:q.title,schemaType:q.schemaType,compact:!0}):e.jsx("div",{className:"text-sm leading-6 text-white/66",children:y.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:y.nextMoves[0]??"No next move yet"})]})]})]},y.id)})})}),e.jsx(rt,{open:n,onOpenChange:r,eyebrow:"Trigger report",title:"Build a reflective chain",description:"This guided flow replaces the old open worksheet with a staged Spark-to-Pivot capture.",value:l,onChange:o,steps:U,submitLabel:"Create report",pending:C.isPending,error:c,onSubmit:async()=>{if(x(null),!hl.safeParse({title:l.title,status:l.status,eventTypeId:l.eventTypeId||null,customEventType:l.customEventType,eventSituation:l.eventSituation,occurredAt:l.occurredAt?new Date(l.occurredAt).toISOString():null,emotions:l.emotions.filter(P=>P.label.trim().length>0),thoughts:l.thoughts.filter(P=>P.text.trim().length>0),behaviors:l.behaviors.filter(P=>P.text.trim().length>0),consequences:{selfShortTerm:l.selfShortTerm,selfLongTerm:l.selfLongTerm,othersShortTerm:l.othersShortTerm,othersLongTerm:l.othersLongTerm},linkedPatternIds:[],linkedValueIds:l.linkedValueIds,linkedGoalIds:l.linkedGoalIds,linkedProjectIds:l.linkedProjectIds,linkedTaskIds:l.linkedTaskIds,linkedBehaviorIds:l.linkedBehaviorIds,linkedBeliefIds:l.linkedBeliefIds,linkedModeIds:l.linkedModeIds,modeOverlays:[],schemaLinks:l.schemaLinks.filter(Boolean),modeTimeline:l.modeTimeline.filter(P=>P.stage.trim().length>0&&P.label.trim().length>0),nextMoves:l.nextMoves.filter(Boolean)}).success){x("This report still needs a title and concrete triggering situation.");return}try{await C.mutateAsync(l)}catch(P){x(P instanceof Error?P.message:"Unable to create this report right now.")}}})]})}const ml="Self-observation",du=new Set(["goal","project","task","strategy","habit","tag","psyche_value","behavior","belief_entry","mode_profile"]),va={noteId:null,contentMarkdown:"",author:"",tags:[],userId:null,observedAtInput:"",linkedPatternIds:[],linkedTriggerReportId:null,linkedEntityValues:[]};function wa(t=[]){return Ut([ml,...t])}function os(t,s){return`${t}:${s}`}function Xj(t){const s=t.indexOf(":");if(s<=0||s>=t.length-1)return null;const i=t.slice(0,s);return du.has(i)?{entityType:i,entityId:t.slice(s+1)}:null}function Vj(t){return t!==null}function Jj(t){const s=new Set;return t.filter(i=>{const a=`${i.entityType}:${i.entityId}:${i.anchorKey??""}`;return s.has(a)?!1:(s.add(a),!0)})}function cu(t){const s=new Date(t);if(Number.isNaN(s.getTime()))return"";const i=s.getFullYear(),a=String(s.getMonth()+1).padStart(2,"0"),n=String(s.getDate()).padStart(2,"0"),r=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${i}-${a}-${n}T${r}:${l}`}function nn(t){const s=t.getFullYear(),i=String(t.getMonth()+1).padStart(2,"0"),a=String(t.getDate()).padStart(2,"0");return`${s}-${i}-${a}`}function Yj(t){return new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function Ac(t){const s=(t.contentPlain||t.contentMarkdown).replace(/\s+/g," ").trim();return s.length<=120?s:`${s.slice(0,117).trimEnd()}...`}function rn(t){const s=t.note.frontmatter.movement;return!!s&&typeof s=="object"&&!Array.isArray(s)}function Zj(t,s,i){const a=new Date(t),n=new Date(s);return n.setHours(i,Number.isNaN(a.getTime())?0:a.getMinutes(),0,0),n.toISOString()}function e1(t,s){var i;return t?{noteId:t.note.id,contentMarkdown:t.note.contentMarkdown,author:t.note.author??"",tags:Ut(t.note.tags??[]),userId:t.note.userId??s,observedAtInput:cu(t.observedAt),linkedPatternIds:t.linkedPatterns.map(a=>a.id),linkedTriggerReportId:((i=t.linkedReports[0])==null?void 0:i.id)??null,linkedEntityValues:t.note.links.filter(a=>a.entityType!=="behavior_pattern"&&a.entityType!=="trigger_report"&&du.has(a.entityType)).map(a=>os(a.entityType,a.entityId))}:{...va,tags:wa(),userId:s}}function t1(t){return t.map(s=>({value:s.id,label:s.title,description:`${s.targetBehavior||s.preferredResponse||"Pattern"}${s.user?` · ${Nt(s.user)}`:""}`,searchText:`${s.title} ${s.targetBehavior} ${s.description} ${s.preferredResponse}`.toLowerCase(),kind:"pattern"}))}function s1(t){return t.map(s=>({value:s.id,label:s.title,description:`${s.customEventType||s.eventSituation||"Trigger report"}${s.user?` · ${Nt(s.user)}`:""}`,searchText:`${s.title} ${s.customEventType} ${s.eventSituation}`.toLowerCase(),kind:"report"}))}function i1({goals:t,projects:s,tasks:i,strategies:a,habits:n,tags:r,values:l,behaviors:o,beliefs:c,modes:x}){return[...[...t.map(u=>({value:os("goal",u.id),label:u.title,description:Ke(u.description,u.user,"Goal"),searchText:Be([u.title,u.description??""],u),kind:"goal"})),...s.map(u=>({value:os("project",u.id),label:u.title,description:Ke(u.description,u.user,"Project"),searchText:Be([u.title,u.description??""],u),kind:"project"})),...i.map(u=>({value:os("task",u.id),label:u.title,description:Ke(u.description,u.user,u.owner??void 0),searchText:Be([u.title,u.description??"",u.owner??""],u),kind:"task"})),...a.map(u=>({value:os("strategy",u.id),label:u.title,description:Ke(u.overview,u.user,"Strategy"),searchText:Be([u.title,u.overview??"",u.endStateDescription??""],u),kind:"strategy"})),...n.map(u=>({value:os("habit",u.id),label:u.title,description:Ke(u.description,u.user,"Habit"),searchText:Be([u.title,u.description??""],u),kind:"habit"})),...r.map(u=>({value:os("tag",u.id),label:u.name,description:Ke(u.description,u.user,u.kind??void 0),searchText:Be([u.name,u.kind??"",u.description??""],u)})),...l.map(u=>({value:os("psyche_value",u.id),label:u.title,description:Ke(u.description,u.user,"Psyche value"),searchText:Be([u.title,u.description,u.valuedDirection],u),kind:"value"})),...o.map(u=>({value:os("behavior",u.id),label:u.title,description:Ke(u.description,u.user,"Behavior"),searchText:Be([u.title,u.description,u.kind],u),kind:"behavior"})),...c.map(u=>({value:os("belief_entry",u.id),label:u.statement,description:Ke(u.flexibleAlternative||u.originNote,u.user,"Belief"),searchText:Be([u.statement,u.flexibleAlternative,u.originNote],u),kind:"belief"})),...x.map(u=>({value:os("mode_profile",u.id),label:u.title,description:Ke(u.archetype||u.family,u.user,"Mode"),searchText:Be([u.title,u.archetype,u.family,u.persona],u),kind:"mode"}))]].sort((u,f)=>u.label.localeCompare(f.label))}function a1(t){return t.note.links.filter(s=>s.entityType!=="behavior_pattern"&&s.entityType!=="trigger_report").slice(0,2).map(s=>e.jsx(L,{className:"bg-white/[0.08] text-white/68",children:zs(s.entityType)},`${t.note.id}-${s.entityType}-${s.entityId}`))}function n1(){var H,me,y,P,q,pe,ee,Y;const t=ut(),s=We(),i=Je(),a=Array.isArray(i.selectedUserIds)?i.selectedUserIds:[],n=Mt(a),[r,l]=d.useState(()=>Tn()),[o,c]=d.useState([ml]),[x,v]=d.useState(""),[u,f]=d.useState(!1),[h,m]=d.useState(!1),[b,w]=d.useState({...va,tags:wa(),userId:n}),[M,E]=d.useState(null),D=d.useMemo(()=>oi(r,7),[r]),j=d.useMemo(()=>pm(r),[r]),S=d.useMemo(()=>Array.from({length:24},(R,X)=>X),[]),p=fe({queryKey:["forge-psyche-self-observation-calendar",r.toISOString(),...a],queryFn:()=>Kg({from:r.toISOString(),to:D.toISOString(),userIds:a})}),A=fe({queryKey:["forge-psyche-values",...a],queryFn:()=>ps(a)}),T=fe({queryKey:["forge-psyche-patterns",...a],queryFn:()=>Vs(a)}),k=fe({queryKey:["forge-psyche-behaviors",...a],queryFn:()=>xs(a)}),$=fe({queryKey:["forge-psyche-beliefs",...a],queryFn:()=>As(a)}),g=fe({queryKey:["forge-psyche-modes",...a],queryFn:()=>Es(a)}),C=fe({queryKey:["forge-psyche-reports",...a],queryFn:()=>bi(a)}),F=xe({mutationFn:async R=>{const X=Pn(R.observedAtInput)??new Date().toISOString(),be=Jj([...R.linkedEntityValues.map(Ie=>Xj(Ie)).filter(Vj).map(Ie=>({entityType:Ie.entityType,entityId:Ie.entityId,anchorKey:null})),...R.linkedPatternIds.map(Ie=>({entityType:"behavior_pattern",entityId:Ie,anchorKey:null})),...R.linkedTriggerReportId?[{entityType:"trigger_report",entityId:R.linkedTriggerReportId,anchorKey:null}]:[]]);return R.noteId?Ta(R.noteId,{contentMarkdown:R.contentMarkdown.trim(),author:R.author.trim()||null,tags:Ut(R.tags),userId:R.userId,frontmatter:{observedAt:X},links:be}):$a({contentMarkdown:R.contentMarkdown.trim(),author:R.author.trim()||null,tags:Ut(R.tags),userId:R.userId,frontmatter:{observedAt:X},links:be})},onSuccess:async()=>{m(!1),w({...va,tags:wa(),userId:n}),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-self-observation-calendar"]}),s.invalidateQueries({queryKey:["forge-snapshot"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]})])}}),z=xe({mutationFn:async({noteId:R,frontmatter:X})=>Ta(R,{frontmatter:X}),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-psyche-self-observation-calendar"]})}}),J=xe({mutationFn:R=>Bl(R),onSuccess:async(R,X)=>{b.noteId===X&&(m(!1),w({...va,tags:wa(),userId:n})),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-self-observation-calendar"]}),s.invalidateQueries({queryKey:["forge-snapshot"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]})])}}),O=d.useMemo(()=>{var R;return Ut([ml,...((R=p.data)==null?void 0:R.calendar.availableTags)??[]])},[(H=p.data)==null?void 0:H.calendar.availableTags]),_=d.useMemo(()=>{var R;return t1(((R=T.data)==null?void 0:R.patterns)??[])},[(me=T.data)==null?void 0:me.patterns]),B=d.useMemo(()=>{var R;return s1(((R=C.data)==null?void 0:R.reports)??[])},[(y=C.data)==null?void 0:y.reports]),K=d.useMemo(()=>{var R,X,be,Ie;return i1({goals:i.snapshot.goals,projects:i.snapshot.dashboard.projects,tasks:i.snapshot.tasks,strategies:i.snapshot.strategies,habits:i.snapshot.habits,tags:i.snapshot.tags,values:((R=A.data)==null?void 0:R.values)??[],behaviors:((X=k.data)==null?void 0:X.behaviors)??[],beliefs:((be=$.data)==null?void 0:be.beliefs)??[],modes:((Ie=g.data)==null?void 0:Ie.modes)??[]})},[(P=k.data)==null?void 0:P.behaviors,(q=$.data)==null?void 0:q.beliefs,(pe=g.data)==null?void 0:pe.modes,i.snapshot.dashboard.projects,i.snapshot.goals,i.snapshot.habits,i.snapshot.strategies,i.snapshot.tags,i.snapshot.tasks,(ee=A.data)==null?void 0:ee.values]),Z=i.snapshot.users.filter(R=>a.includes(R.id)),U=a.length===0?"All owners in scope":a.length===1?Nt(Z[0]??null):`${a.length} owners selected`,I=d.useMemo(()=>{var X;return(((X=p.data)==null?void 0:X.calendar.observations)??[]).filter(be=>{var Ie;return!(u&&((Ie=be.note.user)==null?void 0:Ie.kind)!=="human"||x.trim()&&!(be.note.author??"").toLowerCase().includes(x.trim().toLowerCase())||o.length>0&&!o.every(te=>(be.note.tags??[]).some(ce=>ce.toLowerCase()===te.toLowerCase())))})},[x,(Y=p.data)==null?void 0:Y.calendar.observations,u,o]),G=d.useMemo(()=>{const R=new Map;for(const X of I){const be=new Date(X.observedAt),Ie=`${nn(be)}:${be.getHours()}`,te=R.get(Ie)??[];te.push(X),R.set(Ie,te)}for(const X of R.values())X.sort((be,Ie)=>be.observedAt.localeCompare(Ie.observedAt));return R},[I]),W=R=>{w({...va,userId:n,tags:wa(),observedAtInput:R?cu(R.toISOString()):""})},ne=(R,X)=>{const be=new Date(R);be.setHours(X,0,0,0),W(be),m(!0)},de=R=>{w(e1(R,n)),m(!0)},we=async(R,X,be)=>{await z.mutateAsync({noteId:R.note.id,frontmatter:{...R.note.frontmatter,observedAt:Zj(R.observedAt,X,be)}})},Ne=async()=>{const R=await F.mutateAsync(b),X=new URLSearchParams;X.set("create","1"),X.set("sourceObservationNoteId",R.note.id),R.note.userId&&X.set("userId",R.note.userId),t(`/psyche/patterns?${X.toString()}`)};return p.isLoading?e.jsx(It,{}):p.isError?e.jsx(ze,{eyebrow:"Self Observation",error:p.error,onRetry:()=>void p.refetch()}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{title:"Self Observation",titleText:"Self Observation",description:"Map observed notes onto the real week by hour, including handwritten reflections plus rolling movement stays and trips coming from Forge Companion.",badge:`${I.length} visible`,actions:e.jsxs(Q,{onClick:()=>ne(new Date,new Date().getHours()),children:[e.jsx(zt,{className:"size-4"}),"Add observation"]})}),e.jsx(Bt,{}),e.jsxs(ae,{className:"grid gap-4 rounded-[32px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,31,34,0.96),rgba(13,24,27,0.94))]",children:[e.jsx(xm,{eyebrow:"Observation week",description:"Every observed note can live at the hour it actually happened. Filter reflections and movement together, move through weeks, and keep pattern plus trigger links visible on the same card.",weekStart:r,badges:e.jsxs(e.Fragment,{children:[e.jsx(L,{className:"bg-white/[0.08] text-white/74",children:U}),e.jsx(L,{className:"bg-[rgba(110,231,183,0.14)] text-[var(--tertiary)]",children:u?"Human-owned only":"All note owners"})]}),onPrevious:()=>l(oi(r,-7)),onCurrent:()=>l(Tn()),onNext:()=>l(oi(r,7))}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)_auto]",children:[e.jsx(le,{value:x,onChange:R=>v(R.target.value),placeholder:"Filter by free-text author"}),e.jsx(ci,{value:o,onChange:c,availableTags:O,placeholder:"Filter by note tag"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Q,{variant:u?"secondary":"primary",onClick:()=>f(!1),children:"All notes"}),e.jsx(Q,{variant:u?"primary":"ghost",onClick:()=>f(!0),children:"Human only"})]})]})]}),e.jsxs(ae,{className:"overflow-hidden rounded-[32px] border border-white/8 bg-[linear-gradient(180deg,rgba(16,26,34,0.98),rgba(10,18,27,0.96))] p-0",children:[e.jsx("div",{className:"hidden overflow-x-auto lg:block",children:e.jsxs("div",{className:"min-w-[76rem]",children:[e.jsxs("div",{className:"grid grid-cols-[5rem_repeat(7,minmax(10rem,1fr))] border-b border-white/8 bg-[rgba(10,17,29,0.96)]",children:[e.jsx("div",{className:"border-r border-white/8 px-3 py-4 text-[11px] uppercase tracking-[0.18em] text-white/34",children:"Hour"}),j.map(R=>e.jsxs("div",{className:"border-r border-white/8 px-3 py-4 last:border-r-0",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:di(R)}),e.jsx("div",{className:"mt-1 text-xs text-white/42",children:nn(R)})]},R.toISOString()))]}),S.map(R=>e.jsxs("div",{className:"grid grid-cols-[5rem_repeat(7,minmax(10rem,1fr))] border-b border-white/6 last:border-b-0",children:[e.jsx("div",{className:"border-r border-white/8 bg-[rgba(8,14,24,0.8)] px-3 py-4 text-sm text-white/52",children:kd(R)}),j.map(X=>{const Ie=`${nn(X)}:${R}`,te=G.get(Ie)??[];return e.jsx("div",{"data-self-observation-slot":Ie,className:"min-h-[7rem] border-r border-white/6 px-2 py-2 last:border-r-0",onDragOver:ce=>ce.preventDefault(),onDrop:ce=>{ce.preventDefault();const Se=ce.dataTransfer.getData("text/forge-self-observation-id")||M;if(!Se)return;const he=I.find(Ge=>Ge.note.id===Se);he&&(we(he,X,R),E(null))},children:e.jsxs("div",{className:"grid gap-2",children:[te.length>0?e.jsx("div",{className:"flex justify-end",children:e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 rounded-full border border-white/8 bg-white/[0.04] px-2 py-1 text-[11px] text-white/58 transition hover:bg-white/[0.08] hover:text-white",onClick:()=>ne(X,R),children:[e.jsx(zt,{className:"size-3.5"}),"Add"]})}):null,te.map(ce=>e.jsx("div",{draggable:!0,"data-self-observation-card":ce.note.id,onDragStart:Se=>{E(ce.note.id),Se.dataTransfer.setData("text/forge-self-observation-id",ce.note.id)},onDragEnd:()=>E(null),className:re("rounded-[22px] border p-3 text-white transition hover:border-white/18",rn(ce)?"border-[rgba(126,229,255,0.14)] bg-[rgba(126,229,255,0.08)] hover:bg-[rgba(126,229,255,0.12)]":"border-white/10 bg-[rgba(110,231,183,0.08)] hover:bg-[rgba(110,231,183,0.12)]"),children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("button",{type:"button",className:"min-w-0 flex-1 text-left",onClick:()=>de(ce),children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-[rgba(110,231,183,0.82)]",children:Yj(ce.observedAt)}),rn(ce)?e.jsx(L,{className:"bg-cyan-400/12 text-cyan-100",children:"Movement"}):null,e.jsx(Ue,{user:ce.note.user,compact:!0})]}),e.jsx("div",{className:"mt-2 line-clamp-3 text-sm leading-6 text-white/78",children:Ac(ce.note)}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-1.5",children:[ce.note.author?e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:ce.note.author}):null,(ce.note.tags??[]).slice(0,2).map(Se=>e.jsx(L,{className:"bg-cyan-400/10 text-cyan-50",children:Se},`${ce.id}-${Se}`)),a1(ce),ce.linkedPatterns.slice(0,2).map(Se=>e.jsx(Te,{kind:"pattern",label:Se.title,compact:!0,gradient:!1},Se.id)),ce.linkedReports.slice(0,1).map(Se=>e.jsx(Te,{kind:"report",label:Se.title,compact:!0,gradient:!1},Se.id))]})]}),e.jsx("button",{type:"button",className:"rounded-full border border-white/8 bg-white/[0.04] p-2 text-white/54 transition hover:bg-rose-500/18 hover:text-rose-100","aria-label":`Delete observation ${ce.note.id}`,onClick:Se=>{Se.stopPropagation(),J.mutateAsync(ce.note.id)},children:e.jsx(ct,{className:"size-3.5"})})]})},ce.id)),te.length===0?e.jsx("button",{type:"button",className:"rounded-[18px] border border-dashed border-white/8 px-3 py-4 text-left text-sm text-white/34 transition hover:border-white/16 hover:text-white/56",onClick:()=>ne(X,R),children:"Add observation"}):null]})},Ie)})]},R))]})}),e.jsx("div",{className:"grid gap-4 p-4 lg:hidden",children:j.map(R=>{const X=nn(R);return e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.03] p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[18px] bg-[rgba(10,16,30,0.96)] px-3 py-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-white",children:di(R)}),e.jsx("div",{className:"mt-1 text-xs text-white/42",children:X})]}),e.jsxs(Q,{size:"sm",variant:"secondary",onClick:()=>ne(R,new Date().getHours()),children:[e.jsx(zt,{className:"size-4"}),"Add"]})]}),e.jsx("div",{className:"mt-3 grid gap-2",children:S.map(be=>{const Ie=`${X}:${be}`,te=G.get(Ie)??[];return e.jsxs("div",{"data-self-observation-slot-mobile":Ie,className:"rounded-[18px] border border-white/6 bg-white/[0.03] px-3 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.16em] text-white/34",children:kd(be)}),e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 rounded-full border border-white/8 bg-white/[0.04] px-2 py-1 text-[11px] text-white/58 transition hover:bg-white/[0.08] hover:text-white",onClick:()=>ne(R,be),children:[e.jsx(zt,{className:"size-3.5"}),"Add"]})]}),e.jsx("div",{className:"mt-2 grid gap-2",children:te.length===0?e.jsx("button",{type:"button",className:"rounded-[16px] border border-dashed border-white/8 px-3 py-3 text-left text-sm text-white/38 transition hover:border-white/16 hover:text-white/56",onClick:()=>ne(R,be),children:"Add observation"}):te.map(ce=>e.jsx("div",{className:re("rounded-[16px] p-3",rn(ce)?"bg-[rgba(126,229,255,0.1)]":"bg-[rgba(110,231,183,0.1)]"),children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("button",{type:"button",className:"min-w-0 flex-1 text-left",onClick:()=>de(ce),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[rn(ce)?e.jsx(L,{className:"bg-cyan-400/12 text-cyan-100",children:"Movement"}):null,e.jsx(Ue,{user:ce.note.user,compact:!0}),ce.linkedPatterns.slice(0,1).map(Se=>e.jsx(Te,{kind:"pattern",label:Se.title,compact:!0,gradient:!1},Se.id)),ce.linkedReports.slice(0,1).map(Se=>e.jsx(Te,{kind:"report",label:Se.title,compact:!0,gradient:!1},Se.id))]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/78",children:Ac(ce.note)})]}),e.jsx("button",{type:"button",className:"rounded-full border border-white/8 bg-white/[0.04] p-2 text-white/54 transition hover:bg-rose-500/18 hover:text-rose-100","aria-label":`Delete observation ${ce.note.id}`,onClick:()=>void J.mutateAsync(ce.note.id),children:e.jsx(ct,{className:"size-3.5"})})]})},ce.id))})]},Ie)})})]},X)})})]}),e.jsx(bs,{open:h,onOpenChange:m,eyebrow:"Self Observation",title:b.noteId?"Edit observation":"Add observation",description:"Capture the note, set the exact observation time, then attach the pattern, trigger report, and any other Forge records that belong to that moment.",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsx(ss,{value:b.userId,users:i.snapshot.users,onChange:R=>w(X=>({...X,userId:R})),defaultLabel:ts(i.snapshot.users.find(R=>R.id===n)??null,"Choose observation owner"),help:"Observation notes stay multi-user aware just like the rest of Forge."}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-white",children:"Author"}),e.jsx(le,{value:b.author,onChange:R=>w(X=>({...X,author:R.target.value})),placeholder:"Albert"})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-white",children:"Observed at"}),e.jsx(le,{type:"datetime-local",value:b.observedAtInput,onChange:R=>w(X=>({...X,observedAtInput:R.target.value}))})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-white",children:"Observation note"}),e.jsx(Me,{value:b.contentMarkdown,onChange:R=>w(X=>({...X,contentMarkdown:R.target.value})),className:"min-h-[14rem]",placeholder:"What happened in this hour, what did you notice, and what mattered?"})]}),e.jsx(ci,{value:b.tags,onChange:R=>w(X=>({...X,tags:R})),availableTags:O,placeholder:"Add note tags for the observation"}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Linked patterns"}),e.jsxs("button",{type:"button",className:"inline-flex items-center gap-2 rounded-full bg-white/[0.06] px-3 py-1.5 text-xs text-white/72 transition hover:bg-white/[0.1] hover:text-white",onClick:()=>void Ne(),disabled:F.isPending||b.contentMarkdown.trim().length===0,children:[e.jsx(Tt,{className:"size-3.5"}),"Create pattern from observation"]})]}),e.jsx(et,{options:_,selectedValues:b.linkedPatternIds,onChange:R=>w(X=>({...X,linkedPatternIds:R})),placeholder:"Search patterns in scope",emptyMessage:"No patterns in scope yet."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Trigger report"}),e.jsxs("button",{type:"button",className:"inline-flex items-center gap-2 rounded-full bg-white/[0.06] px-3 py-1.5 text-xs text-white/72 transition hover:bg-white/[0.1] hover:text-white",onClick:()=>{const R=new URLSearchParams;R.set("create","1"),b.observedAtInput&&R.set("occurredAt",Pn(b.observedAtInput)??new Date().toISOString()),b.userId&&R.set("userId",b.userId),t(`/psyche/reports?${R.toString()}`),m(!1)},children:[e.jsx(Tt,{className:"size-3.5"}),"Create report from time"]})]}),e.jsx(et,{options:B,selectedValues:b.linkedTriggerReportId?[b.linkedTriggerReportId]:[],onChange:R=>w(X=>({...X,linkedTriggerReportId:R.at(-1)??null})),placeholder:"Search trigger reports in scope",emptyMessage:"No trigger reports in scope yet."})]})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Linked records"}),e.jsx(et,{options:K,selectedValues:b.linkedEntityValues,onChange:R=>w(X=>({...X,linkedEntityValues:R})),placeholder:"Link goals, projects, tasks, values, beliefs, modes, or other Forge records",emptyMessage:"No linked records in scope yet."})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-white/70",children:[e.jsx(ah,{className:"size-4 text-[var(--tertiary)]"}),"Cards appear in the hourly week grid at the exact observation time, whether they came from deliberate reflection or rolling movement sync."]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/52",children:"Move them later by drag-and-drop, edit the timestamp directly here, or delete them from the card itself when the observation should not stay on the calendar."})]}),e.jsxs("div",{className:"flex flex-wrap justify-between gap-3",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[b.noteId?e.jsxs(Q,{variant:"secondary",pending:J.isPending,pendingLabel:"Deleting",onClick:()=>b.noteId?void J.mutateAsync(b.noteId):void 0,children:[e.jsx(ct,{className:"size-4"}),"Delete observation"]}):null,b.linkedTriggerReportId?e.jsxs("button",{type:"button",className:"inline-flex items-center gap-2 rounded-full bg-white/[0.06] px-3 py-2 text-sm text-white/72 transition hover:bg-white/[0.1] hover:text-white",onClick:()=>t(`/psyche/reports/${b.linkedTriggerReportId}`),children:[e.jsx(Ms,{className:"size-4"}),"Open linked report"]}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Q,{variant:"secondary",onClick:()=>m(!1),children:"Cancel"}),e.jsx(Q,{pending:F.isPending,pendingLabel:"Saving",disabled:b.contentMarkdown.trim().length===0,onClick:()=>void F.mutateAsync(b),children:"Save observation"})]})]})]})})]})}const ma={schemaId:null,statement:"",beliefType:"absolute",originNote:"",confidence:60,evidenceFor:[],evidenceAgainst:[],flexibleAlternative:"",linkedValueIds:[],linkedBehaviorIds:[],linkedModeIds:[],linkedReportIds:[],userId:null};function Fr(t){return{schemaId:t.schemaId,statement:t.statement,beliefType:t.beliefType,originNote:t.originNote,confidence:t.confidence,evidenceFor:t.evidenceFor,evidenceAgainst:t.evidenceAgainst,flexibleAlternative:t.flexibleAlternative,linkedValueIds:t.linkedValueIds,linkedBehaviorIds:t.linkedBehaviorIds,linkedModeIds:t.linkedModeIds,linkedReportIds:t.linkedReportIds,userId:t.userId??null}}function r1({schema:t,beliefs:s,behaviors:i,reports:a}){const n=s.filter(o=>o.schemaId===t.id).length,r=i.filter(o=>o.linkedSchemaIds.includes(t.id)).length,l=a.filter(o=>o.schemaLinks.some(c=>{const x=Xi(c,[t]);return(x==null?void 0:x.id)===t.id})).length;return{beliefCount:n,behaviorCount:r,reportCount:l,total:n+r+l}}function Ec({title:t,description:s,titleHelp:i,schemas:a,beliefs:n,behaviors:r,reports:l,onOpenBelief:o}){if(a.length===0)return null;const c=Gi(a[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}),i?e.jsx(it,{content:i,label:`Explain ${t.toLowerCase()}`}):null]}),e.jsx("div",{className:"max-w-3xl text-sm leading-6 text-white/60",children:s})]}),e.jsxs(L,{children:[a.length," schemas"]})]}),e.jsx("div",{className:"grid gap-4 xl:grid-cols-2",children:a.map(x=>{const v=r1({schema:x,beliefs:n,behaviors:r,reports:l}),u=n.filter(h=>h.schemaId===x.id),f=Gi(x.schemaType);return e.jsxs("div",{className:`min-w-0 rounded-[26px] border p-5 ${f.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(Ws,{label:x.title,schemaType:x.schemaType}),e.jsx("div",{className:"mt-3 text-sm text-white/46",children:go(x.family)}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/62",children:x.description})]}),e.jsxs(L,{children:[v.total," ",f.countLabel]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsxs(L,{className:"bg-white/[0.06] text-white/68",children:[v.beliefCount," beliefs"]}),e.jsxs(L,{className:"bg-white/[0.06] text-white/68",children:[v.behaviorCount," behaviors"]}),e.jsxs(L,{className:"bg-white/[0.06] text-white/68",children:[v.reportCount," reports"]})]}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[u.length>0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] p-4 text-sm text-white/58",children:`${u.length} ${f.linkSummary}${u.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:f.emptyCopy}),u.slice(0,2).map(h=>e.jsxs("button",{type:"button",className:"rounded-[20px] bg-white/[0.04] p-4 text-left transition hover:bg-white/[0.08]",onClick:()=>o(h),children:[e.jsx("div",{className:"font-medium text-white",children:h.statement}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:h.flexibleAlternative||"No flexible alternative recorded yet."})]},h.id))]})]},x.id)})})]})}function l1(){var ne,de,we,Ne,H,me;const t=Je(),s=We(),[i,a]=Pt(),[n,r]=d.useState(!1),[l,o]=d.useState(null),[c,x]=d.useState(ma),[v,u]=d.useState(null),f=fe({queryKey:["forge-psyche-schema-catalog"],queryFn:La}),h=fe({queryKey:["forge-psyche-beliefs"],queryFn:As}),m=fe({queryKey:["forge-psyche-behaviors"],queryFn:xs}),b=fe({queryKey:["forge-psyche-modes"],queryFn:Es}),w=fe({queryKey:["forge-psyche-values"],queryFn:ps}),M=fe({queryKey:["forge-psyche-reports"],queryFn:bi}),E=((ne=f.data)==null?void 0:ne.schemas)??[],D=((de=h.data)==null?void 0:de.beliefs)??[],j=((we=m.data)==null?void 0:we.behaviors)??[],S=((Ne=b.data)==null?void 0:Ne.modes)??[],p=((H=w.data)==null?void 0:H.values)??[],A=((me=M.data)==null?void 0:me.reports)??[],T=Mt(t.selectedUserIds),k=i.get("focus"),$=t.snapshot.dashboard.notesSummaryByEntity;ta(k),d.useEffect(()=>{if(i.get("create")==="1"){r(!0),o(null),x({...ma,userId:T});const y=new URLSearchParams(i);y.delete("create"),a(y,{replace:!0})}},[T,i,a]);const g=xe({mutationFn:async y=>{const P=Nc.parse(y);return l?xg(l.id,P):ql(P)},onSuccess:async()=>{r(!1),o(null),x({...ma,userId:T}),u(null),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-beliefs"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]})])}}),C=p.map(y=>({value:y.id,label:st(y.title,y.user),description:Ke(y.valuedDirection,y.user),searchText:Be([y.title,y.valuedDirection,y.description],y),kind:"value"})),F=j.map(y=>({value:y.id,label:st(y.title,y.user),description:Ke(y.kind,y.user),searchText:Be([y.title,y.kind,y.description],y),kind:"behavior"})),z=S.map(y=>({value:y.id,label:st(y.title,y.user),description:Ke(y.archetype||y.family,y.user),searchText:Be([y.title,y.archetype,y.family,y.persona],y),kind:"mode"})),J=A.map(y=>({value:y.id,label:st(y.title,y.user),description:Ke(y.customEventType||y.eventSituation,y.user),searchText:Be([y.title,y.customEventType,y.eventSituation],y),kind:"report"})),O=d.useMemo(()=>new Map(E.map(y=>[y.id,y])),[E]),_=d.useMemo(()=>E.filter(y=>y.schemaType==="maladaptive"),[E]),B=d.useMemo(()=>E.filter(y=>y.schemaType==="adaptive"),[E]),K=async y=>{const{value:P}=await ea({title:y,description:"",valuedDirection:y,whyItMatters:"",linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],committedActions:[],userId:c.userId});return At(s,["forge-psyche-values"],"values",P),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:P.id,label:P.title,description:P.valuedDirection,kind:"value"}},Z=async y=>{const{behavior:P}=await Hn({kind:"away",title:y,description:"",commonCues:[],urgeStory:"",shortTermPayoff:"",longTermCost:"",replacementMove:"",repairPlan:"",linkedPatternIds:[],linkedValueIds:[],linkedSchemaIds:[],linkedModeIds:[],userId:c.userId});return At(s,["forge-psyche-behaviors"],"behaviors",P),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:P.id,label:P.title,description:P.kind,kind:"behavior"}},U=async y=>{const{mode:P}=await Da({family:"coping",archetype:"",title:y,persona:"",imagery:"",symbolicForm:"",facialExpression:"",fear:"",burden:"",protectiveJob:"",originContext:"",firstAppearanceAt:null,linkedPatternIds:[],linkedBehaviorIds:[],linkedValueIds:[],userId:c.userId});return At(s,["forge-psyche-modes"],"modes",P),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:P.id,label:P.title,description:P.archetype||P.family,kind:"mode"}},I=async y=>{const{report:P}=await $h({title:y,status:"draft",eventTypeId:null,customEventType:"",eventSituation:y,occurredAt:null,emotions:[],thoughts:[],behaviors:[],consequences:{selfShortTerm:[],selfLongTerm:[],othersShortTerm:[],othersLongTerm:[]},linkedPatternIds:[],linkedValueIds:[],linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],linkedBehaviorIds:[],linkedBeliefIds:[],linkedModeIds:[],modeOverlays:[],schemaLinks:[],modeTimeline:[],nextMoves:[],userId:c.userId});return At(s,["forge-psyche-reports"],"reports",P),await s.invalidateQueries({queryKey:["forge-psyche-overview"]}),{value:P.id,label:P.title,description:P.customEventType||P.eventSituation,kind:"report"}};d.useEffect(()=>{n&&u(null)},[n]);const G=[{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:(y,P)=>e.jsxs(e.Fragment,{children:[e.jsx(ss,{value:y.userId??null,users:t.snapshot.users,onChange:q=>P({userId:q}),defaultLabel:ts(t.snapshot.users.find(q=>q.id===T)??null,"Choose belief owner"),help:"Beliefs can belong to a human or bot user even when they connect to shared behaviors, modes, and reports."}),e.jsx(se,{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:_,description:"Recurring old patterns that tend to get activated and distort how the situation feels.",schemaType:"maladaptive"},{title:"Adaptive schemas",schemas:B,description:"Healthier stable themes you want to strengthen, trust, and live from more often.",schemaType:"adaptive"}].map(q=>{const pe=Gi(q.schemaType);return e.jsxs("div",{className:`rounded-[24px] border p-4 ${pe.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(it,{content:ka(q.schemaType),label:`Explain ${ar(q.schemaType)}`})]}),e.jsx(Hs,{className:"mt-2",children:q.description}),e.jsx("div",{className:"mt-4 grid gap-2 sm:flex sm:flex-wrap",children:q.schemas.map(ee=>{const Y=y.schemaId===ee.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 ${Y?`${pe.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:()=>P({schemaId:ee.id}),children:ee.title},ee.id)})})]},q.schemaType)})})}),e.jsx(se,{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(le,{value:y.statement,onChange:q=>P({statement:q.target.value}),placeholder:"If they go quiet, I am already being left."})}),e.jsx(se,{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 ${y.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:()=>P({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:(y,P)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Origin context",description:"Capture where this script learned its force or usefulness.",children:e.jsx(Me,{value:y.originNote,onChange:q=>P({originNote:q.target.value}),placeholder:"It got stronger in periods where silence usually meant anger, distance, or punishment."})}),e.jsxs(se,{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:y.confidence,onChange:q=>P({confidence:Number(q.target.value)})}),e.jsxs("div",{className:"text-sm text-white/48",children:[y.confidence,"% grip"]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(se,{label:"Evidence for",description:"Add one supporting memory, sign, or interpretation per line.",children:e.jsx(Me,{value:y.evidenceFor.join(`
|
|
23
|
-
`),onChange:q=>P({evidenceFor:q.target.value.split(`
|
|
24
|
-
`).map(pe=>pe.trim()).filter(Boolean)}),placeholder:`One line per sign
|
|
25
|
-
They stopped replying for days
|
|
26
|
-
I was ignored when I asked directly`})}),e.jsx(se,{label:"Evidence against",description:"Add one counterexample, nuance, or disconfirming sign per line.",children:e.jsx(Me,{value:y.evidenceAgainst.join(`
|
|
27
|
-
`),onChange:q=>P({evidenceAgainst:q.target.value.split(`
|
|
28
|
-
`).map(pe=>pe.trim()).filter(Boolean)}),placeholder:`One line per counterpoint
|
|
29
|
-
They later explained they were overwhelmed
|
|
30
|
-
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:(y,P)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{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(Me,{value:y.flexibleAlternative,onChange:q=>P({flexibleAlternative:q.target.value}),placeholder:"Silence can mean many things. I can check the facts before deciding I am being left."})}),e.jsx(se,{label:"Linked values",description:"Choose the valued directions this belief interferes with most.",children:e.jsx(et,{options:C,selectedValues:y.linkedValueIds,onChange:q=>P({linkedValueIds:q}),placeholder:"Search or create a value…",emptyMessage:"No values match yet.",createLabel:"Create value",onCreate:K})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(se,{label:"Linked behaviors",description:"Choose the moves this belief tends to trigger or justify.",children:e.jsx(et,{options:F,selectedValues:y.linkedBehaviorIds,onChange:q=>P({linkedBehaviorIds:q}),placeholder:"Search or create a behavior…",emptyMessage:"No behaviors match yet.",createLabel:"Create behavior",onCreate:Z})}),e.jsx(se,{label:"Linked modes",description:"Choose the inner states that most often carry this script.",children:e.jsx(et,{options:z,selectedValues:y.linkedModeIds,onChange:q=>P({linkedModeIds:q}),placeholder:"Search or create a mode…",emptyMessage:"No modes match yet.",createLabel:"Create mode",onCreate:U})}),e.jsx(se,{label:"Linked reports",description:"Choose the reflective chains where this script has already shown up.",children:e.jsx(et,{options:J,selectedValues:y.linkedReportIds,onChange:q=>P({linkedReportIds:q}),placeholder:"Search or create a report…",emptyMessage:"No reports match yet.",createLabel:"Create report",onCreate:I})})]})]})}];if(f.isLoading||h.isLoading||m.isLoading||b.isLoading||w.isLoading||M.isLoading)return e.jsx(nt,{eyebrow:"Schemas & beliefs",title:"Loading schemas and beliefs",description:"Getting schemas, beliefs, behaviors, modes, values, and linked reports ready."});const W=f.error??h.error??m.error??b.error??w.error??M.error;return W?e.jsx(ze,{eyebrow:"Schemas & beliefs",error:W,onRetry:()=>void Promise.all([f.refetch(),h.refetch(),m.refetch(),b.refetch(),w.refetch(),M.refetch()])}):e.jsxs("div",{className:"grid min-w-0 gap-5",children:[e.jsx(qe,{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:`${D.length} beliefs`,actions:e.jsx(Q,{onClick:()=>{o(null),x({...ma,userId:T}),r(!0)},children:"Add belief"})}),e.jsx(Bt,{}),e.jsxs("section",{className:"grid min-w-0 gap-5 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]",children:[e.jsx(Ps,{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:E.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(Ec,{title:"Maladaptive schemas",titleHelp:ka("maladaptive"),description:"These schemas describe recurring old patterns that can change how you read situations and react.",schemas:_,beliefs:D,behaviors:j,reports:A,onOpenBelief:y=>{o(y),x(Fr(y)),r(!0)}}),e.jsx(Ec,{title:"Adaptive schemas",titleHelp:ka("adaptive"),description:"These schemas describe healthier patterns you want to trust, practice, and strengthen over time.",schemas:B,beliefs:D,behaviors:j,reports:A,onOpenBelief:y=>{o(y),x(Fr(y)),r(!0)}})]})}),e.jsx(Ps,{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(Q,{onClick:()=>{o(null),x({...ma,userId:T}),r(!0)},children:"Add belief"}),D.length===0?e.jsx("div",{className:"text-sm text-white/56",children:"Your beliefs will appear here after you add the first one."}):D.map(y=>{const P=y.schemaId?O.get(y.schemaId)??null:null,q=k===y.id;return e.jsxs("div",{"data-psyche-focus-id":y.id,className:`rounded-[24px] border border-white/8 bg-white/[0.04] p-4 text-left transition hover:bg-white/[0.08] ${sa(q)}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:y.statement}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[y.user?e.jsx(Ue,{user:y.user,compact:!0}):null,e.jsx(Vt,{entityType:"belief_entry",entityId:y.id,count:is($,"belief_entry",y.id).count}),e.jsxs(L,{children:[y.confidence,"% grip"]}),e.jsx(Q,{variant:"secondary",size:"sm",onClick:()=>{o(y),x(Fr(y)),r(!0)},children:"Edit"})]})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:y.flexibleAlternative||"No flexible alternative recorded yet."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[P?e.jsx(Ws,{label:P.title,schemaType:P.schemaType,compact:!0,showType:!0}):null,S.filter(pe=>y.linkedModeIds.includes(pe.id)).slice(0,2).map(pe=>e.jsx(Te,{kind:"mode",label:pe.title,compact:!0},pe.id))]})]},y.id)})]})})]}),e.jsx(rt,{open:n,onOpenChange:r,eyebrow:"Belief",title:l?"Refine belief":"Create belief",description:"Use this guided flow to capture the belief, what seems to support it, and a more flexible alternative.",value:c,onChange:x,steps:G,submitLabel:l?"Save belief":"Create belief",pending:g.isPending,error:v,onSubmit:async()=>{u(null);const y=Nc.safeParse(c);if(!y.success){u("This belief still needs a statement before it can be saved.");return}try{await g.mutateAsync(y.data)}catch(P){u(P instanceof Error?P.message:"Unable to save this belief right now.")}}})]})}const Ci={title:"",description:"",valuedDirection:"",whyItMatters:"",linkedGoalIds:[],linkedProjectIds:[],linkedTaskIds:[],committedActions:[],userId:null};function _r(t,s){return t.includes(s)?t.filter(i=>i!==s):[...t,s]}function o1(t){return{title:t.title,description:t.description,valuedDirection:t.valuedDirection,whyItMatters:t.whyItMatters,linkedGoalIds:t.linkedGoalIds,linkedProjectIds:t.linkedProjectIds,linkedTaskIds:t.linkedTaskIds,committedActions:t.committedActions,userId:t.userId??null}}function d1(){var j;const t=Je(),s=We(),[i,a]=Pt(),[n,r]=d.useState(!1),[l,o]=d.useState(null),[c,x]=d.useState(Ci),[v,u]=d.useState(null),f=fe({queryKey:["forge-psyche-values"],queryFn:ps}),h=((j=f.data)==null?void 0:j.values)??[],m=Mt(t.selectedUserIds),b=i.get("focus"),w=t.snapshot.dashboard.notesSummaryByEntity;ta(b),d.useEffect(()=>{if(i.get("create")==="1"){r(!0),o(null),x({...Ci,userId:m});const S=new URLSearchParams(i);S.delete("create"),a(S,{replace:!0})}},[m,i,a]);const M=xe({mutationFn:async S=>{const p=wc.parse(S);return l?mg(l.id,p):ea(p)},onSuccess:async()=>{r(!1),o(null),x({...Ci,userId:m}),u(null),await Promise.all([s.invalidateQueries({queryKey:["forge-psyche-values"]}),s.invalidateQueries({queryKey:["forge-psyche-overview"]})])}}),E=d.useMemo(()=>h.slice(0,5).map((S,p)=>({id:S.id,label:`${S.linkedGoalIds.length} goals`,title:S.title,detail:S.valuedDirection,href:`/psyche/values?focus=${S.id}#values-atlas`,angle:-90+p*68,radius:150+p%2*20,tone:["mint","sky","violet","rose"][p%4]})),[h]),D=[{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:(S,p)=>e.jsxs(e.Fragment,{children:[e.jsx(ss,{value:S.userId??null,users:t.snapshot.users,onChange:A=>p({userId:A}),defaultLabel:ts(t.snapshot.users.find(A=>A.id===m)??null,"Choose value owner"),help:"Values can belong to a human or bot user while still linking to goals, projects, and tasks across Forge."}),e.jsx(se,{label:"Value name",children:e.jsx(le,{value:S.title,onChange:A=>p({title:A.target.value}),placeholder:"Repair with steadiness"})}),e.jsx(se,{label:"Valued direction",children:e.jsx(le,{value:S.valuedDirection,onChange:A=>p({valuedDirection:A.target.value}),placeholder:"Warm, brave, and honest connection"})}),e.jsx(se,{label:"Why it matters",children:e.jsx(Me,{value:S.whyItMatters,onChange:A=>p({whyItMatters:A.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:(S,p)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Description",children:e.jsx(Me,{value:S.description,onChange:A=>p({description:A.target.value}),placeholder:"Describe what this value looks like in daily behavior, not just in theory."})}),e.jsx(se,{label:"Committed action ideas",children:e.jsx(Me,{value:S.committedActions.join(`
|
|
31
|
-
`),onChange:A=>p({committedActions:A.target.value.split(`
|
|
32
|
-
`).map(T=>T.trim()).filter(Boolean)}),placeholder:`One line per action
|
|
33
|
-
Text your sister before Friday
|
|
34
|
-
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:(S,p)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Linked goals",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:t.snapshot.goals.map(A=>{const T=S.linkedGoalIds.includes(A.id);return e.jsx("button",{type:"button",className:`rounded-full px-2.5 py-2 text-sm transition ${ja("goal",T)}`,onClick:()=>p({linkedGoalIds:_r(S.linkedGoalIds,A.id)}),children:e.jsx(Te,{kind:"goal",label:A.title,compact:!0,gradient:!1})},A.id)})})}),e.jsx(se,{label:"Linked projects",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:t.snapshot.dashboard.projects.map(A=>{const T=S.linkedProjectIds.includes(A.id);return e.jsx("button",{type:"button",className:`rounded-full px-2.5 py-2 text-sm transition ${ja("project",T)}`,onClick:()=>p({linkedProjectIds:_r(S.linkedProjectIds,A.id)}),children:e.jsx(Te,{kind:"project",label:A.title,compact:!0,gradient:!1})},A.id)})})}),e.jsx(se,{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(A=>{const T=S.linkedTaskIds.includes(A.id);return e.jsx("button",{type:"button",className:`rounded-full px-2.5 py-2 text-sm transition ${ja("task",T)}`,onClick:()=>p({linkedTaskIds:_r(S.linkedTaskIds,A.id)}),children:e.jsx(Te,{kind:"task",label:A.title,compact:!0,gradient:!1})},A.id)})})})]})}];return f.isLoading?e.jsx(nt,{eyebrow:"Psyche values",title:"Loading value constellation",description:"Hydrating values, linked goals, projects, and tasks."}):f.isError?e.jsx(ze,{eyebrow:"Psyche values",error:f.error,onRetry:()=>void f.refetch()}):e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{entityKind:"value",title:e.jsx(Xe,{kind:"value",label:"Values",variant:"heading",size:"lg"}),description:"Map values as living anchors. Each one should visibly relate to goals, projects, and tasks so reflection stops feeling separate from the rest of life.",badge:`${h.length} values`,actions:e.jsx(Q,{onClick:()=>{o(null),x({...Ci,userId:m}),r(!0)},children:"Add value"})}),e.jsx(Bt,{}),e.jsx(au,{title:"Place values inside the wider life system",description:"Values are not just notes. This constellation shows which directions are already attached to real goals, projects, and concrete tasks.",centerLabel:"Value field",centerValue:`${h.length} mapped`,nodes:E,action:e.jsx(Q,{onClick:()=>{o(null),x({...Ci,userId:m}),r(!0)},children:"Add value"})}),e.jsx(Ps,{eyebrow:"Values in context",title:"See why each value matters and where it lives",description:"Each card combines the value narrative with its linked goals, projects, tasks, and committed actions so you can understand the shape immediately.",tone:"mint",className:"scroll-mt-24",children:e.jsx("div",{id:"values-atlas",className:"grid gap-4",children:h.length===0?e.jsx("div",{className:"flex justify-start",children:e.jsx(Q,{onClick:()=>{o(null),x({...Ci,userId:m}),r(!0)},children:"Add value"})}):h.map(S=>{const p=t.snapshot.goals.filter(g=>S.linkedGoalIds.includes(g.id)),A=t.snapshot.dashboard.projects.filter(g=>S.linkedProjectIds.includes(g.id)),T=t.snapshot.tasks.filter(g=>S.linkedTaskIds.includes(g.id)),k=b===S.id,$=is(w,"psyche_value",S.id).count;return e.jsxs("div",{"data-psyche-focus-id":S.id,className:`rounded-[26px] border border-white/8 bg-white/[0.04] p-5 transition ${sa(k)}`,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(Xe,{kind:"value",label:S.title,variant:"heading",size:"xl"}),e.jsx("div",{className:"mt-2 text-sm text-[var(--tertiary)]",children:S.valuedDirection})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[S.user?e.jsx(Ue,{user:S.user,compact:!0}):null,e.jsx(Vt,{entityType:"psyche_value",entityId:S.id,count:$}),e.jsx(Q,{variant:"secondary",onClick:()=>{o(S),x(o1(S)),r(!0)},children:"Edit"})]})]}),e.jsx("p",{className:"mt-4 max-w-3xl text-sm leading-7 text-white/60",children:S.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:S.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:p.length===0?e.jsx("span",{className:"text-sm text-white/44",children:"None linked"}):p.map(g=>e.jsx(Te,{kind:"goal",label:g.title,compact:!0},g.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:A.length===0?e.jsx("span",{className:"text-sm text-white/44",children:"None linked"}):A.map(g=>e.jsx(Te,{kind:"project",label:g.title,compact:!0},g.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:T.length===0?e.jsx("span",{className:"text-sm text-white/44",children:"None linked"}):T.slice(0,4).map(g=>e.jsx(Te,{kind:"task",label:g.title,compact:!0},g.id))})]})]})]}),e.jsx("div",{className:"mt-4 grid gap-2 md:grid-cols-2",children:S.committedActions.map(g=>e.jsx("div",{className:"rounded-[18px] bg-[rgba(110,231,183,0.08)] px-4 py-3 text-sm text-white/72",children:g},g))})]},S.id)})})}),e.jsx(rt,{open:n,onOpenChange:r,eyebrow:"Value",title:l?"Refine value placement":"Create value",description:"Forge should capture values through guided placement, not a raw admin form.",value:c,onChange:x,steps:D,submitLabel:l?"Save value":"Create value",pending:M.isPending,error:v,onSubmit:async()=>{u(null);const S=wc.safeParse(c);if(!S.success){u("This value still needs a title and valued direction before it can be saved.");return}try{await M.mutateAsync(S.data)}catch(p){u(p instanceof Error?p.message:"Unable to save this value right now.")}}})]})}function Rr({theme:t,title:s,description:i}){return e.jsx("div",{className:"overflow-hidden rounded-[24px] border border-white/10",style:{background:`linear-gradient(180deg, ${t.panelHigh}, ${t.panelLow})`,color:t.ink},children:e.jsxs("div",{className:"px-4 py-4",style:{background:`radial-gradient(circle at top left, ${t.primary}33, transparent 42%), radial-gradient(circle at top right, ${t.secondary}2a, transparent 36%), linear-gradient(180deg, ${t.panel}, ${t.canvas})`},children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.2em] opacity-60",children:"Preview"}),e.jsx("div",{className:"mt-2 font-display text-xl",children:s}),e.jsx("div",{className:"mt-2 text-sm leading-6 opacity-72",children:i}),e.jsx("div",{className:"mt-5 flex gap-2",children:[t.primary,t.secondary,t.tertiary,t.panelHigh].map(a=>e.jsx("div",{className:"h-9 flex-1 rounded-[14px] border border-black/10",style:{background:a}},a))})]})})}function _s({label:t,value:s,onChange:i,description:a}){return e.jsx(se,{label:t,description:a,children:e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[5.5rem_minmax(0,1fr)]",children:[e.jsx("input",{type:"color",value:s,onChange:n=>i(n.target.value),className:"h-12 w-full cursor-pointer rounded-[18px] border border-white/10 bg-transparent p-1"}),e.jsx(le,{value:s,onChange:n=>i(n.target.value),placeholder:"#7cc7ff"})]})})}function c1({open:t,onOpenChange:s,value:i,onSave:a}){const[n,r]=d.useState(i),[l,o]=d.useState(""),[c,x]=d.useState(null),v=d.useRef(null),u=b=>{const w=Zr.parse(JSON.parse(b));r(w),o(JSON.stringify(w,null,2)),x(null)},f=b=>{const w=im(b);r({...w,label:n.label.trim().length>0?n.label:`${w.label} Custom`})},h=async b=>{var M;const w=(M=b.target.files)==null?void 0:M[0];if(w)try{u(await w.text())}catch(E){x(E instanceof Error?E.message:"Forge could not parse that JSON theme.")}finally{b.target.value=""}},m=[{id:"identity",eyebrow:"Custom theme",title:"Name the mood and choose a starting point",description:"Start from a Forge preset, then tune the accents and surfaces in the next steps.",render:(b,w)=>e.jsxs("div",{className:"grid gap-5",children:[e.jsx(se,{label:"Theme label",description:"This label appears in Settings when the custom theme is active.",children:e.jsx(le,{value:b.label,onChange:M=>w({label:M.target.value}),placeholder:"Midnight Circuit"})}),e.jsx(se,{label:"Starter preset",children:e.jsx(Ze,{value:"",onChange:M=>f(M),options:Object.entries(cs).map(([M,E])=>({value:M,label:E.label,description:E.description})),columns:2})}),e.jsx(Rr,{theme:b,title:b.label,description:"Live preview of the current custom theme draft."})]})},{id:"accents",eyebrow:"Custom theme",title:"Set the accent colors",description:"These colors drive buttons, highlights, charts, and the ambient shell lighting.",render:(b,w)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(_s,{label:"Primary",description:"Main emphasis color for actions and active state.",value:b.primary,onChange:M=>w({primary:M})}),e.jsx(_s,{label:"Secondary",description:"Support accent for positive or secondary emphasis.",value:b.secondary,onChange:M=>w({secondary:M})}),e.jsx(_s,{label:"Tertiary",description:"Warm contrast color for warnings, highlights, and supporting metrics.",value:b.tertiary,onChange:M=>w({tertiary:M})})]})},{id:"surfaces",eyebrow:"Custom theme",title:"Tune the shell surfaces",description:"Forge currently assumes a dark shell, so these should remain fairly deep colors for legibility.",render:(b,w)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(_s,{label:"Canvas",description:"Primary app background.",value:b.canvas,onChange:M=>w({canvas:M})}),e.jsx(_s,{label:"Panel",description:"Default card and rail background.",value:b.panel,onChange:M=>w({panel:M})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(_s,{label:"Panel high",description:"Raised highlights and stronger sections.",value:b.panelHigh,onChange:M=>w({panelHigh:M})}),e.jsx(_s,{label:"Panel low",description:"Lower contrast and deeper card areas.",value:b.panelLow,onChange:M=>w({panelLow:M})})]}),e.jsx(_s,{label:"Ink",description:"Main text and readable foreground color.",value:b.ink,onChange:M=>w({ink:M})}),e.jsx(Rr,{theme:b,title:b.label,description:"Live preview after the current surface edits."})]})},{id:"import",eyebrow:"Custom theme",title:"Import or paste JSON directly",description:"You can skip the picker workflow entirely by uploading a JSON file or pasting a valid theme object.",render:b=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(se,{label:"Direct JSON",description:"Paste a full custom theme object, then click Apply JSON.",children:e.jsx(Me,{value:l,onChange:w=>o(w.target.value),className:"min-h-52 font-mono text-[13px] leading-6",placeholder:JSON.stringify(Pa,null,2)})}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(Q,{type:"button",variant:"secondary",onClick:()=>{try{u(l)}catch(w){x(w instanceof Error?w.message:"Forge could not parse that JSON theme.")}},children:"Apply JSON"}),e.jsx(Q,{type:"button",variant:"ghost",onClick:()=>{var w;return(w=v.current)==null?void 0:w.click()},children:"Upload JSON file"}),e.jsx("input",{ref:v,type:"file",accept:"application/json,.json",className:"hidden",onChange:h})]}),e.jsx(Rr,{theme:b,title:b.label,description:"Preview of the theme that will be saved if you submit now."})]})}];return e.jsx(rt,{open:t,onOpenChange:b=>{b&&(r(i),o(""),x(null)),s(b)},eyebrow:"Settings",title:"Forge custom theme",description:"Build a dark Forge palette visually, or import one directly as JSON.",value:n,onChange:b=>{r(b),x(null)},steps:m,error:c,onSubmit:async()=>{try{const b=Zr.parse(n);a(b),s(!1)}catch(b){x(b instanceof Error?b.message:"Forge could not save that custom theme.")}},submitLabel:"Save custom theme",contentClassName:"lg:w-[min(62rem,calc(100vw-1.5rem))]"})}function h1({theme:t}){return e.jsx("div",{className:"mt-4 grid grid-cols-4 gap-2",children:[t.primary,t.secondary,t.tertiary,t.panelHigh].map(s=>e.jsx("div",{className:"h-10 rounded-[14px] border border-black/10",style:{background:s}},s))})}function m1(){var m,b;const{t}=lt(),s=We(),[i,a]=d.useState(!1),n=fe({queryKey:["forge-operator-session"],queryFn:Zi}),r=n.isSuccess,l=fe({queryKey:["forge-settings"],queryFn:vi,enabled:r}),o=vn({defaultValues:{profile:{operatorName:"",operatorEmail:"",operatorTitle:""},notifications:{goalDriftAlerts:!0,dailyQuestReminders:!0,achievementCelebrations:!0},execution:{maxActiveTasks:2,timeAccountingMode:"split"},themePreference:"obsidian",customTheme:Pa,localePreference:"en"}}),c=async()=>{await Promise.all([s.invalidateQueries({queryKey:["forge-operator-session"]}),s.invalidateQueries({queryKey:["forge-settings"]})])},x=xe({mutationFn:w=>Kl(w),onSuccess:c}),v=xe({mutationFn:Rx,onSuccess:async()=>{await c(),await n.refetch()}});d.useEffect(()=>{var w;(w=l.data)!=null&&w.settings&&o.reset(ev.parse(l.data.settings))},[l.data,o]);const u=(m=l.data)==null?void 0:m.settings,f=o.watch("themePreference"),h=o.watch("customTheme")??Pa;return d.useEffect(()=>{if(u)return tl(f,h),()=>{tl(u.themePreference,u.customTheme??null)}},[h,f,u,u==null?void 0:u.customTheme,u==null?void 0:u.themePreference]),n.isLoading||l.isLoading?e.jsx(It,{eyebrow:"Settings",title:"Loading settings",description:"Establishing the operator session and fetching current configuration.",columns:2,blocks:6}):n.isError?e.jsx(ze,{eyebrow:"Settings",error:n.error,onRetry:()=>void n.refetch()}):l.isError||!u?e.jsx(ze,{eyebrow:"Settings",error:l.error??new Error("Forge returned an empty settings payload."),onRetry:()=>void l.refetch()}):e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(qe,{title:"Settings",description:"Tune execution policy, timer behaviour, and personal preferences.",badge:`${u.security.integrityScore}% integrity`}),e.jsx(vs,{}),(b=n.data)!=null&&b.session?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-[18px] border border-emerald-400/20 bg-emerald-500/[0.08] px-4 py-3 text-sm text-emerald-100/88",children:[e.jsxs("div",{children:["Operator session active as ",e.jsx("span",{className:"font-medium text-white",children:n.data.session.actorLabel}),"."]}),e.jsx(Q,{variant:"secondary",size:"sm",pending:v.isPending,pendingLabel:"Resetting session",onClick:()=>void v.mutateAsync(),children:"Reset operator session"})]}):null,e.jsxs("div",{className:"grid gap-5",children:[e.jsx(ae,{children:e.jsxs("form",{className:"grid gap-4",onSubmit:o.handleSubmit(async w=>{await x.mutateAsync(w)}),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(le,{...o.register("profile.operatorName")})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Email"}),e.jsx(le,{...o.register("profile.operatorEmail")})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Title"}),e.jsx(le,{...o.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(le,{type:"number",min:1,max:8,...o.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(w=>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:w.value,...o.register("execution.timeAccountingMode")}),e.jsx("span",{className:"text-white/82",children:w.label})]}),e.jsx("span",{className:"text-sm leading-6 text-white/56",children:w.description})]},w.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",...o.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",...o.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",...o.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("p",{className:"text-sm text-white/58",children:"Switch between Forge presets, follow the system palette, or save your own dark shell theme."}),e.jsx("div",{className:"grid gap-3 xl:grid-cols-3",children:Xb.map(w=>{const M=im(w.value,h),E=f===w.value;return e.jsxs("button",{type:"button",onClick:()=>o.setValue("themePreference",w.value,{shouldDirty:!0}),className:`rounded-[24px] border px-4 py-4 text-left transition ${E?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.14)] shadow-[0_18px_36px_rgba(5,12,24,0.24)]":"border-white/8 bg-white/[0.04] hover:bg-white/[0.07]"}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-semibold text-white",children:w.value==="custom"?h.label:w.label}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:w.description})]}),e.jsx("div",{className:`mt-1 size-4 rounded-full border ${E?"border-[rgba(192,193,255,0.65)] bg-[var(--primary)]":"border-white/25"}`})]}),e.jsx(h1,{theme:M})]},w.value)})}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Custom theme editor"}),e.jsx("div",{className:"mt-1 text-sm leading-6 text-white/58",children:"Save a custom Forge palette through a guided modal, or paste and upload JSON directly."})]}),e.jsx(Q,{type:"button",variant:f==="custom"?"secondary":"ghost",onClick:()=>a(!0),children:f==="custom"?"Edit custom theme":"Create custom theme"})]}),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(w=>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:w.value,...o.register("localePreference")}),e.jsx("span",{className:"text-white/72",children:w.label})]},w.value))}),e.jsx(Q,{type:"submit",pending:x.isPending,pendingLabel:"Saving settings",children:"Save settings"})]})}),e.jsx(ae,{children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Mobile companion"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Pair the native iPhone bridge for HealthKit, background sync, and future watch or location signals."})]}),e.jsx(Ae,{to:"/settings/mobile",className:"inline-flex min-h-11 items-center rounded-[16px] bg-white/[0.08] px-4 py-3 text-sm text-white transition hover:bg-white/[0.12]",children:"Open mobile settings"})]})}),e.jsxs(ae,{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:u.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(u.security.lastAuditAt).toLocaleString()})]})]})]})]}),e.jsx(c1,{open:i,onOpenChange:a,value:h,onSave:w=>{o.setValue("customTheme",w,{shouldDirty:!0}),o.setValue("themePreference","custom",{shouldDirty:!0})}})]})}const Dn=["read","write","insights","rewards.manage","psyche.read","psyche.write","psyche.note","psyche.insight","psyche.mode"],u1=[{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 hu(t,s,i){return s==="review"?{...t,preset:s,trustLevel:"trusted",autonomyMode:"approval_required",approvalMode:"approval_by_default",scopes:[...i]}:s==="operator"?{...t,preset:s,trustLevel:"trusted",autonomyMode:"scoped_write",approvalMode:"high_impact_only",scopes:[...Dn]}:s==="autonomous"?{...t,preset:s,trustLevel:"autonomous",autonomyMode:"autonomous",approvalMode:"none",scopes:[...Dn]}:{...t,preset:s}}function Lc(t,s,i){const a={preset:t,label:"Forge Pilot Token",agentLabel:s,agentType:"assistant",description:"Collaborative planning agent.",trustLevel:"trusted",autonomyMode:"scoped_write",approvalMode:"high_impact_only",scopes:[...Dn]};return hu(a,t,i)}function p1({open:t,onOpenChange:s,pending:i=!1,initialPreset:a="operator",defaultAgentLabel:n="OpenClaw",recommendedScopes:r=[...Dn],onSubmit:l}){const[o,c]=d.useState(()=>Lc(a,n,r)),[x,v]=d.useState(null);d.useEffect(()=>{t&&(c(Lc(a,n,r)),v(null))},[t,a,n,r]);const u=[{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:(f,h)=>e.jsx(Ze,{columns:3,value:f.preset,onChange:m=>h(hu(f,m,r)),options:[{value:"review",label:"Review-first",description:"Every action waits for your approval. Safe starting point for a new agent you have not yet trusted."},{value:"operator",label:"Full operator",description:"Trusted collaborator with full scopes. High-impact actions still ask for approval."},{value:"autonomous",label:"Autonomous pilot",description:"No approval gates. Use only for agents you have fully verified in a controlled setup."},{value:"custom",label:"Custom",description:"Start from a blank slate and configure every dimension yourself."}]})},{id:"identity",eyebrow:"Agent identity",title:"Name the agent and this token",description:"The agent name appears in logs, approval requests, and audit trails. The token label is for your reference.",render:(f,h)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Agent name",labelHelp:"This label identifies the agent in every log entry, approval notification, and XP attribution. Pick something memorable.",children:e.jsx(le,{value:f.agentLabel,placeholder:"OpenClaw",onChange:m=>h({agentLabel:m.target.value})})}),e.jsx(se,{label:"Token label",description:"A short name for this credential — mainly for your reference in the token list.",children:e.jsx(le,{value:f.label,placeholder:"Forge Pilot Token",onChange:m=>h({label:m.target.value})})}),e.jsxs("div",{className:"grid gap-5 md:grid-cols-2",children:[e.jsx(se,{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:f.agentType,onChange:m=>h({agentType:m.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(se,{label:"Description",description:"Optional note about what this agent does.",children:e.jsx(le,{value:f.description,placeholder:"Collaborative planning agent.",onChange:m=>h({description:m.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:(f,h)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{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(Ze,{columns:3,value:f.trustLevel,onChange:m=>h({trustLevel:m}),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(se,{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(Ze,{columns:3,value:f.autonomyMode,onChange:m=>h({autonomyMode:m}),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(se,{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(Ze,{columns:3,value:f.approvalMode,onChange:m=>h({approvalMode:m}),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:(f,h)=>e.jsxs(se,{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:u1.map(m=>{const b=f.scopes.includes(m.value);return e.jsxs("button",{type:"button",className:`rounded-[18px] border px-4 py-4 text-left transition ${b?"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(b){if(f.scopes.length===1)return;h({scopes:f.scopes.filter(w=>w!==m.value)})}else h({scopes:[...f.scopes,m.value]})},children:[e.jsx("div",{className:"font-medium",children:m.label}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/58",children:m.description})]},m.value)})}),e.jsxs("div",{className:"mt-2 text-xs text-white/40",children:[f.scopes.length," scope",f.scopes.length!==1?"s":""," selected"]})]})}];return e.jsx(rt,{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:o,onChange:c,steps:u,submitLabel:"Issue token",pending:i,pendingLabel:"Issuing token…",error:x,onSubmit:async()=>{v(null);const f=tv.safeParse({label:o.label,agentLabel:o.agentLabel,agentType:o.agentType,description:o.description,trustLevel:o.trustLevel,autonomyMode:o.autonomyMode,approvalMode:o.approvalMode,scopes:o.scopes});if(!f.success){const h=f.error.issues[0];v((h==null?void 0:h.message)??"Check the agent name and at least one scope before issuing.");return}try{await l(f.data),s(!1)}catch(h){v(h instanceof Error?h.message:"Could not issue the token right now.")}}})}function Dc(t){return{source:"new",taskId:"",title:"",description:"",owner:t,projectId:"",status:"done",points:40}}function x1({open:t,onOpenChange:s,pending:i=!1,defaultOwner:a="",availableTasks:n=[],availableProjects:r=[],onSubmit:l}){const[o,c]=d.useState(()=>Dc(a)),[x,v]=d.useState(null);d.useEffect(()=>{t&&(c(Dc(a)),v(null))},[t,a]);const u=[{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:(f,h)=>e.jsxs(e.Fragment,{children:[e.jsx(Ze,{columns:2,value:f.source,onChange:m=>h({source:m,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."}]}),f.source==="existing"&&n.length>0?e.jsx(se,{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:f.taskId,onChange:m=>h({taskId:m.target.value}),children:[e.jsx("option",{value:"",children:"— choose a task —"}),n.map(m=>e.jsxs("option",{value:m.id,children:[m.title," · ",m.status.replaceAll("_"," ")]},m.id))]})}):f.source==="existing"&&n.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:(f,h)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Title",labelHelp:"Write the title like a short achievement: what was completed, not what was started.",children:e.jsx(le,{value:f.title,placeholder:"Write postmortem draft",onChange:m=>h({title:m.target.value})})}),e.jsx(se,{label:"Owner",description:"Who did this work? Defaults to the operator name.",children:e.jsx(le,{value:f.owner,placeholder:"Your name",onChange:m=>h({owner:m.target.value})})}),e.jsx(se,{label:"Description",description:"What moved forward? What should remain visible in the project history?",children:e.jsx(Me,{className:"min-h-28",value:f.description,placeholder:"Wrote the full incident timeline and drafted the three key learnings for the team retrospective.",onChange:m=>h({description:m.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:(f,h)=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-5 md:grid-cols-2",children:[e.jsx(se,{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:f.projectId,onChange:m=>h({projectId:m.target.value}),children:[e.jsx("option",{value:"",children:"No project link"}),r.map(m=>e.jsx("option",{value:m.id,children:m.title},m.id))]})}),e.jsx(se,{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(Ze,{columns:2,value:f.status,onChange:m=>h({status:m}),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(se,{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(le,{type:"number",min:5,max:500,className:"w-36",value:f.points,onChange:m=>h({points:Number(m.target.value)})}),e.jsx("div",{className:"flex gap-2",children:[20,40,80,120].map(m=>e.jsxs("button",{type:"button",className:`rounded-full px-3 py-1.5 text-xs transition ${f.points===m?"bg-white/18 text-white":"bg-white/[0.06] text-white/55 hover:bg-white/[0.10]"}`,onClick:()=>h({points:m}),children:[m," xp"]},m))})]})})]})}];return e.jsx(rt,{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:o,onChange:c,steps:u,submitLabel:"Log work",pending:i,pendingLabel:"Logging work…",error:x,onSubmit:async()=>{if(v(null),o.source==="new"&&o.title.trim().length===0){v("Add a title so Forge knows what work to create.");return}if(o.source==="existing"&&!o.taskId){v("Pick an existing task or switch to New task.");return}try{await l({taskId:o.source==="existing"&&o.taskId?o.taskId:void 0,title:o.source==="new"&&o.title.trim()?o.title.trim():void 0,description:o.description.trim()||void 0,owner:o.owner.trim()||void 0,projectId:o.projectId||null,status:o.status,points:o.points}),s(!1)}catch(f){v(f instanceof Error?f.message:"Could not log the work right now.")}}})}function mu({text:t}){const[s,i]=d.useState(!1),a=async()=>{try{await navigator.clipboard.writeText(t),i(!0),setTimeout(()=>i(!1),2200)}catch{}};return e.jsxs("button",{type:"button",onClick:()=>void a(),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(Vi,{className:"size-3 text-emerald-400"}):e.jsx(mh,{className:"size-3"}),s?"Copied":"Copy"]})}function zr({label:t,children:s,copyText:i}){return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:t}),e.jsx(mu,{text:i??s})]}),e.jsx("pre",{className:"mt-3 overflow-x-auto rounded-[14px] bg-[rgba(8,13,28,0.78)] p-3 text-xs leading-6 text-white/78",children:e.jsx("code",{children:s})})]})}function g1({open:t,onOpenChange:s,state:i}){if(!i)return null;const{tokenString:a,agentLabel:n,onboarding:r}=i,l=JSON.stringify({baseUrl:r.forgeBaseUrl,apiToken:a,actorLabel:n,timeoutMs:r.defaultTimeoutMs},null,2),o=[`curl -s ${r.healthUrl} \\`,` -H "Authorization: Bearer ${a}" \\`,' -H "X-Forge-Source: agent" \\',` -H "X-Forge-Actor: ${n}"`].join(`
|
|
35
|
-
`),c=["openclaw gateway restart",'openclaw agent --message "forge_get_operator_overview"'].join(`
|
|
36
|
-
`);return e.jsx(Et,{open:t,onOpenChange:s,children:e.jsxs(Lt,{children:[e.jsx(Dt,{className:"fixed inset-0 z-40 bg-[rgba(4,8,18,0.82)] backdrop-blur-xl"}),e.jsxs($t,{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(Ot,{className:"sr-only",children:"Token issued — setup instructions"}),e.jsx(qt,{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(Hi,{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(Ft,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":"Close",className:"rounded-full bg-white/6 p-2 text-white/55 transition hover:bg-white/10 hover:text-white",children:e.jsx(mt,{className:"size-4"})})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-5",children:e.jsxs(Kt.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(L,{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:a}),e.jsx(mu,{text:a})]}),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(zr,{label:"Plugin params — paste into openclaw.json → plugins → forge → params",copyText:l,children:l})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx("div",{className:"flex size-5 items-center justify-center rounded-full bg-white/12 text-xs font-semibold text-white",children:"2"}),e.jsx("span",{className:"text-sm font-medium text-white",children:"Restart the gateway and confirm the agent can connect"})]}),e.jsx(zr,{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:n})," is authenticated."]}),e.jsx("div",{className:"mt-3",children:e.jsx(zr,{label:"Verify token — run in terminal",copyText:o,children:o})})]}),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(Q,{onClick:()=>s(!1),children:[e.jsx(Vi,{className:"size-4"}),"Done"]})]})})]})]})})}function ln(t,s){return s.every(i=>t.scopes.includes(i))}function f1(){var W,ne,de,we,Ne;const t=We(),[s,i]=d.useState(!1),[a,n]=d.useState("operator"),[r,l]=d.useState(null),[o,c]=d.useState(!1),[x,v]=d.useState(!1),[u,f]=d.useState(!1),h=fe({queryKey:["forge-operator-session"],queryFn:Zi}),m=h.isSuccess,b=fe({queryKey:["forge-settings"],queryFn:vi,enabled:m}),w=fe({queryKey:["forge-approval-requests"],queryFn:mb,enabled:m}),M=fe({queryKey:["forge-agent-onboarding"],queryFn:hb}),E=fe({queryKey:["forge-operator-context"],queryFn:ff,enabled:m}),D=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"]})])},j=xe({mutationFn:H=>vb(H),onSuccess:D}),S=xe({mutationFn:H=>wb(H),onSuccess:async(H,me)=>{if(await D(),C){const y=H.token;l({tokenString:y.token,agentLabel:y.tokenSummary.agentLabel??"forge-agent",onboarding:C}),c(!0)}}}),p=xe({mutationFn:H=>yb(H),onSuccess:D}),A=xe({mutationFn:H=>ub(H),onSuccess:D}),T=xe({mutationFn:H=>pb(H),onSuccess:D}),k=xe({mutationFn:Tb,onSuccess:D}),$=(W=b.data)==null?void 0:W.settings,g=((ne=w.data)==null?void 0:ne.approvalRequests)??[],C=(de=M.data)==null?void 0:de.onboarding,F=(we=E.data)==null?void 0:we.context,z=($==null?void 0:$.agentTokens.filter(H=>H.status==="active"))??[],J=(C==null?void 0:C.recommendedScopes)??[],O=z.some(H=>ln(H,J)),_=z.some(H=>ln(H,["rewards.manage"])),B=z.some(H=>ln(H,["psyche.write"])),K=z.some(H=>H.autonomyMode!=="approval_required"&&ln(H,["write"])),Z=z.length>0,U=d.useMemo(()=>{if(!F)return[];const H=[...F.focusTasks,...F.currentBoard.backlog,...F.currentBoard.focus,...F.currentBoard.inProgress,...F.currentBoard.blocked,...F.currentBoard.done],me=new Map;for(const y of H)me.set(y.id,y);return[...me.values()]},[F]),I=($==null?void 0:$.profile.operatorName)??"",G=[{label:"Operator session",ok:!0,badge:"active",badgeTone:"emerald",detail:(Ne=h.data)!=null&&Ne.session?`Session open as ${h.data.session.actorLabel}. Works for localhost and Tailscale without a token.`:"Passwordless session is active for local and Tailscale access.",action:null},{label:"Agent token",ok:Z,badge:Z?`${z.length} active`:"none issued",badgeTone:Z?"emerald":"amber",detail:Z?`${z.length} active token${z.length===1?"":"s"} allow external agents and scripts to authenticate.`:"No token yet. Issue one to let external agents connect via the API.",action:Z?null:{label:"Issue token",preset:"operator",onClick:()=>{n("operator"),i(!0)}}},{label:"Full operator bundle",ok:O,badge:O?"ready":"optional",badgeTone:O?"emerald":"neutral",detail:O?"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:O?null:{label:"Set up",preset:"operator",onClick:()=>{n("operator"),i(!0)}}},{label:"Reward control",ok:_,badge:_?"ready":"optional",badgeTone:_?"emerald":"neutral",detail:_?"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:_?null:{label:"Add scope",preset:"operator",onClick:()=>{n("operator"),i(!0)}}},{label:"Psyche writes",ok:B,badge:B?"ready":"optional",badgeTone:B?"emerald":"neutral",detail:B?"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:B?null:{label:"Add scope",preset:"operator",onClick:()=>{n("operator"),i(!0)}}},{label:"Scoped writes",ok:K,badge:K?"ready":"optional",badgeTone:K?"emerald":"neutral",detail:K?"A trusted agent can write without constant approval prompts.":"All write tokens are approval-required. Agents must queue every mutation for your review.",action:K?null:{label:"Configure",preset:"operator",onClick:()=>{n("operator"),i(!0)}}}];return h.isLoading||b.isLoading?e.jsx(It,{eyebrow:"Settings · Agents",title:"Loading agent console",description:"Establishing the operator session and loading agent configuration.",columns:2,blocks:6}):h.isError?e.jsx(ze,{eyebrow:"Settings · Agents",error:h.error,onRetry:()=>void h.refetch()}):b.isError||!$?e.jsx(ze,{eyebrow:"Settings · Agents",error:b.error??new Error("Could not load settings."),onRetry:()=>void b.refetch()}):e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(qe,{title:"Agents",description:"Connection status, capability access, tokens, approval queue, and work logging."}),e.jsx(vs,{}),e.jsx(p1,{open:s,onOpenChange:i,pending:j.isPending,initialPreset:a,defaultAgentLabel:(C==null?void 0:C.defaultActorLabel)??"OpenClaw",recommendedScopes:J,onSubmit:async H=>{const me=await j.mutateAsync(H);i(!1),C&&(l({tokenString:me.token.token,agentLabel:H.agentLabel,onboarding:C}),c(!0))}}),e.jsx(g1,{open:o,onOpenChange:c,state:r}),e.jsx(x1,{open:x,onOpenChange:v,pending:k.isPending,defaultOwner:I,availableTasks:U,availableProjects:(F==null?void 0:F.activeProjects)??[],onSubmit:async H=>{await k.mutateAsync(H)}}),e.jsxs("div",{className:"grid gap-5",children:[F?e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsx(Ks,{label:"Active projects",value:F.activeProjects.length,tone:"core"}),e.jsx(Ks,{label:"Focus tasks",value:F.focusTasks.length,tone:"core"}),e.jsx(Ks,{label:"Pending approvals",value:g.filter(H=>H.status==="pending").length,tone:"core"}),e.jsx(Ks,{label:"Operator level",value:F.xp.profile.level,tone:"core",detail:`${F.xp.profile.totalXp} total XP`})]}):null,e.jsxs(ae,{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:G.map(H=>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:H.label}),e.jsx(L,{className:H.badgeTone==="emerald"?"text-emerald-300":H.badgeTone==="amber"?"text-amber-300":"text-white/45",children:H.badge})]}),e.jsx("div",{className:"mt-1 text-sm leading-6 text-white/55",children:H.detail})]}),H.action?e.jsxs("button",{type:"button",onClick:H.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:[H.action.label,e.jsx(Gt,{className:"size-3"})]}):null]},H.label))})]}),e.jsxs(ae,{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(Q,{size:"sm",variant:"secondary",onClick:()=>{n("operator"),i(!0)},children:[e.jsx(zt,{className:"size-3.5"}),"Issue token"]})]}),e.jsx("div",{className:"mt-4 grid gap-3",children:$.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."}):$.agentTokens.map(H=>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:H.label}),e.jsxs("div",{className:"mt-0.5 text-sm text-white/50",children:[H.agentLabel??"Unassigned agent"," ·"," ",e.jsx("span",{className:"font-mono text-xs",children:H.tokenPrefix})]})]}),e.jsx(L,{className:H.status==="active"?"text-emerald-300":"text-white/45",children:H.status})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-xs text-white/55",children:[e.jsx("span",{children:H.trustLevel}),e.jsx("span",{children:"·"}),e.jsx("span",{children:H.autonomyMode.replaceAll("_"," ")}),e.jsx("span",{children:"·"}),e.jsx("span",{children:H.approvalMode.replaceAll("_"," ")})]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-1.5",children:["write","rewards.manage","psyche.write"].map(me=>e.jsx(L,{className:H.scopes.includes(me)?"text-emerald-300":"text-white/30",children:me},me))}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(Q,{variant:"secondary",size:"sm",pending:S.isPending,pendingLabel:"Rotating",onClick:()=>void S.mutateAsync(H.id),children:"Rotate & reveal new token"}),e.jsx(Q,{variant:"ghost",size:"sm",pending:p.isPending,pendingLabel:"Revoking",onClick:()=>void p.mutateAsync(H.id),children:"Revoke"})]})]},H.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."})]}),$.agents.length>0?e.jsxs(ae,{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:$.agents.map(H=>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:H.label}),H.description?e.jsx("div",{className:"mt-1 text-sm text-white/52",children:H.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:H.agentType}),e.jsx("span",{children:H.autonomyMode.replaceAll("_"," ")}),e.jsxs("span",{children:[H.activeTokenCount," active token",H.activeTokenCount!==1?"s":""]})]})]}),e.jsx(L,{className:"text-white/60",children:H.trustLevel})]},H.id))})]}):null,F?e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1.05fr)_minmax(0,0.95fr)]",children:[e.jsxs(ae,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Recommended next move"}),F.recommendedNextTask?e.jsxs("div",{className:"mt-4 grid gap-2",children:[e.jsx(Xe,{kind:"task",label:F.recommendedNextTask.title,variant:"heading",size:"lg"}),e.jsx("div",{className:"text-sm leading-6 text-white/58",children:F.recommendedNextTask.description||"No extra notes yet."}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-2",children:[e.jsx(L,{children:F.recommendedNextTask.status.replaceAll("_"," ")}),e.jsxs(L,{children:[F.recommendedNextTask.points," xp"]}),e.jsx(L,{children:F.recommendedNextTask.owner})]})]}):e.jsx("div",{className:"mt-4 text-sm text-white/55",children:"Board is clear. No recommended task right now."})]}),e.jsxs(ae,{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:F.currentBoard.backlog.length},{label:"Focus",value:F.currentBoard.focus.length},{label:"In progress",value:F.currentBoard.inProgress.length},{label:"Blocked",value:F.currentBoard.blocked.length}].map(H=>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:H.label}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:H.value})]},H.label))})]})]}):null,F&&F.activeProjects.length>0?e.jsxs(ae,{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:F.activeProjects.slice(0,6).map(H=>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(Xe,{kind:"project",label:H.title}),e.jsxs(L,{children:[H.progress,"%"]})]}),e.jsx("div",{className:"mt-2",children:e.jsx(Te,{kind:"goal",label:H.goalTitle,compact:!0,gradient:!1})}),e.jsxs("div",{className:"mt-2 text-xs text-white/38",children:[H.activeTaskCount," active ·"," ",H.completedTaskCount," done"]})]},H.id))})]}):null,e.jsxs(ae,{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"}),g.filter(H=>H.status==="pending").length>0?e.jsxs(L,{className:"text-amber-300",children:[g.filter(H=>H.status==="pending").length," pending"]}):null]}),e.jsx("div",{className:"mt-4 grid gap-3",children:g.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."}):g.map(H=>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:H.title}),e.jsx("div",{className:"mt-0.5 text-sm text-white/55",children:H.summary||H.actionType})]}),e.jsx(L,{className:H.status==="pending"?"text-amber-300":"text-white/45",children:H.status})]}),H.status==="pending"?e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(Q,{variant:"secondary",size:"sm",pending:A.isPending,pendingLabel:"Approving",onClick:()=>void A.mutateAsync(H.id),children:"Approve"}),e.jsx(Q,{variant:"ghost",size:"sm",pending:T.isPending,pendingLabel:"Rejecting",onClick:()=>void T.mutateAsync(H.id),children:"Reject"})]}):null]},H.id))})]}),e.jsxs(ae,{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(Q,{variant:"secondary",size:"sm",onClick:()=>v(!0),children:[e.jsx(zp,{className:"size-3.5"}),"Log work"]})]}),k.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(Xe,{kind:"task",label:k.data.task.title,showKind:!1})}),". Operator XP updated to ",k.data.xp.profile.totalXp,"."]}):null]}),e.jsxs(ae,{children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-4 text-left",onClick:()=>f(H=>!H),children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Connection & onboarding"}),C?e.jsx("div",{className:"mt-1 text-sm text-white/55",children:C.forgeBaseUrl}):null]}),u?e.jsx(Bn,{className:"size-4 shrink-0 text-white/38"}):e.jsx(Ji,{className:"size-4 shrink-0 text-white/38"})]}),u&&C?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:C.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:C.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:C.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:[C.recommendedTrustLevel," ·"," ",C.recommendedAutonomyMode.replaceAll("_"," ")," ·"," ",C.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:C.authModes.operatorSession.label}),e.jsx(L,{className:"mt-1 text-emerald-300",children:C.defaultConnectionMode==="operator_session"?"default":"available"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:C.authModes.operatorSession.summary}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:C.authModes.operatorSession.trustedTargets.map(H=>e.jsx(L,{className:"text-white/65",children:H},H))})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:C.authModes.managedToken.label}),e.jsx(L,{className:"mt-1 text-white/55",children:"optional"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:C.authModes.managedToken.summary}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/48",children:C.tokenRecovery.rotationSummary})]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Shared runtime"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:"Keep Forge, OpenClaw, Hermes, and the browser on the same runtime when they should see one shared user directory, one strategy graph, and one task history."}),e.jsxs("div",{className:"mt-3 text-xs leading-5 text-white/46",children:["Base URL: ",C.forgeBaseUrl]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Agent identity"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:"Create each agent as a bot user, then write with that user's `userId`. The relationship graph in Settings -> Users controls what each direction can see, message, share, plan, and affect."}),e.jsx("div",{className:"mt-3 text-xs leading-5 text-white/46",children:"Cross-owner links stay valid even when ownership differs."})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Contract timing"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:"Leave strategies editable while humans and bots refine the graph. Lock them only when the plan becomes the contract the alignment metrics should judge."}),e.jsx("div",{className:"mt-3 text-xs leading-5 text-white/46",children:"Coverage, sequencing, scope discipline, and quality all contribute to alignment now."})]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Fast onboarding checklist"}),e.jsxs("div",{className:"mt-3 grid gap-2 text-sm leading-6 text-white/60",children:[e.jsx("div",{children:"1. Create the human and bot users in Settings -> Users."}),e.jsx("div",{children:"2. Keep the default graph permissive until collaboration is flowing cleanly."}),e.jsx("div",{children:"3. Point OpenClaw and Hermes at the same Forge runtime and storage root when they should collaborate."}),e.jsx("div",{children:"4. Give each adapter a distinct actor label so activity stays readable."}),e.jsx("div",{children:"5. Build strategies as drafts first, then lock when the plan is ready to become the contract."})]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Rights language"}),e.jsxs("div",{className:"mt-3 grid gap-2 text-sm leading-6 text-white/60",children:[e.jsx("div",{children:"`See` means discover, search, and read another owner."}),e.jsx("div",{children:"`Message` means coordinate and hand off through Forge."}),e.jsx("div",{children:"`Plan` means draft or edit that owner's strategies."}),e.jsx("div",{children:"`Affect` means create or mutate that owner's work."})]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Strategy lifecycle"}),e.jsxs("div",{className:"mt-3 grid gap-2 text-sm leading-6 text-white/60",children:[e.jsx("div",{children:"1. Save an incomplete draft while the plan is still being negotiated."}),e.jsx("div",{children:"2. Let humans and bots refine targets, nodes, and sequence together."}),e.jsx("div",{children:"3. Lock only when the graph becomes the contract for alignment."}),e.jsx("div",{children:"4. Unlock only when the contract itself is being renegotiated."})]})]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Quick-connect verification"}),e.jsx("pre",{className:"mt-3 overflow-x-auto rounded-[16px] bg-[rgba(8,13,28,0.78)] p-4 text-xs leading-6 text-white/72",children:e.jsx("code",{children:[`curl -s ${C.healthUrl}`,"openclaw plugins install ./projects/forge","openclaw gateway restart"].join(`
|
|
37
|
-
`)})})]}),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:C.requiredHeaders.authorization}),e.jsx("div",{children:C.requiredHeaders.source}),e.jsx("div",{children:C.requiredHeaders.actor})]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:[C.connectionGuides.openclaw,C.connectionGuides.hermes].map(H=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-medium text-white",children:H.label}),e.jsx("div",{className:"mt-3 grid gap-2 text-sm leading-6 text-white/60",children:H.installSteps.map(me=>e.jsx("div",{children:me},me))}),e.jsx("pre",{className:"mt-4 overflow-x-auto rounded-[16px] bg-[rgba(8,13,28,0.78)] p-4 text-xs leading-6 text-white/72",children:e.jsx("code",{children:H.verifyCommands.join(`
|
|
38
|
-
`)})}),e.jsx("div",{className:"mt-3 grid gap-1 text-sm leading-6 text-white/48",children:H.configNotes.map(me=>e.jsx("div",{children:me},me))})]},H.label))}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Multi-user model"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:C.multiUserModel.summary}),e.jsx("div",{className:"mt-3 grid gap-1 text-sm leading-6 text-white/48",children:C.multiUserModel.routeScoping.map(H=>e.jsx("div",{children:H},H))})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.14em] text-white/40",children:"Strategy contracts"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/60",children:C.strategyContractModel.lockSummary}),e.jsx("div",{className:"mt-3 grid gap-1 text-sm leading-6 text-white/48",children:C.strategyContractModel.metricBreakdown.map(H=>e.jsx("div",{children:H},H))})]})]})]}):u&&M.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."}):u?e.jsx("div",{className:"mt-4 text-sm text-white/50",children:"Loading…"}):null]})]})]})}const ii={goal:"Goals",project:"Projects",task:"Tasks",strategy:"Strategies",habit:"Habits",tag:"Tags",note:"Notes",insight:"Insights",psyche_value:"Values",behavior_pattern:"Patterns",behavior:"Behaviors",belief_entry:"Beliefs",mode_profile:"Modes",mode_guide_session:"Mode guides",event_type:"Event types",emotion_definition:"Emotions",trigger_report:"Reports",calendar_event:"Calendar events",work_block_template:"Work blocks",task_timebox:"Timeboxes"},b1={goal:"goal",project:"project",task:"task",strategy:"strategy",habit:"habit",tag:null,note:null,insight:"report",psyche_value:"value",behavior_pattern:"pattern",behavior:"behavior",belief_entry:"belief",mode_profile:"mode",mode_guide_session:"mode",event_type:null,emotion_definition:null,trigger_report:"report",calendar_event:null,work_block_template:null,task_timebox:null};function v1(t){return new Date(t).toLocaleString()}function w1(){var j,S;const t=We(),[s,i]=d.useState(""),[a,n]=d.useState([]),r=fe({queryKey:["forge-operator-session"],queryFn:Zi}),l=r.isSuccess,o=fe({queryKey:["forge-settings-bin"],queryFn:cb,enabled:l}),c=async()=>{await t.invalidateQueries({predicate:p=>Array.isArray(p.queryKey)&&typeof p.queryKey[0]=="string"&&p.queryKey[0].startsWith("forge-")})},x=xe({mutationFn:p=>ad({operations:[{entityType:p.entityType,id:p.entityId}]}),onSuccess:c}),v=xe({mutationFn:p=>id({operations:[{entityType:p.entityType,id:p.entityId,mode:"hard"}]}),onSuccess:c}),u=xe({mutationFn:p=>ad({operations:p.map(A=>({entityType:A.entityType,id:A.entityId}))}),onSuccess:c}),f=xe({mutationFn:p=>id({operations:p.map(A=>({entityType:A.entityType,id:A.entityId,mode:"hard"}))}),onSuccess:c}),h=((j=o.data)==null?void 0:j.bin.records)??[],m=s.trim().toLowerCase(),b=d.useMemo(()=>h.filter(p=>a.length===0||a.includes(p.entityType)?m?[p.title,p.subtitle??"",p.entityType,p.entityId,p.deletedByActor??"",p.deletedSource??"",p.deleteReason??""].join(" ").toLowerCase().includes(m):!0:!1),[m,h,a]),w=d.useMemo(()=>{const p=new Map;for(const A of b){const T=p.get(A.entityType)??[];T.push(A),p.set(A.entityType,T)}return[...p.entries()].sort((A,T)=>ii[A[0]].localeCompare(ii[T[0]]))},[b]),M=d.useMemo(()=>[...new Set(h.map(p=>p.entityType))].sort((p,A)=>ii[p].localeCompare(ii[A])),[h]);function E(p){n(A=>A.includes(p)?A.filter(T=>T!==p):[...A,p])}async function D(){b.length===0||!window.confirm(`Permanently delete ${b.length} item${b.length===1?"":"s"} from the bin? This cannot be undone.`)||await f.mutateAsync(b)}return r.isLoading||o.isLoading?e.jsx(It,{eyebrow:"Settings",title:"Loading bin",description:"Loading deleted items and restore controls.",columns:2,blocks:6}):r.isError?e.jsx(ze,{eyebrow:"Settings",error:r.error,onRetry:()=>void r.refetch()}):o.isError?e.jsx(ze,{eyebrow:"Settings",error:o.error,onRetry:()=>void o.refetch()}):e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(qe,{title:"Bin",description:"Restore soft-deleted items or permanently remove them when you really mean it.",badge:`${((S=o.data)==null?void 0:S.bin.totalCount)??0} deleted items`}),e.jsx(vs,{}),e.jsxs(ae,{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(bt,{className:"pointer-events-none absolute left-4 top-1/2 size-4 -translate-y-1/2 text-white/35"}),e.jsx(le,{value:s,onChange:p=>i(p.target.value),placeholder:"Search title, id, reason, or source",className:"pl-11"})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:M.map(p=>{const A=a.includes(p);return e.jsx("button",{type:"button",onClick:()=>E(p),className:re("rounded-full border px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] transition",A?"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:ii[p]},p)})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 lg:max-w-[22rem] lg:justify-end",children:[e.jsxs(Q,{variant:"secondary",size:"sm",disabled:b.length===0,pending:u.isPending,pendingLabel:"Restoring",onClick:()=>void u.mutateAsync(b),children:[e.jsx(Hr,{className:"size-4"}),e.jsx("span",{children:"Restore visible"})]}),e.jsxs(Q,{variant:"secondary",size:"sm",disabled:b.length===0,pending:f.isPending,pendingLabel:"Deleting",onClick:()=>void D(),children:[e.jsx(ct,{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:[b.length," visible"]}),a.length>0?e.jsxs("span",{children:[a.length," type filters active"]}):null,m?e.jsxs("span",{children:["Search: “",s.trim(),"”"]}):null]})]}),h.length===0?e.jsxs(ae,{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."})]}):w.length===0?e.jsxs(ae,{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:w.map(([p,A])=>{const T=b1[p];return e.jsxs(ae,{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:[T?e.jsx(Te,{kind:T,label:ii[p],compact:!0}):null,T?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:ii[p]}),e.jsxs("div",{className:"text-sm text-white/55",children:[A.length," deleted"]})]})}),e.jsx("div",{className:"mt-4 grid gap-3",children:A.map(k=>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:k.title}),k.subtitle?e.jsx("div",{className:"mt-1 text-sm text-white/62",children:k.subtitle}):null,e.jsxs("div",{className:"mt-3 flex flex-wrap gap-3 text-xs text-white/45",children:[e.jsxs("span",{children:["Deleted ",v1(k.deletedAt)]}),k.deletedByActor?e.jsxs("span",{children:["By ",k.deletedByActor]}):null,k.deletedSource?e.jsxs("span",{children:["Source ",k.deletedSource]}):null,k.deleteReason?e.jsxs("span",{children:["Reason: ",k.deleteReason]}):null]})]}),e.jsxs("div",{className:"flex flex-wrap items-start justify-end gap-2",children:[e.jsxs(Q,{variant:"secondary",size:"sm",pending:x.isPending,pendingLabel:"Restoring",onClick:()=>void x.mutateAsync(k),children:[e.jsx(Hr,{className:"size-4"}),e.jsx("span",{children:"Restore"})]}),e.jsxs(Q,{variant:"secondary",size:"sm",pending:v.isPending,pendingLabel:"Deleting",onClick:()=>void v.mutateAsync(k),children:[e.jsx(ct,{className:"size-4"}),e.jsx("span",{children:"Delete forever"})]})]})]},`${k.entityType}:${k.entityId}`))})]},p)})})]})}const $c=[{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:fs,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:Hi,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:xl,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:Hi,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:fs,links:[]}];function y1(t){if(!t)return $c;const s=t==="google"?"Google Calendar setup":t==="apple"?"Apple Calendar setup":t==="microsoft"?"Exchange Online setup":"Custom CalDAV setup";return $c.filter(i=>i.title==="Before you connect anything"||i.title===s)}function j1({section:t,compact:s}){const i=t.icon;return e.jsxs(ae,{className:s?"grid gap-3 rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))] p-4":"grid gap-4 rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-[18px] bg-[var(--primary)]/14 p-3 text-[var(--primary)]",children:e.jsx(i,{className:s?"size-4":"size-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:s?"font-medium text-white":"font-display text-[1.15rem] text-white",children:t.title}),e.jsx("p",{className:s?"mt-1.5 text-sm leading-6 text-white/62":"mt-2 max-w-3xl text-sm leading-6 text-white/62",children:t.description})]})]}),e.jsx("div",{className:s?"grid gap-1.5":"grid gap-2",children:t.bullets.map(a=>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:a},a))}),t.links.length>0?e.jsx("div",{className:"flex flex-wrap gap-2",children:t.links.map(a=>e.jsxs("a",{href:a.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(Wi,{className:"size-3.5"}),a.label]},a.href))}):null]})}function N1({provider:t,compact:s=!1}){const i=y1(t);return e.jsx("div",{className:"grid gap-4",children:i.map(a=>e.jsx(j1,{section:a,compact:s},a.title))})}const $n={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 qr(t){return{provider:t,label:$n[t].label,serverUrl:$n[t].serverUrl,username:"",password:"",clientId:"",clientSecret:"",refreshToken:"",selectedCalendarUrls:[],forgeCalendarUrl:null,createForgeCalendar:!1}}function Ii(t,s){const i=s.trim();return i.length>0?i:$n[t].label}function k1({open:t,onOpenChange:s,initialProvider:i="google",initialStepId:a,microsoftSetup:n,onSubmit:r,pending:l=!1}){const[o,c]=d.useState(()=>qr(i)),[x,v]=d.useState(null),[u,f]=d.useState(null),[h,m]=d.useState(null),b=d.useRef(null),w=()=>{m(null),b.current=null},M=p=>{f(p);const A=p.calendars.filter(k=>k.selectedByDefault).map(k=>k.url),T=p.calendars.find(k=>k.isForgeCandidate);c(k=>({...k,selectedCalendarUrls:k.selectedCalendarUrls.length>0?k.selectedCalendarUrls.filter($=>p.calendars.some(g=>g.url===$)):A,forgeCalendarUrl:k.provider==="microsoft"?null:(T==null?void 0:T.url)??k.forgeCalendarUrl??null,createForgeCalendar:k.provider==="microsoft"?!1:k.createForgeCalendar&&!T})),v(null)};d.useEffect(()=>{var p;if(!t){(p=b.current)==null||p.close(),b.current=null;return}v(null),f(null),c(qr(i)),w()},[i,t]),d.useEffect(()=>{if(!t||!h||h.status!=="pending")return;const p=T=>{var k,$;T.origin===window.location.origin&&(((k=T.data)==null?void 0:k.type)!=="forge:microsoft-calendar-auth"||(($=T.data)==null?void 0:$.sessionId)!==h.sessionId||D(h.sessionId))},A=window.setInterval(()=>{!b.current||!b.current.closed||(b.current=null,D(h.sessionId,{afterPopupClose:!0}))},400);return window.addEventListener("message",p),()=>{window.removeEventListener("message",p),window.clearInterval(A)}},[h,t]);const E=xe({mutationFn:()=>o.provider==="google"?ur({provider:"google",username:o.username,clientId:o.clientId,clientSecret:o.clientSecret,refreshToken:o.refreshToken}):o.provider==="apple"?ur({provider:"apple",username:o.username,password:o.password}):ur({provider:"caldav",serverUrl:o.serverUrl,username:o.username,password:o.password}),onSuccess:({discovery:p})=>{M(p)},onError:p=>{f(null),v(p instanceof Error?p.message:"Forge could not discover calendars with these credentials.")}}),D=async(p,A)=>{try{const{session:T}=await Hg(p);if(m(T),T.status==="authorized"&&T.discovery){M(T.discovery),v(null);return}if(T.status==="error"||T.status==="expired"){v(T.error??"Microsoft sign-in did not complete. Start the guided sign-in again.");return}A!=null&&A.afterPopupClose&&v("The Microsoft sign-in window closed before Forge received permission.")}catch(T){v(T instanceof Error?T.message:"Forge could not confirm the Microsoft sign-in session.")}},j=async()=>{var p;try{if(!n.isReadyForSignIn)throw new Error("Finish the Microsoft setup in Settings -> Calendar before starting sign-in.");v(null),f(null);const{session:A}=await Qg({label:Ii("microsoft",o.label)});if(!A.authUrl)throw new Error("Forge could not prepare the Microsoft sign-in URL.");if(m(A),(p=b.current)==null||p.close(),b.current=window.open(A.authUrl,"forge-microsoft-calendar-auth","popup=yes,width=520,height=720,resizable=yes,scrollbars=yes"),!b.current)throw new Error("The Microsoft sign-in popup was blocked. Allow popups for Forge and try again.");b.current.focus()}catch(A){w(),v(A instanceof Error?A.message:"Forge could not start the Microsoft sign-in flow.")}},S=d.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:(p,A)=>e.jsxs("div",{className:"grid gap-5",children:[e.jsx(se,{label:"Provider",description:"Each setup path is guided. Forge discovers calendars before anything is saved.",children:e.jsx(Ze,{value:p.provider,onChange:T=>{f(null),v(null),w(),A(qr(T))},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(qp,{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:p.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(Hi,{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:p.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(N1,{provider:p.provider,compact:!0})})]})]})},{id:"credentials",eyebrow:"Credentials",title:o.provider==="google"?"Provide the Google CalDAV credentials":o.provider==="apple"?"Provide the Apple account email and app-specific password":o.provider==="microsoft"?"Sign in with Microsoft":"Provide the custom CalDAV base URL and credentials",description:o.provider==="apple"?"Apple discovery starts from https://caldav.icloud.com, so you only need the Apple ID email and app password here.":o.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:(p,A)=>e.jsxs("div",{className:"grid gap-4",children:[e.jsx(se,{label:"Connection label",description:"This is the readable label Forge shows in settings and the calendar health cards.",children:e.jsx(le,{value:p.label,onChange:T=>A({label:T.target.value}),placeholder:$n[p.provider].label})}),p.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(L,{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:n.clientId||"Not configured yet"})]}),e.jsxs("div",{children:["Tenant:"," ",e.jsx("span",{className:"font-medium text-white",children:n.tenantId})]}),e.jsxs("div",{className:"break-all",children:["Redirect URI:"," ",e.jsx("span",{className:"font-medium text-white",children:n.redirectUri})]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-3",children:[e.jsxs(Q,{type:"button",onClick:()=>void j(),disabled:!n.isReadyForSignIn,pending:(h==null?void 0:h.status)==="pending",pendingLabel:"Waiting for Microsoft",children:[e.jsx(Wi,{className:"size-4"}),(h==null?void 0:h.status)==="authorized"?"Sign in again":"Sign in with Microsoft"]}),h!=null&&h.accountLabel?e.jsxs(L,{className:"bg-emerald-500/16 text-emerald-100",children:[e.jsx(Pl,{className:"mr-1 size-3.5"}),h.accountLabel]}):null]}),e.jsxs("div",{className:"mt-4 grid gap-3 md:grid-cols-2",children:[e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/68",children:"Users do not paste client secrets or refresh tokens here."}),e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm leading-6 text-white/68",children:"After sign-in, Forge will let you choose which Exchange Online calendars to mirror into the Calendar page."})]}),n.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:n.setupMessage})]})}):e.jsxs(e.Fragment,{children:[p.provider==="caldav"?e.jsx(se,{label:"CalDAV base URL",description:"Use the account-level CalDAV server URL, not an individual calendar collection URL.",children:e.jsx(le,{value:p.serverUrl,onChange:T=>A({serverUrl:T.target.value}),placeholder:"https://caldav.example.com"})}):null,p.provider==="apple"?e.jsx(se,{label:"Apple CalDAV base URL",children:e.jsx(le,{value:"https://caldav.icloud.com",disabled:!0})}):null,e.jsx(se,{label:"Account email or username",children:e.jsx(le,{value:p.username,onChange:T=>A({username:T.target.value}),placeholder:"operator@example.com"})}),p.provider==="google"?e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Google client ID",children:e.jsx(le,{value:p.clientId,onChange:T=>A({clientId:T.target.value}),placeholder:"1234567890-abcdef.apps.googleusercontent.com"})}),e.jsx(se,{label:"Google client secret",children:e.jsx(le,{type:"password",value:p.clientSecret,onChange:T=>A({clientSecret:T.target.value}),placeholder:"GOCSPX-..."})}),e.jsx(se,{label:"Refresh token",children:e.jsx(le,{type:"password",value:p.refreshToken,onChange:T=>A({refreshToken:T.target.value}),placeholder:"1//0g..."})})]}):e.jsx(se,{label:p.provider==="apple"?"App-specific password":"Password or app password",children:e.jsx(le,{type:"password",value:p.password,onChange:T=>A({password:T.target.value}),placeholder:"Password"})})]})]})},{id:"discovery",eyebrow:"Discovery",title:"Discover the calendars and choose what Forge should sync",description:o.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:(p,A)=>e.jsxs("div",{className:"grid gap-4",children:[p.provider==="microsoft"?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(Q,{type:"button",onClick:()=>void j(),pending:(h==null?void 0:h.status)==="pending",pendingLabel:"Waiting for Microsoft",children:[e.jsx(Wi,{className:"size-4"}),(h==null?void 0:h.status)==="authorized"?"Reconnect Microsoft":"Sign in with Microsoft"]}),u?e.jsxs(L,{className:"bg-white/[0.08] text-white/74",children:[u.calendars.length," discovered"]}):null]}):e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(Q,{pending:E.isPending,pendingLabel:"Discovering",onClick:()=>void E.mutateAsync(),children:[e.jsx(Is,{className:"size-4"}),"Discover calendars"]}),u?e.jsxs(L,{className:"bg-white/[0.08] text-white/74",children:[u.calendars.length," discovered"]}):null]}),u?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:u.serverUrl}),u.homeUrl?e.jsxs(e.Fragment,{children:[" ","· home set"," ",e.jsx("span",{className:"font-medium text-white",children:u.homeUrl})]}):null]}),e.jsx("div",{className:"grid gap-3",children:u.calendars.map(T=>{const k=p.selectedCalendarUrls.includes(T.url),$=p.forgeCalendarUrl===T.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:T.displayName}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[T.timezone||"No timezone exposed"," ·"," ",T.url]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[T.isForgeCandidate?e.jsx(L,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"Forge match"}):null,T.isPrimary?e.jsx(L,{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:()=>A({selectedCalendarUrls:k?p.selectedCalendarUrls.filter(g=>g!==T.url):[...p.selectedCalendarUrls,T.url]}),className:`rounded-full px-3 py-2 text-sm transition ${k?"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:k?"Mirrored":"Mirror into Forge"}),p.provider!=="microsoft"?e.jsx("button",{type:"button",onClick:()=>A({forgeCalendarUrl:T.url,createForgeCalendar:!1}),className:`rounded-full px-3 py-2 text-sm transition ${$?"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:$?"Forge writes here":"Use for Forge writes"}):e.jsx(L,{className:"bg-sky-400/12 text-sky-100",children:"Read only"})]})]},T.url)})}),p.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:()=>A({forgeCalendarUrl:null,createForgeCalendar:!p.createForgeCalendar}),className:`rounded-full px-3 py-2 text-sm transition ${p.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:p.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:p.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:p=>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(fs,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-display text-xl text-white",children:Ii(p.provider,p.label)}),e.jsx("div",{className:"mt-1 text-sm text-white/58",children:p.provider==="google"?"Google Calendar":p.provider==="apple"?"Apple Calendar":p.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:p.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:p.provider==="microsoft"?"read only":p.forgeCalendarUrl?"existing calendar":p.createForgeCalendar?"new Forge calendar":"not selected"})]})]})]})})}],[u,E.isPending,o.provider,h]);return e.jsx(rt,{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:o,onChange:p=>{c(p),u&&p.provider!==u.provider&&f(null)},steps:S,submitLabel:"Connect provider",pending:l,pendingLabel:"Connecting",error:x,initialStepId:a,onSubmit:async()=>{try{if(v(null),!u){v("Discover the available calendars before saving the connection.");return}if(o.selectedCalendarUrls.length===0){v("Select at least one calendar to mirror into Forge.");return}if(o.provider!=="microsoft"&&!o.forgeCalendarUrl&&!o.createForgeCalendar){v("Choose the calendar Forge should write into, or ask Forge to create one.");return}if(o.provider==="google")await r({provider:"google",label:Ii("google",o.label),username:o.username.trim(),clientId:o.clientId.trim(),clientSecret:o.clientSecret.trim(),refreshToken:o.refreshToken.trim(),selectedCalendarUrls:o.selectedCalendarUrls,forgeCalendarUrl:o.forgeCalendarUrl,createForgeCalendar:o.createForgeCalendar});else if(o.provider==="apple")await r({provider:"apple",label:Ii("apple",o.label),username:o.username.trim(),password:o.password.trim(),selectedCalendarUrls:o.selectedCalendarUrls,forgeCalendarUrl:o.forgeCalendarUrl,createForgeCalendar:o.createForgeCalendar});else if(o.provider==="microsoft"){if(!(h!=null&&h.sessionId)||h.status!=="authorized"){v("Complete the Microsoft sign-in flow before saving this connection.");return}await r({provider:"microsoft",label:Ii("microsoft",o.label),authSessionId:h.sessionId,selectedCalendarUrls:o.selectedCalendarUrls})}else await r({provider:"caldav",label:Ii("caldav",o.label),serverUrl:o.serverUrl.trim(),username:o.username.trim(),password:o.password.trim(),selectedCalendarUrls:o.selectedCalendarUrls,forgeCalendarUrl:o.forgeCalendarUrl,createForgeCalendar:o.createForgeCalendar});s(!1)}catch(p){v(p instanceof Error?p.message:"Forge could not create this calendar connection.")}}})}function Ti(t){try{const s=new URL(t);return s.pathname.endsWith("/")||(s.pathname=`${s.pathname}/`),s.toString()}catch{return t}}function Oc(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 Fc="/api/v1/calendar/oauth/microsoft/callback",S1=/^[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 _c(t){return{clientId:t.clientId,tenantId:t.tenantId,redirectUri:t.redirectUri}}function C1(t){const s={};if(t.clientId.trim()?S1.test(t.clientId.trim())||(s.clientId="Use the Microsoft app registration client ID GUID."):s.clientId="Microsoft client ID is required.",!t.redirectUri.trim())s.redirectUri="Redirect URI is required.";else try{const i=new URL(t.redirectUri.trim());i.protocol!=="http:"&&i.protocol!=="https:"?s.redirectUri="Redirect URI must use http or https.":i.pathname!==Fc&&(s.redirectUri=`Redirect URI must end with ${Fc}.`)}catch{s.redirectUri="Redirect URI must be a full URL."}return{issues:s,isValid:Object.keys(s).length===0}}function I1(t,s){return t.clientId.trim()===s.clientId.trim()&&t.tenantId.trim()===s.tenantId.trim()&&t.redirectUri.trim()===s.redirectUri.trim()}function T1(){var y,P,q,pe,ee;const t=We(),[s,i]=Pt(),[a,n]=d.useState(!1),[r,l]=d.useState("google"),[o,c]=d.useState(void 0),[x,v]=d.useState(null),[u,f]=d.useState([]),[h,m]=d.useState(!1),[b,w]=d.useState(null),[M,E]=d.useState(()=>vm()),[D,j]=d.useState({clientId:"",tenantId:"common",redirectUri:""}),S=fe({queryKey:["forge-operator-session"],queryFn:Zi}),p=S.isSuccess,A=fe({queryKey:["forge-settings"],queryFn:vi,enabled:p}),T=fe({queryKey:["forge-calendar-connections"],queryFn:Ug,enabled:p}),k=fe({queryKey:["forge-calendar-resources"],queryFn:Zg,enabled:p}),$=async()=>{await Promise.all([t.invalidateQueries({queryKey:["forge-settings"]}),t.invalidateQueries({queryKey:["forge-calendar-connections"]}),t.invalidateQueries({queryKey:["forge-calendar-resources"]}),t.invalidateQueries({queryKey:["forge-calendar-overview"]}),t.invalidateQueries({queryKey:["forge-snapshot"]})])},g=xe({mutationFn:Xg,onSuccess:$}),C=xe({mutationFn:Y=>Vg(Y),onSuccess:$}),F=xe({mutationFn:({connectionId:Y,patch:R})=>Jg(Y,R),onSuccess:$}),z=xe({mutationFn:Y=>Yg(Y),onSuccess:$}),J=xe({mutationFn:Y=>Kl({calendarProviders:{microsoft:Y}}),onSuccess:$}),O=xe({mutationFn:Y=>Wg({clientId:Y.clientId.trim(),tenantId:Y.tenantId.trim()||"common",redirectUri:Y.redirectUri.trim()})});d.useEffect(()=>{if(!p)return;const Y=s.get("intent"),R=s.get("provider");if(Y!=="connect")return;l(R==="apple"||R==="caldav"||R==="google"||R==="microsoft"?R:"google"),c(R==="microsoft"?"credentials":void 0),n(!0);const X=new URLSearchParams(s);X.delete("intent"),X.delete("provider"),i(X,{replace:!0})},[p,s,i]),d.useEffect(()=>{var R;const Y=(R=A.data)==null?void 0:R.settings.calendarProviders.microsoft;Y&&j(_c(Y))},[A.data]);const _=d.useMemo(()=>{var R;const Y=new Map;for(const X of((R=k.data)==null?void 0:R.calendars)??[]){const be=Y.get(X.connectionId)??[];be.push(X),Y.set(X.connectionId,be)}return Y},[k.data]),B=d.useMemo(()=>{var Y;return ym(((Y=k.data)==null?void 0:Y.calendars)??[],M.calendarColors)},[(y=k.data)==null?void 0:y.calendars,M.calendarColors]),K=d.useMemo(()=>{var Y;return((Y=T.data)==null?void 0:Y.connections.find(R=>R.id===x))??null},[T.data,x]),Z=d.useMemo(()=>{var Y;return((Y=T.data)==null?void 0:Y.connections.find(R=>R.id===b))??null},[T.data,b]),U=d.useMemo(()=>x?_.get(x)??[]:[],[_,x]),I=((P=A.data)==null?void 0:P.settings.calendarProviders.microsoft)??null,G=d.useMemo(()=>C1(D),[D]),W=I!==null&&!I1(D,_c(I)),ne=!(I!=null&&I.isReadyForSignIn)||!G.isValid||W||J.isPending,de=fe({queryKey:["forge-calendar-connection-discovery",x],queryFn:()=>Gg(x),enabled:p&&x!==null});d.useEffect(()=>{if(!x){f([]),m(!1);return}const Y=U.filter(R=>R.selectedForSync).map(R=>Ti(R.remoteId));f(Y),m(!0)},[x,U]),d.useEffect(()=>{Kv(M)},[M]);const we=d.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:(Y,R)=>{var te,ce;if(de.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(de.isError||!((te=de.data)!=null&&te.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:de.error instanceof Error?de.error.message:"Forge could not rediscover calendars for this connection."});const X=de.data.discovery,be=(K==null?void 0:K.provider)==="microsoft",Ie=typeof((ce=K==null?void 0:K.config)==null?void 0:ce.forgeCalendarUrl)=="string"?Ti(K.config.forgeCalendarUrl):null;return e.jsx("div",{className:"grid gap-3",children:X.calendars.map(Se=>{const he=Ti(Se.url),Ge=h?Y.selectedCalendarUrls.includes(he):U.some(ue=>ue.selectedForSync&&Ti(ue.remoteId)===he),De=Ie===he;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:Se.displayName}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[Se.timezone||"No timezone exposed"," · ",Se.url]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[De&&!be?e.jsx(L,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"Forge writes here"}):null,be?e.jsx(L,{className:"bg-sky-400/12 text-sky-100",children:"Read only"}):null,Se.isPrimary?e.jsx(L,{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:De&&!be,onClick:()=>R({selectedCalendarUrls:Ge?Y.selectedCalendarUrls.filter(ue=>ue!==he):[...Y.selectedCalendarUrls,he]}),className:`rounded-full px-3 py-2 text-sm transition ${De&&!be?"cursor-not-allowed bg-white/[0.05] text-white/35":Ge?"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:De&&!be?"Always available for Forge writes":Ge?"Mirrored into Forge":"Do not mirror"})})]},Se.url)})})}}],[K,de]);if(S.isLoading||A.isLoading||T.isLoading||k.isLoading)return e.jsx(It,{eyebrow:"Settings · Calendar",title:"Loading calendar settings",description:"Checking the operator session and loading provider connections.",columns:2,blocks:6});if(S.isError)return e.jsx(ze,{eyebrow:"Settings · Calendar",error:S.error,onRetry:()=>void S.refetch()});if(A.isError||T.isError||k.isError||!((q=A.data)!=null&&q.settings)||!T.data||!k.data)return e.jsx(ze,{eyebrow:"Settings · Calendar",error:A.error??T.error??k.error??new Error("Calendar settings are unavailable."),onRetry:()=>{A.refetch(),T.refetch(),k.refetch()}});const{providers:Ne,connections:H}=T.data,me=A.data.settings.calendarProviders.microsoft;return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(qe,{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:`${H.length} connection${H.length===1?"":"s"}`}),e.jsx(vs,{}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ae,{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(L,{className:"bg-sky-400/12 text-sky-100",children:"Read only"}),me.isReadyForSignIn&&!W?e.jsxs(L,{className:"bg-emerald-500/16 text-emerald-100",children:[e.jsx(Pl,{className:"mr-1 size-3.5"}),"Ready for sign-in"]}):e.jsxs(L,{className:"bg-white/[0.08] text-white/74",children:[e.jsx(Hi,{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:D.clientId,onChange:Y=>j(R=>({...R,clientId:Y.target.value})),placeholder:"00000000-0000-0000-0000-000000000000"}),G.issues.clientId?e.jsx("span",{className:"text-sm text-rose-300",children:G.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:D.tenantId,onChange:Y=>j(R=>({...R,tenantId:Y.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(L,{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:D.redirectUri,onChange:Y=>j(R=>({...R,redirectUri:Y.target.value})),placeholder:"http://127.0.0.1:4317/api/v1/calendar/oauth/microsoft/callback"}),G.issues.redirectUri?e.jsx("span",{className:"text-sm text-rose-300",children:G.issues.redirectUri}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Q,{onClick:()=>void J.mutateAsync({clientId:D.clientId.trim(),tenantId:D.tenantId.trim()||"common",redirectUri:D.redirectUri.trim()}),disabled:!G.isValid,pending:J.isPending,pendingLabel:"Saving",children:"Save Microsoft settings"}),e.jsx(Q,{variant:"secondary",onClick:()=>void O.mutateAsync(D),disabled:!G.isValid,pending:O.isPending,pendingLabel:"Testing",children:"Test Microsoft configuration"}),e.jsxs(Q,{variant:"secondary",onClick:()=>{l("microsoft"),c("credentials"),n(!0)},disabled:ne,children:[e.jsx(Wi,{className:"size-4"}),"Sign in with Microsoft"]})]}),J.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:J.error.message}):null,O.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:O.data.result.message}):null,O.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:O.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:me.clientId||"Not saved yet"})]}),e.jsxs("div",{children:["Tenant:"," ",e.jsx("span",{className:"font-medium text-white",children:me.tenantId})]}),e.jsxs("div",{className:"break-all",children:["Redirect URI:"," ",e.jsx("span",{className:"font-medium text-white",children:me.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:W?"Save these Microsoft settings before you try to sign in, otherwise the popup will still use the previous saved configuration.":me.setupMessage})]})]})]}),e.jsxs(ae,{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(L,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[e.jsx(vh,{className:"mr-1 size-3.5"}),"Settings-owned"]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Ne.map(Y=>e.jsxs("button",{type:"button",onClick:()=>{l(Y.provider),c(Y.provider==="microsoft"?"credentials":void 0),n(!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(fs,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:Y.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:Y.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"})]},Y.provider))})]}),e.jsxs(ae,{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:()=>E(Y=>({...Y,useCalendarColors:!Y.useCalendarColors})),className:`rounded-full px-4 py-2 text-sm transition ${M.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:M.useCalendarColors?"Colors on":"Colors off"})]}),(((pe=k.data)==null?void 0:pe.calendars)??[]).length>0?e.jsx("div",{className:"grid gap-3",children:(((ee=k.data)==null?void 0:ee.calendars)??[]).map(Y=>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:B[Y.id]}}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate font-medium text-white",children:Y.title}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[Y.canWrite?"Writable":"Read only"," · ",Y.timezone]})]})]})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{"aria-label":`Choose display color for ${Y.title}`,type:"color",value:B[Y.id],onChange:R=>E(X=>({...X,calendarColors:{...X.calendarColors,[Y.id]:R.target.value}})),className:"h-10 w-12 cursor-pointer rounded-[14px] border border-white/12 bg-transparent p-1"}),e.jsx(Q,{size:"sm",variant:"secondary",onClick:()=>E(R=>{const X={...R.calendarColors};return delete X[Y.id],{...R,calendarColors:X}}),children:"Reset palette"})]})]},Y.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(ae,{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."})]})}),H.length>0?e.jsx("div",{className:"grid gap-3",children:H.map(Y=>{var X;const R=_.get(Y.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:Y.label}),e.jsxs("div",{className:"mt-1 text-sm text-white/55",children:[Oc(Y.provider)," · ",Y.accountLabel||"No account label yet"]}),Y.lastSyncedAt?e.jsxs("div",{className:"mt-2 text-sm text-white/48",children:["Last synced ",new Date(Y.lastSyncedAt).toLocaleString()]}):null,Y.lastSyncError?e.jsx("div",{className:"mt-2 text-sm text-rose-200",children:Y.lastSyncError}):null]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(L,{className:"bg-white/[0.08] text-white/74",children:Y.status}),((X=Y.config)==null?void 0:X.readOnly)===!0?e.jsx(L,{className:"bg-sky-400/12 text-sky-100",children:"Read only"}):null,e.jsxs(Q,{size:"sm",variant:"secondary",pending:C.isPending&&C.variables===Y.id,pendingLabel:"Syncing",onClick:()=>void C.mutateAsync(Y.id),children:[e.jsx(Is,{className:"size-4"}),"Sync"]}),e.jsxs(Q,{size:"sm",variant:"secondary",onClick:()=>{const be=(_.get(Y.id)??[]).filter(Ie=>Ie.selectedForSync).map(Ie=>Ti(Ie.remoteId));f(be),m(!0),v(Y.id)},children:[e.jsx(bh,{className:"size-4"}),"Manage mirrored calendars"]}),e.jsxs(Q,{size:"sm",variant:"secondary",onClick:()=>w(Y.id),children:[e.jsx(ct,{className:"size-4"}),"Remove"]})]})]}),e.jsx("div",{className:"mt-4 grid gap-2",children:R.map(be=>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:be.title}),e.jsxs("div",{className:"mt-1 text-xs uppercase tracking-[0.16em] text-white/45",children:[be.canWrite?"Writable":"Read only"," · ",be.timezone]})]}),be.forgeManaged?e.jsx(L,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"Forge"}):e.jsxs(L,{className:"bg-white/[0.08] text-white/74",children:[e.jsx(Xt,{className:"mr-1 size-3.5"}),"Mirrored"]})]},be.id))})]},Y.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(k1,{open:a,onOpenChange:Y=>{n(Y),Y||c(void 0)},initialProvider:r,initialStepId:o,microsoftSetup:me,pending:g.isPending,onSubmit:async Y=>{await g.mutateAsync(Y)}}),e.jsx(rt,{open:x!==null,onOpenChange:Y=>{Y||v(null)},eyebrow:"Calendar settings",title:"Manage mirrored calendars",description:"Choose which calendars this connection should mirror into Forge.",value:{selectedCalendarUrls:u},onChange:Y=>f(Y.selectedCalendarUrls),steps:we,pending:F.isPending,pendingLabel:"Saving",submitLabel:"Save mirror selection",error:F.error instanceof Error?F.error.message:null,onSubmit:async()=>{x&&(await F.mutateAsync({connectionId:x,patch:{selectedCalendarUrls:u.map(Ti)}}),m(!1),v(null))}}),e.jsx(rt,{open:b!==null,onOpenChange:Y=>{Y||w(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:Z?`Remove ${Z.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:Z?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"font-medium text-white",children:[Oc(Z.provider)," · ",Z.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:z.isPending,pendingLabel:"Removing",submitLabel:"Remove connection",error:z.error instanceof Error?z.error.message:null,onSubmit:async()=>{b&&(await z.mutateAsync(b),w(null))}})]})}function P1(t){return t.replaceAll("."," ")}function M1(t){const s=typeof t.sleepSessions=="number"?t.sleepSessions:0,i=typeof t.workouts=="number"?t.workouts:0;return`${s} sleep · ${i} workouts`}function Rc(t){return t?"signal":"meta"}function A1(){const t=Je(),s=We(),i=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],a=Mt(i),[n,r]=d.useState(null),[l,o]=d.useState(!1),[c,x]=d.useState(null),v=fe({queryKey:["forge-companion-overview",...i],queryFn:async()=>(await $f(i)).overview}),u=xe({mutationFn:async()=>Zf({userId:a??null}),onSuccess:async E=>{x({qrPayload:E.qrPayload}),o(!0),await s.invalidateQueries({queryKey:["forge-companion-overview"]})}}),f=xe({mutationFn:async E=>eb(E),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-companion-overview"]})}}),h=xe({mutationFn:async()=>tb({userIds:i,includeRevoked:!1}),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-companion-overview"]})}});if(d.useEffect(()=>{if(!c){r(null);return}Bp.toDataURL(JSON.stringify(c.qrPayload),{width:320,margin:1}).then(r)},[c]),v.isLoading)return e.jsx(It,{eyebrow:"Companion",title:"Loading mobile companion",description:"Checking pairing state and recent sync status.",columns:2,blocks:5});if(v.isError||!v.data)return e.jsx(ze,{eyebrow:"Companion",error:v.error??new Error("Companion overview unavailable"),onRetry:()=>void v.refetch()});const m=v.data,b=m.pairings.filter(E=>E.status!=="revoked"),w=m.pairings.length-b.length,M=async()=>{if(c&&l){o(!1);return}if(c&&!l){o(!0);return}await u.mutateAsync()};return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(qe,{title:"Mobile companion",description:"Pair the native iPhone companion, sync Apple Health, and keep the bridge open for watch and location signals.",badge:m.healthState.replaceAll("_"," ")}),e.jsx(vs,{}),e.jsxs("section",{className:"grid gap-4",children:[e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Pair iPhone"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Open a pairing QR only when you need it"}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:"Keep the page compact by generating or reopening the one-time QR only when you are about to scan it from Forge Companion."})]}),e.jsxs(Q,{onClick:()=>void M(),pending:u.isPending,pendingLabel:"Generating",children:[e.jsx(Kp,{className:"size-4"}),c?l?"Hide QR":"Show QR":"Generate QR",c?l?e.jsx(Bn,{className:"size-4"}):e.jsx(Ji,{className:"size-4"}):null]})]}),l?e.jsxs("div",{className:"grid gap-4 rounded-[24px] border border-white/8 bg-white/[0.03] p-4 sm:p-5",children:[n?e.jsxs("div",{className:"grid justify-items-center gap-4 rounded-[24px] bg-white px-6 py-6 text-slate-950",children:[e.jsx("img",{src:n,alt:"Forge Companion pairing QR code",className:"w-full max-w-[320px]"}),e.jsx("div",{className:"max-w-[320px] text-center text-sm text-slate-600",children:"Scan this in the iOS companion to pass the Forge API address and the one-time pairing token."})]}):e.jsx("div",{className:"rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] px-5 py-8 text-center text-sm text-white/55",children:"Generating the QR code now."}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"text-sm text-white/62",children:c?e.jsxs(e.Fragment,{children:["Expires"," ",new Date(c.qrPayload.expiresAt).toLocaleString(),"."]}):"Generate the one-time QR and scan it from the iPhone app."}),c?e.jsxs(Q,{variant:"secondary",pending:u.isPending,pendingLabel:"Generating",onClick:()=>void u.mutateAsync(),children:[e.jsx(Is,{className:"size-4"}),"Regenerate QR"]}):null]}),c?e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] p-4 text-sm text-white/62",children:[e.jsx("div",{className:"rounded-[16px] bg-slate-950/60 p-3 font-mono text-[11px] leading-5 text-white/70",children:JSON.stringify(c.qrPayload,null,2)}),e.jsx("div",{className:"text-xs text-white/45",children:"The same payload can be pasted into the iPhone app if the camera path is unavailable."})]}):null]}):e.jsx("div",{className:"rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] px-5 py-6 text-sm text-white/55",children:"Tap the QR button when you actually want to pair a phone."})]}),e.jsxs(ae,{className:"grid gap-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Companion state"}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Pairings"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:b.length}),w>0?e.jsxs("div",{className:"mt-2 text-xs text-white/42",children:[w," revoked hidden"]}):null]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Sleep sessions"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:m.counts.sleepSessions})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Workouts"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:m.counts.workouts})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Reflected sleep"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:m.counts.reflectiveSleepSessions})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Linked workouts"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:m.counts.linkedWorkouts})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Habit-generated"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:m.counts.habitGeneratedWorkouts})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Reconciled"}),e.jsx("div",{className:"mt-2 font-display text-3xl text-white",children:m.counts.reconciledWorkouts})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(L,{children:m.healthState.replaceAll("_"," ")}),m.lastSyncAt?e.jsxs(L,{tone:"meta",children:["Last sync ",new Date(m.lastSyncAt).toLocaleString()]}):null,e.jsxs(L,{tone:Rc(m.permissions.healthKitAuthorized),children:["HealthKit ",m.permissions.healthKitAuthorized?"ready":"needed"]}),e.jsxs(L,{tone:Rc(m.permissions.backgroundRefreshEnabled),children:["Background refresh"," ",m.permissions.backgroundRefreshEnabled?"ready":"not yet"]}),e.jsxs(L,{tone:"meta",children:["Location ",m.permissions.locationReady?"ready":"later"]}),e.jsxs(L,{tone:"meta",children:["Motion ",m.permissions.motionReady?"ready":"later"]})]}),e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Pairing path"}),e.jsxs("div",{className:"grid gap-2 text-sm text-white/62",children:[e.jsx("div",{children:"1. Generate a one-time QR code here inside Forge Settings."}),e.jsx("div",{children:"2. Scan it in Forge Companion to pass the API URL and pairing token."}),e.jsx("div",{children:"3. Approve Health access on iPhone, then run the first sync."}),e.jsx("div",{children:"4. Review import history below and open Sleep or Sports to enrich the imported records."})]})]}),e.jsxs("div",{className:"grid gap-3",children:[b.length>0?e.jsx("div",{className:"flex justify-end",children:e.jsxs(Q,{variant:"secondary",pending:h.isPending,pendingLabel:"Revoking all",onClick:()=>void h.mutateAsync(),children:[e.jsx(Qo,{className:"size-4"}),"Revoke all"]})}):null,b.map(E=>e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] px-4 py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-base text-white",children:E.deviceName??E.label}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[E.platform??"ios"," · ",E.status]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(L,{tone:E.status==="healthy"?"signal":"meta",children:E.status.replaceAll("_"," ")}),E.lastSyncAt?e.jsxs(L,{tone:"meta",children:["Synced ",new Date(E.lastSyncAt).toLocaleString()]}):null]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:E.capabilities.map(D=>e.jsx(L,{tone:"meta",size:"sm",wrap:!0,children:P1(D)},D))}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 text-sm text-white/55",children:[e.jsxs("div",{className:"grid gap-1",children:[e.jsx("div",{children:E.apiBaseUrl}),e.jsxs("div",{children:["Expires ",new Date(E.expiresAt).toLocaleString()]}),E.lastSyncError?e.jsx("div",{className:"text-rose-200/80",children:E.lastSyncError}):null]}),e.jsxs(Q,{variant:"secondary",pending:f.isPending&&f.variables===E.id,pendingLabel:"Revoking",disabled:E.status==="revoked",onClick:()=>void f.mutateAsync(E.id),children:[e.jsx(Qo,{className:"size-4"}),E.status==="revoked"?"Revoked":"Revoke"]})]})]},E.id)),b.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-6 text-sm text-white/55",children:"No companion paired yet. Generate a QR code, then open the iOS companion and scan it."}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(Q,{variant:"secondary",onClick:()=>void v.refetch(),children:[e.jsx(Is,{className:"size-4"}),"Refresh status"]}),e.jsxs(Ae,{to:"/sleep",className:"inline-flex min-h-11 items-center gap-2 rounded-[16px] border border-white/8 bg-white/[0.03] px-4 py-3 text-sm text-white/72 transition hover:bg-white/[0.06] hover:text-white",children:[e.jsx(fs,{className:"size-4"}),"Open sleep view"]}),e.jsxs(Ae,{to:"/sports",className:"inline-flex min-h-11 items-center gap-2 rounded-[16px] border border-white/8 bg-white/[0.03] px-4 py-3 text-sm text-white/72 transition hover:bg-white/[0.06] hover:text-white",children:[e.jsx(fs,{className:"size-4"}),"Open sports view"]})]})]})]}),e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Sync history"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Recent HealthKit import runs"})]}),e.jsxs(L,{tone:"meta",children:[m.importRuns.length," recent runs"]})]}),e.jsxs("div",{className:"grid gap-3",children:[m.importRuns.map(E=>e.jsxs("div",{className:"grid gap-3 rounded-[18px] bg-white/[0.04] px-4 py-4 lg:grid-cols-[minmax(0,1fr)_auto]",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Up,{className:"size-4 text-white/55"}),e.jsxs("div",{className:"text-base text-white",children:[E.sourceDevice||"iPhone"," import"]}),e.jsx(L,{tone:E.status==="completed"?"signal":"meta",children:E.status})]}),e.jsxs("div",{className:"text-sm text-white/60",children:[new Date(E.importedAt).toLocaleString()," ·"," ",M1(E.payloadSummary)]}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-sm text-white/60",children:[e.jsxs(L,{tone:"meta",children:["Imported ",E.importedCount]}),e.jsxs(L,{tone:"meta",children:["Created ",E.createdCount]}),e.jsxs(L,{tone:"meta",children:["Updated ",E.updatedCount]}),e.jsxs(L,{tone:"meta",children:["Merged ",E.mergedCount]})]}),E.errorMessage?e.jsx("div",{className:"text-sm text-rose-200/80",children:E.errorMessage}):null]}),E.pairingSessionId?e.jsxs("div",{className:"text-sm text-white/45 lg:text-right",children:["Pairing ",E.pairingSessionId]}):null]},E.id)),m.importRuns.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-6 text-sm text-white/55",children:"No sync runs yet. Pair the iPhone companion and run the first HealthKit import."}):null]})]})]})}function Br(t="openai-api"){return{label:t==="openai-codex"?"OpenAI Codex":t==="openai-compatible"?"Local compatible endpoint":"OpenAI API",provider:t,baseUrl:t==="openai-codex"?"https://chatgpt.com/backend-api":t==="openai-compatible"?"http://127.0.0.1:11434/v1":"https://api.openai.com/v1",model:"gpt-5.4-mini",apiKey:""}}function E1(t){return{id:t.id,label:t.label,provider:t.provider,baseUrl:t.baseUrl,model:t.model,apiKey:""}}function L1(){var z,J,O;const t=We(),[s,i]=d.useState(()=>Br()),[a,n]=d.useState(""),[r,l]=d.useState("gpt-5.4-mini"),[o,c]=d.useState(""),[x,v]=d.useState("gpt-5.4-mini"),[u,f]=d.useState(""),[h,m]=d.useState(null),[b,w]=d.useState(null),M=fe({queryKey:["forge-settings"],queryFn:vi}),E=fe({queryKey:["forge-openai-codex-oauth",h],queryFn:async()=>{if(!h)throw new Error("Missing OAuth session id");return await jf(h)},enabled:!!h,refetchInterval:_=>{var K;const B=(K=_.state.data)==null?void 0:K.session.status;return B&&["authorized","error","consumed","expired"].includes(B)?!1:1500}}),D=async()=>{await t.invalidateQueries({queryKey:["forge-settings"]}),await t.invalidateQueries({queryKey:["forge-openai-codex-oauth",h]})},j=xe({mutationFn:()=>Kl({modelSettings:{forgeAgent:{basicChat:{connectionId:a||null,model:r},wiki:{connectionId:o||null,model:x}}}}),onSuccess:D}),S=xe({mutationFn:()=>bf({id:s.id,label:s.label,provider:s.provider,authMode:s.provider==="openai-codex"?"oauth":"api_key",baseUrl:s.baseUrl,model:s.model,apiKey:s.provider==="openai-codex"?void 0:s.apiKey||void 0,oauthSessionId:s.provider==="openai-codex"?h??void 0:void 0}),onSuccess:async()=>{w("Connection saved."),s.provider==="openai-codex"&&(m(null),f("")),i(Br(s.provider)),await D()}}),p=xe({mutationFn:vf,onSuccess:D}),A=xe({mutationFn:async()=>wf({connectionId:s.id,provider:s.provider,baseUrl:s.baseUrl,model:s.model,apiKey:s.provider==="openai-codex"?void 0:s.apiKey||void 0}),onSuccess:({result:_})=>{w(`Connection test succeeded: ${_.outputPreview}`)},onError:_=>{w(_ instanceof Error?_.message:"Connection test failed.")}}),T=xe({mutationFn:yf,onSuccess:({session:_})=>{m(_.id),w("OpenAI Codex OAuth started."),_.authUrl&&window.open(_.authUrl,"_blank","noopener,noreferrer")}}),k=xe({mutationFn:async()=>{if(!h)throw new Error("No OAuth session started yet.");return await Nf(h,u)},onSuccess:({session:_})=>{w(_.status==="authorized"?"OpenAI Codex OAuth authorized.":"Manual OAuth code submitted.")}});d.useEffect(()=>{var B;const _=(B=M.data)==null?void 0:B.settings;_&&(n(_.modelSettings.forgeAgent.basicChat.connectionId??""),l(_.modelSettings.forgeAgent.basicChat.model),c(_.modelSettings.forgeAgent.wiki.connectionId??""),v(_.modelSettings.forgeAgent.wiki.model))},[M.data]);const $=((z=M.data)==null?void 0:z.settings.modelSettings.connections)??[],g=((J=E.data)==null?void 0:J.session)??null,C=d.useMemo(()=>!s.label.trim()||!s.model.trim()?!1:s.provider==="openai-codex"?!!(s.id||(g==null?void 0:g.status)==="authorized"):s.apiKey.trim().length>0||!!s.id,[s,g==null?void 0:g.status]);if(M.isLoading)return e.jsx(nt,{eyebrow:"Models",title:"Loading model settings",description:"Fetching Forge agent defaults and configured AI connections."});if(M.isError||!((O=M.data)!=null&&O.settings))return e.jsx(ze,{eyebrow:"Models",error:M.error??new Error("Forge returned an empty model settings payload."),onRetry:()=>void M.refetch()});const F=M.data.settings;return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1440px] gap-5",children:[e.jsx(qe,{eyebrow:"AI runtime",title:"Model Settings",description:"Manage Forge Agent defaults, OpenAI OAuth/API connections, and local OpenAI-compatible endpoints as first-class chat agents.",badge:`${$.length} model connection${$.length===1?"":"s"}`}),e.jsx(vs,{}),e.jsxs(ae,{className:"grid gap-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ui,{className:"size-4 text-[var(--secondary)]"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-white",children:"Forge Agent defaults"}),e.jsx("div",{className:"text-xs leading-5 text-white/52",children:"Forge Agent stays the default system agent. Choose which model connection powers basic chat and the managed wiki workflow."})]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("span",{className:"text-sm text-white/72",children:"Basic chat connection"}),e.jsxs("select",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:a,onChange:_=>n(_.target.value),children:[e.jsx("option",{value:"",children:"No external connection"}),$.map(_=>e.jsxs("option",{value:_.id,children:[_.label," (",_.agentLabel,")"]},_.id))]}),e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:r,onChange:_=>l(_.target.value),placeholder:"Model"})]}),e.jsxs("label",{className:"grid gap-2 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("span",{className:"text-sm text-white/72",children:"Wiki model connection"}),e.jsxs("select",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:o,onChange:_=>c(_.target.value),children:[e.jsx("option",{value:"",children:"No external connection"}),$.map(_=>e.jsxs("option",{value:_.id,children:[_.label," (",_.agentLabel,")"]},_.id))]}),e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:x,onChange:_=>v(_.target.value),placeholder:"Model"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(Q,{pending:j.isPending,pendingLabel:"Saving defaults",onClick:()=>void j.mutateAsync(),children:"Save Forge Agent defaults"}),e.jsxs(L,{className:"bg-white/[0.06] text-white/78",children:["Forge Agent",F.modelSettings.forgeAgent.basicChat.connectionLabel?` basic chat: ${F.modelSettings.forgeAgent.basicChat.connectionLabel}`:" basic chat stays local"]}),e.jsx(L,{className:"bg-white/[0.06] text-white/78",children:F.modelSettings.forgeAgent.wiki.connectionLabel?`Wiki: ${F.modelSettings.forgeAgent.wiki.connectionLabel}`:"Wiki: no external model selected"})]})]}),e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]",children:[e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Qp,{className:"size-4 text-[var(--secondary)]"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-white",children:"Connection editor"}),e.jsx("div",{className:"text-xs leading-5 text-white/52",children:"Every saved connection becomes a first-class agent layered on top of Forge Agent."})]})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Provider"}),e.jsx("div",{className:"grid gap-2 md:grid-cols-3",children:[["openai-api","OpenAI API"],["openai-codex","OpenAI Codex OAuth"],["openai-compatible","OpenAI-compatible"]].map(([_,B])=>e.jsx("button",{type:"button",className:`rounded-[18px] px-4 py-3 text-left text-sm transition ${s.provider===_?"bg-[var(--primary)]/[0.18] text-white":"bg-white/[0.04] text-white/62 hover:bg-white/[0.08]"}`,onClick:()=>{i(Br(_)),m(null),f("")},children:B},_))})]}),e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:s.label,onChange:_=>i(B=>({...B,label:_.target.value})),placeholder:"Connection label"}),e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:s.model,onChange:_=>i(B=>({...B,model:_.target.value})),placeholder:"Model"}),s.provider!=="openai-codex"?e.jsxs(e.Fragment,{children:[e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:s.baseUrl,onChange:_=>i(B=>({...B,baseUrl:_.target.value})),placeholder:"Base URL"}),e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:s.apiKey,onChange:_=>i(B=>({...B,apiKey:_.target.value})),placeholder:s.id?"Leave blank to keep the stored key":"API key",type:"password"})]}):e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"text-sm text-white",children:["OpenAI Codex uses the documented PKCE flow with the local callback at ",F.modelSettings.oauth.openAiCodex.callbackUrl,"."]}),e.jsx("div",{className:"text-xs leading-5 text-white/52",children:"Start OAuth, finish the browser sign-in, then save the resulting connection as a chat agent backed by the ChatGPT Codex runtime."}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(Q,{variant:"secondary",pending:T.isPending,pendingLabel:"Starting OAuth",onClick:()=>void T.mutateAsync(),children:[e.jsx(Tt,{className:"size-4"}),"Start OAuth"]}),g!=null&&g.authUrl?e.jsxs(Q,{variant:"secondary",onClick:()=>window.open(g.authUrl??"","_blank","noopener,noreferrer"),children:["Open sign-in",e.jsx(Wi,{className:"size-4"})]}):null]}),g?e.jsxs("div",{className:"grid gap-2 rounded-[18px] bg-black/20 p-3 text-sm text-white/72",children:[e.jsxs("div",{children:["Status: ",g.status]}),g.accountLabel?e.jsxs("div",{children:["Account: ",g.accountLabel]}):null,g.error?e.jsx("div",{className:"text-rose-200",children:g.error}):null]}):null,e.jsxs("div",{className:"grid gap-2",children:[e.jsx("input",{className:"rounded-[16px] border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-white",value:u,onChange:_=>f(_.target.value),placeholder:"Paste the authorization code or full redirect URL"}),e.jsx(Q,{variant:"secondary",disabled:!u.trim()||!h,pending:k.isPending,pendingLabel:"Submitting",onClick:()=>void k.mutateAsync(),children:"Submit manual code"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(Q,{pending:S.isPending,pendingLabel:"Saving connection",disabled:!C,onClick:()=>void S.mutateAsync(),children:"Save connection"}),e.jsxs(Q,{variant:"secondary",pending:A.isPending,pendingLabel:"Testing",disabled:s.provider==="openai-codex"?!s.id:!s.id&&!s.apiKey.trim(),onClick:()=>void A.mutateAsync(),children:[e.jsx(Hi,{className:"size-4"}),"Test connection"]})]}),b?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3 text-sm text-white/72",children:b}):null]})]}),e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ui,{className:"size-4 text-[var(--secondary)]"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-white",children:"Connected agents"}),e.jsx("div",{className:"text-xs leading-5 text-white/52",children:"Each connection registers its own chat-facing agent identity."})]})]}),e.jsxs("div",{className:"grid gap-3",children:[$.length===0?e.jsx("div",{className:"rounded-[20px] border border-dashed border-white/10 bg-white/[0.02] px-4 py-5 text-sm leading-6 text-white/58",children:"No external model connection yet. Add one with OAuth or API credentials and Forge will expose it as a first-class agent."}):null,$.map(_=>e.jsxs("div",{className:"grid gap-3 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-white",children:_.label}),e.jsxs("div",{className:"mt-1 text-xs text-white/46",children:[_.agentLabel," · ",_.provider," ·"," ",_.model]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Q,{variant:"secondary",onClick:()=>{i(E1(_)),m(null),f("")},children:"Edit"}),e.jsx(Q,{variant:"secondary",pending:p.isPending,pendingLabel:"Deleting",onClick:()=>void p.mutateAsync(_.id),children:e.jsx(ct,{className:"size-4"})})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(L,{className:"bg-white/[0.06] text-white/78",children:_.authMode==="oauth"?"OAuth":"API key"}),e.jsx(L,{className:"bg-white/[0.06] text-white/78",children:_.status}),e.jsx(L,{className:"bg-white/[0.06] text-white/78",children:_.baseUrl}),_.accountLabel?e.jsx(L,{className:"bg-white/[0.06] text-white/78",children:_.accountLabel}):null]})]},_.id))]})]})]})]})}const D1=["error","warning","info","debug"],$1=["server","ui","system","agent","openclaw"],O1=60;function Ma(t){return t.trim().toLowerCase()}function Ri(t){return Array.from(new Set(t.map(s=>(s==null?void 0:s.trim())??"").filter(Boolean)))}function Pi(t,s){const i=Ri(t.getAll(s));if(i.length>0)return i;const a=t.get(s);return a!=null&&a.trim()?[a.trim()]:[]}function F1(t){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}).format(new Date(t))}function uu(t){return t==="error"?"border-rose-400/20 bg-rose-500/[0.08] text-rose-100":t==="warning"?"border-amber-400/20 bg-amber-500/[0.08] text-amber-100":t==="info"?"border-sky-400/20 bg-sky-500/[0.08] text-sky-100":"border-white/10 bg-white/[0.04] text-white/68"}function Kr(t){return t==="error"?"Errors":t==="warning"?"Warnings":t==="info"?"Info":"Debug"}function Ur(t){return t==="openclaw"?"OpenClaw":t.charAt(0).toUpperCase()+t.slice(1)}function _1(t){return[t.scope?`scope: ${t.scope}`:null,t.eventKey?`event: ${t.eventKey}`:null,t.route?`route: ${t.route}`:null,t.functionName?`function: ${t.functionName}`:null,t.jobId?`job: ${t.jobId}`:null,t.entityType&&t.entityId?`entity: ${t.entityType}:${t.entityId}`:null,t.requestId?`request: ${t.requestId}`:null].filter(s=>!!s)}function R1(t){return Ma([t.message,t.scope,t.eventKey,t.route,t.functionName,t.requestId,t.entityType,t.entityId,t.jobId,JSON.stringify(t.details)].filter(Boolean).join(" "))}function ni(t,s){return e.jsx(L,{size:"sm",className:re("bg-white/[0.08] text-white/74",s),children:t})}function zc(t,s){return kx(t)?e.jsx(Te,{kind:t,label:s,compact:!0,gradient:!1}):ni(s,"bg-[rgba(192,193,255,0.12)] text-white/84")}function Mi({label:t,placeholder:s,options:i,selectedIds:a,onChange:n,emptyMessage:r="No matches yet."}){const[l,o]=d.useState(!1),[c,x]=d.useState(""),[v,u]=d.useState(0),f=d.useMemo(()=>a.map(M=>i.find(E=>E.id===M)??null).filter(M=>M!==null),[i,a]),h=Ma(c),m=d.useMemo(()=>{const M=i.filter(E=>!a.includes(E.id));return h?M.filter(E=>Ma(`${E.label} ${E.description??""} ${E.searchText??""}`).includes(h)).slice(0,10):M.slice(0,10)},[h,i,a]),b=M=>{a.includes(M)||(n([...a,M]),x(""),u(0),o(!1))},w=M=>{n(a.filter(E=>E!==M))};return e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-[11px] font-medium uppercase tracking-[0.18em] text-white/45",children:t}),e.jsxs("div",{className:"relative rounded-[20px] border border-white/8 bg-white/[0.04] px-3 py-2.5",children:[f.length>0?e.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:f.map(M=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-white/8 bg-white/[0.05] px-1.5 py-1",children:[M.badge,e.jsx("button",{type:"button",className:"rounded-full p-0.5 text-white/46 transition hover:text-white",onClick:()=>w(M.id),"aria-label":`Remove ${M.label}`,children:e.jsx(mt,{className:"size-3"})})]},M.id))}):null,e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bt,{className:"size-3.5 text-white/34"}),e.jsx("input",{value:c,onChange:M=>{x(M.target.value),u(0),o(!0)},onFocus:()=>o(!0),onBlur:()=>{window.setTimeout(()=>o(!1),120)},onKeyDown:M=>{if(M.key==="Backspace"&&!c&&a.length>0){w(a[a.length-1]);return}if(M.key==="ArrowDown"){M.preventDefault(),o(!0),u(E=>m.length===0?0:Math.min(m.length-1,E+1));return}if(M.key==="ArrowUp"){M.preventDefault(),u(E=>Math.max(0,E-1));return}if(M.key==="Escape"){o(!1);return}M.key==="Enter"&&m[v]&&(M.preventDefault(),b(m[v].id))},placeholder:s,className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]}),l?e.jsx("div",{className:"absolute left-0 right-0 top-full z-20 mt-2 max-h-64 overflow-y-auto rounded-[20px] border border-white/8 bg-[rgba(8,13,24,0.96)] p-2 shadow-[0_26px_60px_rgba(4,8,18,0.32)] backdrop-blur-xl",children:m.length>0?m.map((M,E)=>e.jsx("button",{type:"button",className:re("flex w-full items-start justify-between gap-3 rounded-[16px] px-3 py-2 text-left transition",E===v?"bg-white/[0.1] text-white":"text-white/70 hover:bg-white/[0.06] hover:text-white"),onMouseEnter:()=>u(E),onMouseDown:D=>D.preventDefault(),onClick:()=>b(M.id),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:M.menuBadge??M.badge}),M.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/46",children:M.description}):null]})},M.id)):e.jsx("div",{className:"px-3 py-2 text-sm text-white/42",children:r})}):null]})]})}function z1(t,s){const i=`${s.entityType}:${s.entityId}`;t.has(i)||t.set(i,{id:i,label:s.label,description:s.description,searchText:s.searchText,badge:s.badge,menuBadge:s.menuBadge})}function q1(t){const s=new Map;for(const i of t){if(!i.entityType||!i.entityId)continue;const a=`${i.entityType}:${i.entityId}`;if(s.has(a))continue;const n=i.entityType==="wiki_ingest_job"?`Ingest ${i.entityId}`:`${i.entityType} ${i.entityId}`;z1(s,{entityType:i.entityType,entityId:i.entityId,label:n,description:"Seen in diagnostics logs",searchText:Ma(`${n} ${i.scope} ${i.message} ${i.eventKey}`),badge:zc(i.entityType,n),menuBadge:zc(i.entityType,n)})}return Array.from(s.values()).sort((i,a)=>i.label.localeCompare(a.label))}const B1=d.memo(function({entry:s}){const[i,a]=d.useState(!1),n=d.useMemo(()=>i&&Object.keys(s.details).length>0?JSON.stringify(s.details,null,2):"",[i,s.details]);return e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:re("rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em]",uu(s.level)),children:s.level}),e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-white/60",children:s.source}),e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-white/60",children:s.scope}),s.eventKey?e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-white/46",children:s.eventKey}):null]}),e.jsx("div",{className:"text-base font-medium text-white",children:s.message}),e.jsx("div",{className:"flex flex-wrap gap-3 text-xs text-white/45",children:_1(s).map(r=>e.jsx("span",{children:r},r))})]}),e.jsxs("div",{className:"shrink-0 text-right text-xs text-white/40",children:[e.jsx("div",{children:F1(s.createdAt)}),e.jsx("div",{className:"mt-1 font-mono text-[11px]",children:s.id})]})]}),Object.keys(s.details).length>0?e.jsxs("details",{className:"rounded-[18px] border border-white/8 bg-[rgba(7,11,21,0.72)] px-4 py-3",onToggle:r=>a(r.currentTarget.open),children:[e.jsx("summary",{className:"cursor-pointer text-sm text-white/70",children:"View structured details"}),i?e.jsx("pre",{className:"mt-3 overflow-x-auto whitespace-pre-wrap text-xs leading-6 text-white/58",children:n}):null]}):null]})});function K1(){const[t,s]=Pt(),i=d.useMemo(()=>{var k,$;const p=((k=t.get("entityType"))==null?void 0:k.trim())||"",A=(($=t.get("entityId"))==null?void 0:$.trim())||"",T=Pi(t,"entity");return T.length===0&&p&&A&&T.push(`${p}:${A}`),{search:t.get("search")||"",levels:Pi(t,"level"),sources:Pi(t,"source"),scopes:Pi(t,"scope"),routes:Pi(t,"route"),jobs:Pi(t,"jobId"),entities:Ri(T)}},[t]),a=Wr({queryKey:["forge-diagnostic-logs","settings-filters"],initialPageParam:null,queryFn:({pageParam:p})=>Nb({limit:O1,beforeCreatedAt:p==null?void 0:p.beforeCreatedAt,beforeId:p==null?void 0:p.beforeId}),getNextPageParam:p=>p.nextCursor,retry:!1,refetchOnWindowFocus:!1}),n=(p,A)=>{const T=new URLSearchParams(t);A.trim()?T.set(p,A.trim()):T.delete(p),s(T,{replace:!0})},r=(p,A,T=[])=>{const k=new URLSearchParams(t);k.delete(p);for(const $ of T)k.delete($);for(const $ of Ri(A))k.append(p,$);s(k,{replace:!0})},l=()=>{const p=new URLSearchParams(t);["search","level","source","scope","route","jobId","entity","entityType","entityId"].forEach(A=>p.delete(A)),s(p,{replace:!0})},o=d.useMemo(()=>{var p;return((p=a.data)==null?void 0:p.pages.flatMap(A=>A.logs))??[]},[a.data]),c=Ma(i.search),x=d.useRef(null),v=d.useMemo(()=>D1.map(p=>({id:p,label:Kr(p),searchText:`${p} ${Kr(p)}`,badge:e.jsx(L,{size:"sm",className:uu(p),children:Kr(p)})})),[]),u=d.useMemo(()=>$1.map(p=>({id:p,label:Ur(p),searchText:`${p} ${Ur(p)}`,badge:ni(Ur(p))})),[]),f=d.useMemo(()=>Ri(o.map(p=>p.scope)).map(p=>({id:p,label:p,searchText:p,badge:ni(p)})),[o]),h=d.useMemo(()=>Ri(o.map(p=>p.route)).map(p=>({id:p,label:p,description:"Filter logs to one or more exact routes.",searchText:p,badge:ni(p,"max-w-[16rem]"),menuBadge:ni(p)})),[o]),m=d.useMemo(()=>Ri(o.map(p=>p.jobId)).map(p=>({id:p,label:p,description:"Background job or ingest run id.",searchText:p,badge:ni(p,"max-w-[14rem]"),menuBadge:ni(p)})),[o]),b=d.useMemo(()=>q1(o),[o]),w=d.useMemo(()=>o.filter(p=>{if(c&&!R1(p).includes(c)||i.levels.length>0&&!i.levels.includes(p.level)||i.sources.length>0&&!i.sources.includes(p.source)||i.scopes.length>0&&!i.scopes.includes(p.scope)||i.routes.length>0&&!i.routes.includes(p.route??"")||i.jobs.length>0&&!i.jobs.includes(p.jobId??""))return!1;if(i.entities.length>0){const A=p.entityType&&p.entityId?`${p.entityType}:${p.entityId}`:"";if(!A||!i.entities.includes(A))return!1}return!0}),[i,c,o]),M=[i.search,i.levels.join("|"),i.sources.join("|"),i.scopes.join("|"),i.routes.join("|"),i.jobs.join("|"),i.entities.join("|")].join("::");d.useEffect(()=>{var p;(p=x.current)==null||p.scrollTo({top:0})},[M]);const E=Qi({count:w.length,getScrollElement:()=>x.current,estimateSize:()=>260,overscan:8}),D=E.getVirtualItems(),j=()=>{const p=x.current;if(!p||!a.hasNextPage||a.isFetchingNextPage)return;p.scrollHeight-p.scrollTop-p.clientHeight<=800&&a.fetchNextPage()},S=i.levels.length+i.sources.length+i.scopes.length+i.routes.length+i.jobs.length+i.entities.length+(i.search.trim()?1:0);return a.isPending?e.jsx(It,{eyebrow:"Settings",title:"Loading diagnostics",description:"Collecting the latest frontend, backend, and runtime traces.",columns:1,blocks:6}):a.isError?e.jsx(ze,{eyebrow:"Settings",error:a.error,onRetry:()=>void a.refetch()}):e.jsxs("div",{className:"mx-auto grid w-full max-w-[1220px] gap-5",children:[e.jsx(qe,{title:"Logs",description:"Inspect shared diagnostics from the UI, backend routes, background jobs, and LLM flows.",badge:`${w.length} matching${w.length!==o.length?` · ${o.length} loaded`:""}${a.hasNextPage?" · more available":""}`}),e.jsx(vs,{}),e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Filters"}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:"Use token filters with OR-style badge selections for levels, sources, routes, jobs, scopes, and linked entities. Search still matches the message body and structured details."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[S>0?e.jsxs(Q,{variant:"ghost",size:"sm",onClick:l,children:["Clear ",S]}):null,e.jsx(Q,{variant:"secondary",size:"sm",onClick:()=>void a.refetch(),pending:a.isRefetching&&!a.isFetchingNextPage,pendingLabel:"Refreshing",children:"Refresh"})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-[11px] font-medium uppercase tracking-[0.18em] text-white/45",children:"Search message or details"}),e.jsx(le,{value:i.search,onChange:p=>n("search",p.target.value),placeholder:"LLM compilation failed, wiki_ingest, request_failed…",className:"h-11 rounded-[20px]"})]}),e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsx(Mi,{label:"Levels",placeholder:"Add one or more levels",options:v,selectedIds:i.levels,onChange:p=>r("level",p),emptyMessage:"No additional log levels."}),e.jsx(Mi,{label:"Sources",placeholder:"Add one or more sources",options:u,selectedIds:i.sources,onChange:p=>r("source",p),emptyMessage:"No additional log sources."}),e.jsx(Mi,{label:"Scopes",placeholder:"Search scopes",options:f,selectedIds:i.scopes,onChange:p=>r("scope",p),emptyMessage:"No scopes match the current logs."}),e.jsx(Mi,{label:"Routes",placeholder:"Search exact routes",options:h,selectedIds:i.routes,onChange:p=>r("route",p),emptyMessage:"No routes match the current logs."}),e.jsx(Mi,{label:"Jobs",placeholder:"Search job ids",options:m,selectedIds:i.jobs,onChange:p=>r("jobId",p),emptyMessage:"No job ids match the current logs."}),e.jsx(Mi,{label:"Entities",placeholder:"Search Forge entities or logged ids",options:b,selectedIds:i.entities,onChange:p=>r("entity",p,["entityType","entityId"]),emptyMessage:"No logged entities match yet."})]})]}),e.jsx("div",{className:"grid gap-3",children:w.length===0?e.jsx(ae,{className:"text-sm text-white/58",children:"No diagnostic entries match the current filters yet."}):e.jsx(ae,{className:"p-0",children:e.jsxs("div",{ref:x,onScroll:j,className:"h-[72vh] overflow-y-auto px-3 py-3",children:[e.jsx("div",{className:"relative",style:{height:`${E.getTotalSize()}px`},children:D.map(p=>{const A=w[p.index];return A?e.jsx("div",{"data-index":p.index,ref:E.measureElement,className:"absolute left-0 top-0 w-full pb-3",style:{transform:`translateY(${p.start}px)`},children:e.jsx(B1,{entry:A})},A.id):null})}),e.jsx("div",{className:"border-t border-white/6 px-1 py-3 text-center text-xs text-white/46",children:a.isFetchingNextPage?"Loading older logs…":a.hasNextPage?"Scroll to load older logs.":`Showing all ${o.length} loaded logs.`})]})})})]})}function U1(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 Q1(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 W1({profile:t,achievements:s,milestoneRewards:i,momentumPulse:a,recentLedger:n=[],className:r,tone:l="core"}){const o=s.filter(f=>f.unlocked),c=(o.length>0?o:s).slice(0,3),x=i.slice(0,3),v=n.slice(0,3),u=Math.min(100,Math.round(t.currentLevelXp/t.nextLevelXp*100));return e.jsxs("section",{className:re("min-w-0 overflow-hidden rounded-[30px] border border-white/6 bg-[linear-gradient(180deg,rgba(18,24,40,0.96),rgba(11,16,28,0.94))] shadow-[0_24px_70px_rgba(4,8,18,0.3)]",l==="psyche"&&"bg-[linear-gradient(180deg,rgba(18,27,35,0.96),rgba(12,20,26,0.94))]",r),children:[e.jsx("div",{className:re("bg-gradient-to-r px-5 py-5",Q1(a.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:a.headline}),e.jsx("p",{className:"mt-3 max-w-3xl text-sm leading-7 text-white/68",children:a.detail})]}),e.jsxs("div",{className:"flex min-w-0 flex-wrap gap-2",children:[e.jsxs(L,{wrap:!0,className:"bg-black/20 text-white/84",children:["Level ",t.level]}),e.jsxs(L,{wrap:!0,className:"bg-black/20 text-white/84",children:[t.streakDays," day streak"]}),e.jsxs(L,{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(Kt.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:a.nextMilestoneLabel})]}),e.jsx(L,{wrap:!0,className:"max-w-[12rem] shrink-0 self-start text-[var(--tertiary)]",children:a.celebrationLabel})]}),e.jsx("div",{className:"mt-5",children:e.jsx(us,{value:u})}),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((f,h)=>e.jsxs(Kt.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.24,delay:.04*h,ease:"easeOut"},className:"overflow-hidden rounded-[22px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0 flex-1 font-medium text-white",children:f.title}),e.jsx(L,{wrap:!0,className:re("max-w-[8rem] shrink-0 self-start",U1(f.tier)),children:f.tier})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:f.summary}),e.jsx("div",{className:"mt-4 text-xs uppercase tracking-[0.16em] text-white/40",children:f.progressLabel})]},f.id))})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"overflow-hidden rounded-[24px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Rewards in progress"}),e.jsx("div",{className:"mt-4 grid gap-3",children:x.map(f=>{const h=Math.min(100,Math.round(f.current/f.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:f.title}),e.jsx(L,{wrap:!0,className:re("max-w-[10.5rem] shrink-0 self-start",f.completed?"text-emerald-300":"text-white/68"),children:f.rewardLabel})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:f.summary}),e.jsx("div",{className:"mt-4",children:e.jsx(us,{value:h})}),e.jsx("div",{className:"mt-3 text-xs uppercase tracking-[0.16em] text-white/38",children:f.progressLabel})]},f.id)})})]}),v.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:v.map(f=>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:f.reasonTitle}),e.jsxs(L,{wrap:!0,className:re("max-w-[8rem] shrink-0 self-start",f.deltaXp>=0?"text-emerald-300":"text-amber-300"),children:[f.deltaXp>0?"+":"",f.deltaXp," XP"]})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:f.reasonSummary}),e.jsx("div",{className:"mt-3 text-xs uppercase tracking-[0.16em] text-white/38",children:Ol(f.createdAt)})]},f.id))})]}):null]})]})]})}function H1(t){return JSON.stringify(t,null,2)}function qc(t){const s=t.trim();if(!s)return{};const i=JSON.parse(s);if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Expected a JSON object.");return i}function G1(){var k,$,g;const t=Je(),s=We(),[i,a]=d.useState(""),[n,r]=d.useState(null),[l,o]=d.useState(null),c=fe({queryKey:["forge-operator-session"],queryFn:Zi}),x=c.isSuccess,v=fe({queryKey:["forge-xp-metrics"],queryFn:Kh}),u=fe({queryKey:["forge-reward-rules"],queryFn:xb,enabled:x}),f=fe({queryKey:["forge-reward-ledger"],queryFn:()=>bb(30),enabled:x}),h=fe({queryKey:["forge-psyche-overview"],queryFn:async()=>(await Wn()).overview}),m=vn({defaultValues:{title:"",description:"",active:!0,configJson:"{}"}}),b=vn({defaultValues:{entityType:"task",entityId:"",deltaXp:15,reasonTitle:"Operator bonus",reasonSummary:"Manual boost for a meaningful action captured with good provenance.",metadataJson:"{}"}}),w=async()=>{await Promise.all([s.invalidateQueries({queryKey:["forge-xp-metrics"]}),s.invalidateQueries({queryKey:["forge-reward-rules"]}),s.invalidateQueries({queryKey:["forge-reward-ledger"]})])},M=xe({mutationFn:C=>gb(C.ruleId,{title:C.title,description:C.description,active:C.active,config:C.config}),onSuccess:w}),E=xe({mutationFn:fb,onSuccess:w}),D=((k=u.data)==null?void 0:k.rules)??[],j=d.useMemo(()=>{var C,F,z,J,O,_;return{system:[{id:"operator_manual_reward",label:"Operator reward ledger"}],goal:t.snapshot.goals.map(B=>({id:B.id,label:B.title})),project:t.snapshot.dashboard.projects.map(B=>({id:B.id,label:B.title})),task:t.snapshot.tasks.map(B=>({id:B.id,label:B.title})),habit:t.snapshot.habits.map(B=>({id:B.id,label:B.title})),tag:t.snapshot.tags.map(B=>({id:B.id,label:B.name})),note:[],insight:[],psyche_value:(((C=h.data)==null?void 0:C.values)??[]).map(B=>({id:B.id,label:B.title})),behavior_pattern:(((F=h.data)==null?void 0:F.patterns)??[]).map(B=>({id:B.id,label:B.title})),behavior:(((z=h.data)==null?void 0:z.behaviors)??[]).map(B=>({id:B.id,label:B.title})),belief_entry:(((J=h.data)==null?void 0:J.beliefs)??[]).map(B=>({id:B.id,label:B.statement})),mode_profile:(((O=h.data)==null?void 0:O.modes)??[]).map(B=>({id:B.id,label:B.title})),trigger_report:(((_=h.data)==null?void 0:_.reports)??[]).map(B=>({id:B.id,label:B.title}))}},[h.data,t.snapshot.dashboard.projects,t.snapshot.goals,t.snapshot.habits,t.snapshot.tags,t.snapshot.tasks]);d.useEffect(()=>{var J;const C=b.getValues("entityType"),F=b.getValues("entityId"),z=j[C]??[];F&&z.some(O=>O.id===F)||b.setValue("entityId",((J=z[0])==null?void 0:J.id)??"")},[b,j]),d.useEffect(()=>{D.length&&(!i||!D.some(C=>C.id===i))&&a(D[0].id)},[D,i]);const S=D.find(C=>C.id===i)??D[0]??null;d.useEffect(()=>{S&&(m.reset({title:S.title,description:S.description,active:S.active,configJson:H1(S.config)}),r(null))},[S,m]);const p=($=v.data)==null?void 0:$.metrics,T=(((g=f.data)==null?void 0:g.ledger)??[]).filter(C=>C.metadata.manual===!0).slice(0,8);return c.isLoading?e.jsx(It,{eyebrow:"Settings · Rewards",title:"Loading reward controls",description:"Establishing the operator session and fetching reward configuration.",columns:2,blocks:6}):c.isError?e.jsx(ze,{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(qe,{title:"Rewards",description:"XP command deck, reward rule editor, manual bonus grants, and ledger history."}),e.jsx(vs,{}),e.jsx("div",{className:"grid gap-5",children:e.jsxs(ae,{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:[p?e.jsx(W1,{profile:p.profile,achievements:p.achievements,milestoneRewards:p.milestoneRewards,momentumPulse:p.momentumPulse,recentLedger:p.recentLedger}):null,p?e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(Ks,{label:"Total XP",value:p.profile.totalXp,tone:"core"}),e.jsx(Ks,{label:"Daily ambient",value:`${p.dailyAmbientXp} / ${p.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"}),D.length>0?e.jsxs("form",{className:"mt-4 grid gap-4",onSubmit:m.handleSubmit(async C=>{try{r(null);const F=qc(C.configJson);if(!S)return;await M.mutateAsync({ruleId:S.id,title:C.title,description:C.description,active:C.active,config:F})}catch(F){r(F instanceof Error?F.message:"Invalid reward rule config.")}}),children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Rule"}),e.jsx("select",{className:"rounded-[14px] bg-white/[0.06] px-3 py-3 text-white",value:i,onChange:C=>a(C.target.value),children:D.map(C=>e.jsx("option",{value:C.id,children:C.title},C.id))})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Title"}),e.jsx(le,{...m.register("title")})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Description"}),e.jsx(Me,{className:"min-h-24",...m.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",...m.register("active")})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Config JSON"}),e.jsx(Me,{className:"min-h-28 font-mono text-xs",...m.register("configJson")})]}),n?e.jsx("div",{className:"text-sm text-amber-300",children:n}):null,e.jsx(Q,{type:"submit",pending:M.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:b.handleSubmit(async C=>{try{o(null);const F=qc(C.metadataJson);await E.mutateAsync({entityType:C.entityType,entityId:C.entityId,deltaXp:C.deltaXp,reasonTitle:C.reasonTitle,reasonSummary:C.reasonSummary,metadata:F}),b.reset({...C,entityId:"",reasonTitle:"Operator bonus",reasonSummary:"Manual boost for a meaningful action captured with good provenance.",metadataJson:"{}"})}catch(F){o(F instanceof Error?F.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",...b.register("entityType"),children:Object.keys(j).map(C=>e.jsx("option",{value:C,children:C.replaceAll("_"," ")},C))})]}),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",...b.register("entityId"),children:(j[b.watch("entityType")]??[]).map(C=>e.jsx("option",{value:C.id,children:C.label},C.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(le,{type:"number",...b.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(le,{...b.register("reasonTitle")})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Reason summary"}),e.jsx(Me,{className:"min-h-24",...b.register("reasonSummary")})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Metadata JSON"}),e.jsx(Me,{className:"min-h-24 font-mono text-xs",...b.register("metadataJson")})]}),l?e.jsx("div",{className:"text-sm text-amber-300",children:l}):null,e.jsx(Q,{type:"submit",pending:E.isPending,pendingLabel:"Issuing bonus",children:"Issue bonus XP"})]}),E.data?e.jsxs("div",{className:"mt-4 rounded-[18px] bg-[rgba(192,193,255,0.12)] p-4 text-sm text-white",children:["Granted ",E.data.reward.deltaXp>0?"+":"",E.data.reward.deltaXp," XP for ",e.jsx("strong",{children:E.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:T.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."}):T.map(C=>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:C.reasonTitle}),e.jsxs(L,{className:C.deltaXp>=0?"text-emerald-300":"text-amber-300",children:[C.deltaXp>0?"+":"",C.deltaXp," XP"]})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:C.reasonSummary||"No summary supplied."}),e.jsxs("div",{className:"mt-2 text-xs uppercase tracking-[0.16em] text-white/38",children:[C.entityType," · ",C.entityId," · ",new Date(C.createdAt).toLocaleString()]})]},C.id))})]})]})]})})]})}const pu=[{id:"visibility",label:"Discovery and visibility",description:"What the source user can discover, inspect, and pull into read flows on the target side.",rights:[{key:"discoverable",label:"Discoverable",description:"The target appears as a reachable collaborator in the source user's graph and pickers."},{key:"canListUsers",label:"List users",description:"The source user can include the target in directory, comparison, and routing surfaces."},{key:"canReadProfile",label:"Read profile",description:"The source user can inspect the target's identity card, handle, type, and description."},{key:"canReadEntities",label:"Read entities",description:"The source user can read the target's goals, projects, tasks, notes, strategies, and related records."},{key:"canSearchEntities",label:"Search entities",description:"The source user can find the target's work through Forge search and entity pickers."}]},{id:"coordination",label:"Messaging, context, and handoff",description:"What the source user can message, connect, and coordinate on the target side before changing execution.",rights:[{key:"canLinkEntities",label:"Share context",description:"The source user can attach the target's records into shared notes, strategies, calendar context, and cross-owner plans."},{key:"canCoordinate",label:"Message and coordinate",description:"The source user can communicate with the target through Forge, hand off work, and coordinate execution."},{key:"canViewMetrics",label:"View metrics",description:"The source user can inspect the target's XP, alignment, and progress metrics."},{key:"canViewActivity",label:"View activity",description:"The source user can inspect the target's activity stream, evidence, and execution trail."}]},{id:"execution",label:"Plan and execution control",description:"What the source user can actually change on the target side once collaboration is trusted.",rights:[{key:"canManageStrategies",label:"Manage strategies",description:"The source user can draft and update strategies that belong to the target."},{key:"canCreateOnBehalf",label:"Create on behalf",description:"The source user can intentionally create new target-owned entities."},{key:"canAffectEntities",label:"Affect entities",description:"The source user can mutate work that belongs to the target."}]}],X1=[{id:"full_collab",label:"Full collaboration",description:"Use when two humans or agents can see, coordinate, plan, and change each other's work.",rights:{discoverable:!0,canListUsers:!0,canReadProfile:!0,canReadEntities:!0,canSearchEntities:!0,canLinkEntities:!0,canCoordinate:!0,canAffectEntities:!0,canManageStrategies:!0,canCreateOnBehalf:!0,canViewMetrics:!0,canViewActivity:!0}},{id:"coordination_only",label:"Coordinate only",description:"Use when the source user may see and coordinate with the target but should not directly mutate target-owned work.",rights:{discoverable:!0,canListUsers:!0,canReadProfile:!0,canReadEntities:!0,canSearchEntities:!0,canLinkEntities:!0,canCoordinate:!0,canAffectEntities:!1,canManageStrategies:!0,canCreateOnBehalf:!1,canViewMetrics:!0,canViewActivity:!0}},{id:"observe_only",label:"Observe only",description:"Use when the source user should keep visibility into the target without planning or execution control.",rights:{discoverable:!0,canListUsers:!0,canReadProfile:!0,canReadEntities:!0,canSearchEntities:!0,canLinkEntities:!1,canCoordinate:!1,canAffectEntities:!1,canManageStrategies:!1,canCreateOnBehalf:!1,canViewMetrics:!0,canViewActivity:!0}},{id:"hidden",label:"Hidden edge",description:"Use when this direction should stop discovering, reading, or acting on the target.",rights:{discoverable:!1,canListUsers:!1,canReadProfile:!1,canReadEntities:!1,canSearchEntities:!1,canLinkEntities:!1,canCoordinate:!1,canAffectEntities:!1,canManageStrategies:!1,canCreateOnBehalf:!1,canViewMetrics:!1,canViewActivity:!1}}],Bi=pu.reduce((t,s)=>t+s.rights.length,0);function rr(t){return Object.values(t.config.rights).filter(Boolean).length}function xu(t){const s=[];return t.config.rights.canReadEntities&&s.push("See"),t.config.rights.canCoordinate&&s.push("Message"),t.config.rights.canManageStrategies&&s.push("Plan"),t.config.rights.canAffectEntities&&s.push("Affect"),s.join(" · ")||"Hidden"}function V1(t){return!t.config.rights.discoverable&&!t.config.rights.canReadEntities?"Hidden":t.config.rights.canAffectEntities&&t.config.rights.canManageStrategies?"Trusted":t.config.rights.canCoordinate||t.config.rights.canLinkEntities?"Coordinated":"Observed"}function gu(t){return[{id:"see",label:"See",enabled:t.config.rights.discoverable&&t.config.rights.canReadEntities&&t.config.rights.canSearchEntities},{id:"message",label:"Message",enabled:t.config.rights.canCoordinate},{id:"share",label:"Share context",enabled:t.config.rights.canLinkEntities},{id:"plan",label:"Plan",enabled:t.config.rights.canManageStrategies},{id:"affect",label:"Affect",enabled:t.config.rights.canAffectEntities||t.config.rights.canCreateOnBehalf}]}function J1(t,s){return Object.entries(s.rights).every(([i,a])=>t.config.rights[i]===a)}function Y1(t,s){const i=t.filter(l=>l.kind==="human"),a=t.filter(l=>l.kind==="bot"),n=[{entries:i,x:120},{entries:a,x:1040}],r=new Set(s.selectedGrant?[s.selectedGrant.subjectUserId,s.selectedGrant.targetUserId]:s.selectedUserId?[s.selectedUserId]:[]);return n.flatMap(l=>l.entries.map((o,c)=>{const x=r.has(o.id),v=o.id===s.selectedUserId;return{id:o.id,position:{x:l.x,y:64+c*168},draggable:!1,selectable:!1,data:{label:e.jsxs("div",{className:`min-w-[206px] rounded-[22px] border px-4 py-4 shadow-[0_24px_60px_rgba(0,0,0,0.28)] transition ${v?"border-[rgba(244,185,122,0.45)] bg-[rgba(27,16,10,0.92)]":x?"border-white/18 bg-[rgba(14,20,34,0.94)]":"border-white/10 bg-[rgba(9,15,28,0.92)]"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(Ue,{user:o}),e.jsx(L,{className:"bg-white/[0.08] text-white/65",children:o.kind})]}),e.jsxs("div",{className:"mt-3 text-xs text-white/52",children:["@",o.handle]}),e.jsx("div",{className:"mt-2 line-clamp-2 text-xs leading-5 text-white/46",children:o.description||"No user description yet."})]})},style:{background:"transparent",border:"none",padding:0}}}))}function Z1(t,s,i){return t.filter(a=>a.subjectUserId!==a.targetUserId).map(a=>{const n=s===a.id,r=i!==null&&(a.subjectUserId===i||a.targetUserId===i),l=rr(a),o=n?"#f4b97a":!a.config.rights.discoverable&&!a.config.rights.canReadEntities?"rgba(248,113,113,0.55)":r?"rgba(192,193,255,0.78)":"rgba(255,255,255,0.32)";return{id:a.id,source:a.subjectUserId,target:a.targetUserId,label:`${xu(a)} · ${l}/${Bi}`,markerEnd:{type:wh.ArrowClosed,color:o},labelStyle:{fill:n?"#f4b97a":"rgba(255,255,255,0.68)",fontSize:11,fontWeight:600},style:{stroke:o,strokeWidth:n?2.5:r?1.8:1.25},animated:n}})}function eN({users:t,grants:s,selectedGrantId:i=null,selectedUserId:a=null,onOpenGrant:n,onOpenUser:r}){const l=s.find(h=>h.id===i)??null,o=d.useMemo(()=>Y1(t,{selectedUserId:a,selectedGrant:l}),[l,a,t]),c=d.useMemo(()=>Z1(s,i,a),[s,i,a]),x=d.useMemo(()=>s.filter(h=>h.subjectUserId!==h.targetUserId),[s]),v=x.filter(h=>rr(h)===Bi).length,u=x.filter(h=>h.config.rights.canCoordinate).length,f=x.filter(h=>h.config.rights.canAffectEntities||h.config.rights.canCreateOnBehalf).length;return e.jsxs(ae,{className:"overflow-hidden p-0",children:[e.jsxs("div",{className:"grid gap-4 border-b border-white/8 px-5 py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"max-w-3xl",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Directed relationship graph"}),e.jsx(it,{content:"Keep Forge, OpenClaw, Hermes, and the browser on the same runtime and storage root when these arrows should describe one shared human and bot system.",label:"Explain the shared runtime rule"})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Click a user card to open that user's settings. Click any arrow to open the exact directional relationship flow for that lane."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(L,{className:"bg-white/[0.08] text-white/70",children:[x.length," edges"]}),e.jsxs(L,{className:"bg-emerald-500/12 text-emerald-200",children:[v," fully open"]})]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Full collaboration"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:v}),e.jsx("div",{className:"text-xs leading-5 text-white/48",children:"Directions still running with the default fully open posture."})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Coordination lanes"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:u}),e.jsx("div",{className:"text-xs leading-5 text-white/48",children:"Directions allowed to coordinate directly through Forge."})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Execution control"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:f}),e.jsx("div",{className:"text-xs leading-5 text-white/48",children:"Directions allowed to create or mutate target-owned work."})]})]})]}),e.jsx("div",{className:"h-[min(72vh,54rem)] min-h-[34rem] bg-[radial-gradient(circle_at_top,rgba(244,185,122,0.08),transparent_34%),linear-gradient(180deg,rgba(6,10,20,0.97),rgba(8,14,26,0.94))]",children:e.jsxs(kl,{nodes:o,edges:c,fitView:!0,fitViewOptions:{padding:.12,maxZoom:1},nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,onNodeClick:(h,m)=>{r(m.id)},onEdgeClick:(h,m)=>{n(m.id)},attributionPosition:"bottom-left",children:[e.jsx(Cl,{showInteractive:!1}),e.jsx(Sl,{gap:28,size:1,color:"rgba(255,255,255,0.06)"})]})})]})}const tN={kind:"human",handle:"",displayName:"",description:"",accentColor:"#c0c1ff"};function Bc(t){return t?{kind:t.kind,handle:t.handle,displayName:t.displayName,description:t.description,accentColor:t.accentColor}:tN}function sN({open:t,onOpenChange:s,user:i,grants:a,ownership:n,xp:r,pending:l=!1,onSubmit:o,onOpenRelationship:c}){const[x,v]=d.useState(()=>Bc(i)),[u,f]=d.useState(null);d.useEffect(()=>{t&&(v(Bc(i)),f(null))},[t,i]);const h=d.useMemo(()=>a.filter(M=>M.subjectUserId!==M.targetUserId),[a]),m=d.useMemo(()=>i?h.filter(M=>M.subjectUserId===i.id):[],[h,i]),b=d.useMemo(()=>i?h.filter(M=>M.targetUserId===i.id):[],[h,i]),w=[{id:"identity",eyebrow:i?"Edit user":"Create user",title:i?"Update the user identity":"Add a human or bot user",description:"Set the owner type and the public identity Forge will use across ownership, routing, and collaboration surfaces.",render:(M,E)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Kind",description:"Humans represent real people. Bots represent agents or automations with their own ownership lane.",children:e.jsx(Ze,{columns:2,value:M.kind,onChange:D=>E({kind:D}),options:[{value:"human",label:"Human",description:"Use for a real person in the Forge runtime."},{value:"bot",label:"Bot",description:"Use for an agent, assistant, or automation actor."}]})}),e.jsx(se,{label:"Handle",description:"This becomes the stable short id shown as @handle.",hint:"Use lowercase and a durable label, for example forge-operator or planner-bot.",children:e.jsx(le,{value:M.handle,onChange:D=>E({handle:D.target.value}),placeholder:"forge-operator"})}),e.jsx(se,{label:"Display name",description:"This is the human-readable label used across the UI.",children:e.jsx(le,{value:M.displayName,onChange:D=>E({displayName:D.target.value}),placeholder:"Forge Operator"})})]})},{id:"profile",eyebrow:"Profile",title:"Describe the user lane",description:"Capture what this user represents in the shared Forge runtime and pick the accent color that helps the lane stay recognizable.",render:(M,E)=>e.jsxs(e.Fragment,{children:[e.jsx(se,{label:"Description",description:"Explain what this user is responsible for and what side of the system it represents.",children:e.jsx(Me,{value:M.description,onChange:D=>E({description:D.target.value}),className:"min-h-36",placeholder:"Primary human operator for strategy, execution, and review."})}),e.jsx(se,{label:"Accent color",description:"Forge uses this accent to help the user stand out in ownership and collaboration surfaces.",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(le,{value:M.accentColor,onChange:D=>E({accentColor:D.target.value}),placeholder:"#c0c1ff"}),e.jsx("div",{className:"size-10 shrink-0 rounded-full border border-white/10",style:{backgroundColor:M.accentColor||"#c0c1ff"}})]})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Owned records"}),e.jsx("div",{className:"mt-2 text-white",children:(n==null?void 0:n.totalOwnedEntities)??0})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Total XP"}),e.jsx("div",{className:"mt-2 text-white",children:(r==null?void 0:r.totalXp)??0})]}),e.jsxs("div",{className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Weekly XP"}),e.jsx("div",{className:"mt-2 text-white",children:(r==null?void 0:r.weeklyXp)??0})]})]})]})},{id:"relationships",eyebrow:"Relationships",title:"Open directional relationship settings",description:"Each arrow is a separate contract. Open the exact lane you want to adjust and Forge will take you into the relationship flow.",render:()=>i?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx(Ue,{user:i}),e.jsxs("div",{className:"mt-3 text-sm leading-6 text-white/56",children:["@",i.handle," · ",i.description||"No description yet."]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Outbound lanes"}),m.length>0?m.map(M=>e.jsxs("button",{type:"button",className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-4 text-left transition hover:bg-white/[0.05]",onClick:()=>c(M.id),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Ue,{user:M.subjectUser}),e.jsx("span",{className:"text-white/45",children:"→"}),e.jsx(Ue,{user:M.targetUser})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(L,{className:"bg-white/[0.08] text-white/74",children:xu(M)}),e.jsxs(L,{className:"bg-white/[0.08] text-white/74",children:[rr(M),"/",Bi," rights"]})]})]},M.id)):e.jsx("div",{className:"rounded-[20px] border border-dashed border-white/10 bg-white/[0.02] px-4 py-4 text-sm text-white/52",children:"No outbound relationship lanes yet."})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Inbound lanes"}),b.length>0?b.map(M=>e.jsxs("button",{type:"button",className:"rounded-[20px] border border-white/8 bg-white/[0.03] px-4 py-4 text-left transition hover:bg-white/[0.05]",onClick:()=>c(M.id),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Ue,{user:M.subjectUser}),e.jsx("span",{className:"text-white/45",children:"→"}),e.jsx(Ue,{user:M.targetUser})]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:gu(M).map(E=>e.jsx(L,{className:E.enabled?"bg-white/[0.08] text-white/74":"bg-white/[0.04] text-white/38",children:E.label},`${M.id}-${E.id}`))})]},M.id)):e.jsx("div",{className:"rounded-[20px] border border-dashed border-white/10 bg-white/[0.02] px-4 py-4 text-sm text-white/52",children:"No inbound relationship lanes yet."})]})]})]}):e.jsx("div",{className:"rounded-[20px] border border-dashed border-white/10 bg-white/[0.02] px-4 py-4 text-sm leading-6 text-white/52",children:"Create the user first, then Forge will generate the directional relationship lanes you can tune from here."})}];return e.jsx(rt,{open:t,onOpenChange:s,eyebrow:i?"User settings":"Create user",title:i?"User settings":"Create user",description:"Edit the user identity, clarify what this lane represents, and jump into relationship settings without crowding the page.",value:x,onChange:v,steps:w,submitLabel:i?"Save user":"Create user",pending:l,pendingLabel:i?"Saving user":"Creating user",error:u,contentClassName:"lg:w-[min(58rem,calc(100vw-1.5rem))]",onSubmit:async()=>{const M=x.handle.trim(),E=x.displayName.trim();if(M.length===0){f("Add a handle before saving this user.");return}if(E.length===0){f("Add a display name before saving this user.");return}await o({userId:i==null?void 0:i.id,input:{kind:x.kind,handle:M,displayName:E,description:x.description.trim(),accentColor:x.accentColor.trim()||"#c0c1ff"}}),s(!1)}})}function Kc(t,s){return{accessLevel:(t==null?void 0:t.accessLevel)??"manage",applyScope:"this_arrow",rights:{discoverable:(t==null?void 0:t.config.rights.discoverable)??!0,canListUsers:(t==null?void 0:t.config.rights.canListUsers)??!0,canReadProfile:(t==null?void 0:t.config.rights.canReadProfile)??!0,canReadEntities:(t==null?void 0:t.config.rights.canReadEntities)??!0,canSearchEntities:(t==null?void 0:t.config.rights.canSearchEntities)??!0,canLinkEntities:(t==null?void 0:t.config.rights.canLinkEntities)??!0,canCoordinate:(t==null?void 0:t.config.rights.canCoordinate)??!0,canAffectEntities:(t==null?void 0:t.config.rights.canAffectEntities)??!0,canManageStrategies:(t==null?void 0:t.config.rights.canManageStrategies)??!0,canCreateOnBehalf:(t==null?void 0:t.config.rights.canCreateOnBehalf)??!0,canViewMetrics:(t==null?void 0:t.config.rights.canViewMetrics)??!0,canViewActivity:(t==null?void 0:t.config.rights.canViewActivity)??!0}}}function iN({open:t,onOpenChange:s,grant:i,grants:a,pending:n=!1,onSubmit:r}){const l=d.useMemo(()=>i?a.find(f=>f.subjectUserId===i.targetUserId&&f.targetUserId===i.subjectUserId)??null:null,[i,a]),[o,c]=d.useState(()=>Kc(i,!!l));d.useEffect(()=>{t&&c(Kc(i,!!l))},[i,t,l]);const x=d.useMemo(()=>Object.values(o.rights).filter(Boolean).length,[o.rights]),v=Math.round(x/Bi*100),u=[{id:"posture",eyebrow:"Relationship posture",title:"Set the trust mode for this arrow",description:"Each arrow is directional. Decide whether you want to tune only this lane or mirror the same contract onto both directions.",render:(f,h)=>e.jsxs(e.Fragment,{children:[i?e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Ue,{user:i.subjectUser}),e.jsx("span",{className:"text-white/45",children:"→"}),e.jsx(Ue,{user:i.targetUser})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(L,{className:"bg-white/[0.08] text-white/74",children:V1(i)}),e.jsxs(L,{className:"bg-white/[0.08] text-white/74",children:[rr(i),"/",Bi," rights"]})]})]}):null,e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Access level"}),e.jsx(Ze,{columns:2,value:f.accessLevel,onChange:m=>h({accessLevel:m}),options:[{value:"view",label:"View",description:"Use when this lane should stay mostly observational."},{value:"manage",label:"Manage",description:"Use when the source side can actively collaborate or act."}]})]}),l?e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Apply scope"}),e.jsx(Ze,{columns:2,value:f.applyScope,onChange:m=>h({applyScope:m}),options:[{value:"this_arrow",label:"This arrow",description:"Only change the exact direction you opened."},{value:"both_arrows",label:"Both arrows",description:"Mirror the same contract onto the reverse direction too."}]})]}):null]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Quick preset"}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:X1.map(m=>e.jsxs("button",{type:"button",className:`rounded-[22px] border p-4 text-left transition ${i&&J1(i,m)?"border-[rgba(244,185,122,0.35)] bg-[rgba(244,185,122,0.08)]":"border-white/8 bg-white/[0.03] hover:bg-white/[0.05]"}`,onClick:()=>h({rights:{...f.rights,...m.rights}}),children:[e.jsx("div",{className:"text-sm font-medium text-white",children:m.label}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:m.description})]},m.id))})]})]})},{id:"rights",eyebrow:"Rights",title:"Tune the individual permissions",description:"Use the preset as the starting point, then sharpen the exact boundaries only where this relationship needs them.",render:(f,h)=>e.jsx(e.Fragment,{children:pu.map(m=>e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-white",children:m.label}),e.jsx("div",{className:"mt-1 text-sm leading-6 text-white/54",children:m.description})]}),e.jsx("div",{className:"grid gap-2",children:m.rights.map(b=>e.jsxs("label",{className:"flex items-start justify-between gap-3 rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-white",children:b.label}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/50",children:b.description})]}),e.jsx("input",{type:"checkbox",checked:f.rights[b.key],onChange:w=>h({rights:{...f.rights,[b.key]:w.target.checked}})})]},b.key))})]},m.id))})},{id:"review",eyebrow:"Review",title:"Review the final relationship contract",description:"Check the enabled capabilities, confirm whether both directions should match, and then save the relationship.",render:f=>{var h,m;return e.jsx(e.Fragment,{children:e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Capability coverage"}),e.jsx("div",{className:"mt-4",children:e.jsx(us,{value:v})}),e.jsxs("div",{className:"mt-3 text-sm text-white/62",children:[x,"/",Bi," rights enabled"]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:gu({...i??{id:"draft",subjectUserId:"",targetUserId:"",accessLevel:f.accessLevel,config:{self:!1,mutable:!0,linkedEntities:!0,rights:f.rights},createdAt:"",updatedAt:"",subjectUser:null,targetUser:null},accessLevel:f.accessLevel,config:{...(i==null?void 0:i.config)??{self:!1,mutable:!0,linkedEntities:!0},rights:f.rights}}).map(b=>e.jsx(L,{className:b.enabled?"bg-white/[0.08] text-white/74":"bg-white/[0.04] text-white/38",children:b.label},b.id))})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-sm font-medium text-white",children:"Save scope"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:f.applyScope==="both_arrows"&&l?"Forge will apply the same access level and rights to both directions of this pair.":"Forge will only update the exact arrow you opened."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(L,{className:"bg-white/[0.08] text-white/74",children:["access ",f.accessLevel]}),e.jsxs(L,{className:"bg-white/[0.08] text-white/74",children:["scope"," ",f.applyScope==="both_arrows"&&l?"both arrows":"this arrow"]})]}),l?e.jsxs("div",{className:"mt-4 rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-3 text-sm text-white/54",children:["Reverse arrow available:"," ",((h=l.subjectUser)==null?void 0:h.displayName)??l.subjectUserId," ","→"," ",((m=l.targetUser)==null?void 0:m.displayName)??l.targetUserId]}):null]})]})})}}];return e.jsx(rt,{open:t,onOpenChange:s,eyebrow:"Relationship settings",title:"Relationship settings",description:"Edit the exact directional contract between two users without keeping the full rights editor pinned on the page.",value:o,onChange:c,steps:u,submitLabel:"Save relationship",pending:n,pendingLabel:"Saving relationship",contentClassName:"lg:w-[min(62rem,calc(100vw-1.5rem))]",onSubmit:async()=>{i&&(await r({grantId:i.id,patch:{accessLevel:o.accessLevel,rights:o.rights},reverseGrantId:(l==null?void 0:l.id)??null,applyToReverse:o.applyScope==="both_arrows"&&l!==null}),s(!1))}})}function aN(){var k;const t=Je(),[s,i]=d.useState(null),[a,n]=d.useState(null),[r,l]=d.useState(!1),[o,c]=d.useState(!1),[x,v]=d.useState(""),u=fe({queryKey:["forge-user-directory"],queryFn:ab}),f=async()=>{await Promise.all([t.refresh(),u.refetch()])},h=xe({mutationFn:async({input:$,userId:g})=>g?(await lb(g,$)).user:(await rb($)).user,onSuccess:async()=>{i(null),l(!1),await f()}}),m=xe({mutationFn:async({grantId:$,patch:g})=>(await nb($,g)).grant,onSuccess:f}),b=(k=u.data)==null?void 0:k.directory,w=(b==null?void 0:b.grants.find($=>$.id===a))??null,M=d.useMemo(()=>new Map(((b==null?void 0:b.ownership)??[]).map($=>[$.userId,$])),[b==null?void 0:b.ownership]),E=d.useMemo(()=>new Map(((b==null?void 0:b.xp)??[]).map($=>[$.userId,$])),[b==null?void 0:b.xp]),D=d.useMemo(()=>{const $=new Map;for(const g of(b==null?void 0:b.grants)??[]){if(!g.targetUser||g.subjectUserId===g.targetUserId)continue;const C=$.get(g.subjectUserId)??[];C.push(g.targetUser),$.set(g.subjectUserId,C)}return $},[b==null?void 0:b.grants]),j=d.useMemo(()=>{const $=((b==null?void 0:b.grants)??[]).filter(g=>g.subjectUserId!==g.targetUserId);return{totalEdges:$.length,fullyOpenEdges:$.filter(g=>Object.values(g.config.rights).every(Boolean)).length,coordinationEdges:$.filter(g=>g.config.rights.canCoordinate).length,executionEdges:$.filter(g=>g.config.rights.canAffectEntities||g.config.rights.canCreateOnBehalf).length}},[b==null?void 0:b.grants]),S=x.trim().toLowerCase(),p=d.useMemo(()=>{const g=((b==null?void 0:b.users)??t.snapshot.users).filter(C=>S?[C.displayName,C.handle,C.kind,C.description].join(" ").toLowerCase().includes(S):!0);return{humans:g.filter(C=>C.kind==="human"),bots:g.filter(C=>C.kind==="bot")}},[b==null?void 0:b.users,S,t.snapshot.users]),A=(w==null?void 0:w.subjectUserId)??(s==null?void 0:s.id)??null,T=(w==null?void 0:w.id)??null;return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1440px] gap-5",children:[e.jsx(qe,{title:"Users",description:"Forge users can be human or bot. Ownership, search, and routing are prepared so work can move across both sides of the system.",badge:`${t.snapshot.users.length} users`}),e.jsx(vs,{}),e.jsx(sN,{open:r,onOpenChange:l,user:s,grants:(b==null?void 0:b.grants)??[],ownership:s?M.get(s.id)??null:null,xp:s?E.get(s.id)??null:null,pending:h.isPending,onSubmit:async $=>{await h.mutateAsync($)},onOpenRelationship:$=>{l(!1),n($),c(!0)}}),e.jsx(iN,{open:o,onOpenChange:c,grant:w,grants:(b==null?void 0:b.grants)??[],pending:m.isPending,onSubmit:async $=>{await m.mutateAsync({grantId:$.grantId,patch:$.patch}),$.applyToReverse&&$.reverseGrantId&&await m.mutateAsync({grantId:$.reverseGrantId,patch:$.patch})}}),e.jsxs(ae,{className:"grid gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Multi-user posture"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:(b==null?void 0:b.posture.summary)??"Forge is preparing modular user access while keeping the current posture permissive."})]}),e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:(b==null?void 0:b.posture.accessModel)??"permissive"})]}),e.jsx("div",{className:"flex items-center gap-3 rounded-[18px] bg-white/[0.04] px-4 py-3",children:e.jsx(le,{value:x,onChange:$=>v($.target.value),placeholder:"Search human, bot, @handle, or description"})})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Multi-agent onboarding"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:"Forge now treats the users graph as the collaboration control plane. Create each human or bot here, keep the runtime shared, then narrow only the specific arrows that should stop seeing, coordinating, planning, or affecting another user."})]}),e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:"default open"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Directional edges"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:j.totalEdges})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Fully open"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:j.fullyOpenEdges})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Coordination"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:j.coordinationEdges})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Execution control"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:j.executionEdges})]})]}),e.jsxs("div",{className:"grid gap-2 text-sm leading-6 text-white/56",children:[e.jsx("div",{children:"1. Create the human and bot users that should exist in the shared Forge system."}),e.jsx("div",{children:"2. Point OpenClaw, Hermes, and the browser at the same Forge runtime and storage root."}),e.jsx("div",{children:"3. Use the graph below to decide what each direction can see, message, plan, or change."}),e.jsx("div",{children:"4. Keep strategy drafting open while the plan is negotiated, then lock the strategy once it becomes the contract."})]})]}),e.jsx(eN,{users:(b==null?void 0:b.users)??t.snapshot.users,grants:(b==null?void 0:b.grants)??[],selectedGrantId:T,selectedUserId:A,onOpenUser:$=>{const g=((b==null?void 0:b.users)??t.snapshot.users).find(C=>C.id===$)??null;n(null),i(g),l(!0)},onOpenGrant:$=>{i(null),n($),c(!0)}}),e.jsxs(ae,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Agent onboarding"}),e.jsx("div",{className:"text-sm leading-6 text-white/60",children:"OpenClaw, Hermes, and the Forge UI all read this same multi-user graph. Keep the defaults open while you are still wiring collaboration, then narrow specific arrows when one user or agent should stop seeing, messaging, planning, or changing another user's work."}),e.jsx("div",{className:"text-sm leading-6 text-white/52",children:"Forge now treats every owner as either human or bot, keeps search cross-user by default, and allows cross-owner links plus explicit coordination lanes between projects, tasks, notes, and strategies."}),e.jsx("div",{children:e.jsx(Ae,{to:"/settings/agents",className:"inline-flex min-h-10 items-center justify-center rounded-[var(--radius-control)] bg-white/8 px-3 py-2 text-[13px] font-medium text-white transition hover:bg-white/12",children:"Open agent onboarding"})})]})]}),e.jsx(ae,{children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"User directory"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:"Open any user to edit its identity and jump into the exact directional relationship lanes from the user settings flow."})]}),e.jsx(Q,{onClick:()=>{n(null),i(null),l(!0)},children:"Create user"})]})}),e.jsx("div",{className:"grid gap-5",children:[{title:"Human users",users:p.humans},{title:"Bot users",users:p.bots}].map($=>e.jsxs(ae,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:$.title}),e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:$.users.length})]}),e.jsx("div",{className:"mt-4 grid gap-3",children:$.users.map(g=>{var C,F,z,J,O,_;return e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(Ue,{user:g}),e.jsxs("div",{className:"mt-3 text-sm text-white/58",children:["@",g.handle]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/60",children:g.description||"No description yet."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs(L,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[((C=E.get(g.id))==null?void 0:C.totalXp)??0," XP"]}),e.jsxs(L,{className:"bg-white/[0.08] text-white/70",children:[((F=E.get(g.id))==null?void 0:F.weeklyXp)??0," weekly"]}),e.jsxs(L,{className:"bg-white/[0.08] text-white/70",children:[((z=E.get(g.id))==null?void 0:z.rewardEventCount)??0," ","rewards"]}),Object.entries(((J=M.get(g.id))==null?void 0:J.entityCounts)??{}).sort((B,K)=>K[1]-B[1]).slice(0,4).map(([B,K])=>e.jsxs(L,{className:"bg-white/[0.08] text-white/70",children:[K," ",B]},`${g.id}-${B}`)),e.jsxs(L,{className:"bg-white/[0.08] text-white/70",children:[((O=M.get(g.id))==null?void 0:O.totalOwnedEntities)??0," ","owned"]})]}),e.jsxs("div",{className:"mt-3 text-xs leading-5 text-white/50",children:["Can currently read:"," ",(D.get(g.id)??[]).map(B=>`${B.displayName} (${B.kind})`).join(", ")||"no other users"]}),(_=E.get(g.id))!=null&&_.lastRewardAt?e.jsxs("div",{className:"mt-2 text-xs leading-5 text-white/45",children:["Last XP movement:"," ",new Date(E.get(g.id).lastRewardAt).toLocaleString()]}):null]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Q,{variant:"secondary",onClick:()=>{n(null),i(g),l(!0)},children:"Open settings"})})]})},g.id)})})]},$.title))})]})]})}function js(t,s,i,a){return{value:t,label:s,description:i,searchText:`${s} ${i}`,kind:a}}function fu(t){const s=t.goals??[],i=t.projects??[],a=t.tasks??[],n=t.habits??[],r=t.values??[],l=t.patterns??[],o=t.behaviors??[],c=t.beliefs??[],x=t.reports??[];return[...s.map(v=>js(`goal:${v.id}`,v.title,"Goal","goal")),...i.map(v=>js(`project:${v.id}`,v.title,"Project","project")),...a.map(v=>js(`task:${v.id}`,v.title,"Task","task")),...n.map(v=>js(`habit:${v.id}`,v.title,"Habit","habit")),...r.map(v=>js(`psyche_value:${v.id}`,v.title,"Value","value")),...l.map(v=>js(`behavior_pattern:${v.id}`,v.title,"Pattern","pattern")),...o.map(v=>js(`behavior:${v.id}`,v.title,"Behavior","behavior")),...c.map(v=>js(`belief_entry:${v.id}`,v.statement,"Belief","belief")),...x.map(v=>js(`trigger_report:${v.id}`,v.title,"Report","report"))]}function bu(t){return t.map(s=>{const i=s.indexOf(":");if(i===-1)return null;const a=s.slice(0,i),n=s.slice(i+1);return!a||!n?null:{entityType:a,entityId:n,relationshipType:"context"}}).filter(s=>s!==null)}function qs(t){return`${(t/3600).toFixed(1)}h`}function Sa(t){return`${Math.round(t*100)}%`}function Uc(t){return t?new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"n/a"}function fo(t,s){const i=new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short"}),a=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"});return`${i.format(new Date(t))} · ${a.format(new Date(t))} - ${a.format(new Date(s))}`}function ua(t){return{qualitySummary:typeof t.annotations.qualitySummary=="string"?t.annotations.qualitySummary:"",notes:typeof t.annotations.notes=="string"?t.annotations.notes:"",tagsText:Array.isArray(t.annotations.tags)?t.annotations.tags.join(", "):"",linkValues:Array.isArray(t.links)?t.links.map(s=>`${s.entityType}:${s.entityId}`):[]}}function vu(t){return t.trim().toLowerCase()}function nN(t,s){return vu([t.sourceType,t.sourceDevice,fo(t.startedAt,t.endedAt),s.qualitySummary,s.notes,s.tagsText,String(t.sleepScore??""),String(t.regularityScore??""),typeof t.derived.recoveryState=="string"?t.derived.recoveryState:""].join(" "))}function rN(t){const s=new Map;for(const i of t)s.set(`source:${i.sourceType}`,{id:`source:${i.sourceType}`,label:i.sourceType.replaceAll("_"," "),description:"Source type",badge:e.jsx(L,{tone:"meta",className:"capitalize",children:i.sourceType.replaceAll("_"," ")})}),typeof i.derived.recoveryState=="string"&&s.set(`recovery:${i.derived.recoveryState}`,{id:`recovery:${i.derived.recoveryState}`,label:i.derived.recoveryState,description:"Derived recovery state",badge:e.jsx(L,{tone:"meta",className:"capitalize",children:i.derived.recoveryState})});return s.set("linked:yes",{id:"linked:yes",label:"Linked nights",description:"Already tied to Forge or Psyche context",badge:e.jsx(L,{tone:"meta",children:"Linked"})}),s.set("linked:no",{id:"linked:no",label:"Needs links",description:"No Forge or Psyche links yet",badge:e.jsx(L,{tone:"meta",children:"Needs links"})}),s.set("reflective:yes",{id:"reflective:yes",label:"Reflected",description:"Already has notes, quality summary, tags, or links",badge:e.jsx(L,{tone:"meta",children:"Reflected"})}),s.set("reflective:no",{id:"reflective:no",label:"Needs reflection",description:"Still missing reflection context",badge:e.jsx(L,{tone:"meta",children:"Needs reflection"})}),s.set("stages:yes",{id:"stages:yes",label:"Has stage data",description:"Night includes sleep stages",badge:e.jsx(L,{tone:"meta",children:"Stages"})}),Array.from(s.values())}function lN(t,s){return s.every(i=>i.startsWith("source:")?t.sourceType===i.slice(7):i.startsWith("recovery:")?t.derived.recoveryState===i.slice(9):i==="linked:yes"?t.links.length>0:i==="linked:no"?t.links.length===0:i==="reflective:yes"?typeof t.annotations.notes=="string"&&t.annotations.notes.trim().length>0||typeof t.annotations.qualitySummary=="string"&&t.annotations.qualitySummary.trim().length>0||Array.isArray(t.annotations.tags)&&t.annotations.tags.length>0||t.links.length>0:i==="reflective:no"?(!Array.isArray(t.annotations.tags)||t.annotations.tags.length===0)&&(typeof t.annotations.notes!="string"||t.annotations.notes.trim().length===0)&&(typeof t.annotations.qualitySummary!="string"||t.annotations.qualitySummary.trim().length===0)&&t.links.length===0:i==="stages:yes"?t.stageBreakdown.length>0:!0)}function oN({session:t,draft:s,linkOptions:i,pending:a,step:n,onStepChange:r,onDraftChange:l,onSave:o}){const c=[{id:"night",title:"Night context",description:"Inspect the timing, stage data, and quick quality summary."},{id:"reflection",title:"Reflection",description:"Capture what shaped the night and what it meant."},{id:"links",title:"Links",description:"Tie the night back to habits, projects, beliefs, patterns, or reports."}],x=typeof t.derived.efficiency=="number"?t.derived.efficiency:t.timeInBedSeconds>0?t.asleepSeconds/t.timeInBedSeconds:0,v=typeof t.derived.restorativeShare=="number"?t.derived.restorativeShare:0;return e.jsxs("div",{className:"grid gap-5",children:[e.jsx("div",{className:"rounded-[24px] bg-white/[0.04] p-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-lg text-white",children:[e.jsx(Nh,{className:"size-4 text-[var(--primary)]"}),e.jsx("span",{children:"Night review"})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:fo(t.startedAt,t.endedAt)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(L,{children:[qs(t.asleepSeconds)," asleep"]}),e.jsxs(L,{tone:"meta",children:[qs(t.timeInBedSeconds)," in bed"]}),e.jsxs(L,{tone:"meta",children:["Score ",t.sleepScore??"n/a"]})]})]})}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-3",children:c.map((u,f)=>e.jsxs("button",{type:"button",onClick:()=>r(f),className:`rounded-[20px] border px-4 py-3 text-left transition ${n===f?"border-[var(--primary)] bg-[var(--primary)]/10 text-white":"border-white/8 bg-white/[0.04] text-white/62 hover:bg-white/[0.06] hover:text-white"}`,children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:["Step ",f+1]}),e.jsx("div",{className:"mt-2 text-sm font-medium",children:u.title})]},u.id))}),e.jsxs("div",{className:"rounded-[24px] bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:c[n].title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:c[n].description}),n===0?e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Stage breakdown"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:t.stageBreakdown.length>0?t.stageBreakdown.map(u=>e.jsxs(L,{tone:"meta",children:[u.stage," ",qs(u.seconds)]},u.stage)):e.jsx("div",{className:"text-sm text-white/48",children:"No stage data synced for this night."})})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Efficiency"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Sa(x)})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Restorative share"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Sa(v)})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Recovery state"}),e.jsx("div",{className:"mt-2 text-lg text-white capitalize",children:typeof t.derived.recoveryState=="string"?t.derived.recoveryState:"n/a"})]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Bedtime drift"}),e.jsxs("div",{className:"mt-2 text-lg text-white",children:[t.bedtimeConsistencyMinutes??0,"m"]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Wake drift"}),e.jsxs("div",{className:"mt-2 text-lg text-white",children:[t.wakeConsistencyMinutes??0,"m"]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Source"}),e.jsx("div",{className:"mt-2 text-lg text-white capitalize",children:t.sourceType.replaceAll("_"," ")})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Quality summary"}),e.jsx(le,{value:s.qualitySummary,onChange:u=>l({qualitySummary:u.target.value}),placeholder:"Restless before sleep but recovered by morning."})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Tags"}),e.jsx(le,{value:s.tagsText,onChange:u=>l({tagsText:u.target.value}),placeholder:"travel, overload, good-routine, late-caffeine"})]})]}):null,n===1?e.jsx("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:"Reflection, trigger context, habits, or belief patterns"}),e.jsx(Me,{className:"min-h-[180px]",value:s.notes,onChange:u=>l({notes:u.target.value}),placeholder:"This night followed a late work push, poor wind-down, and rising rumination around the project deadline."})]})}):null,n===2?e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Search habits, goals, beliefs, patterns, projects, or reports and attach the context that explains this night."}),e.jsx(et,{options:i,selectedValues:s.linkValues,onChange:u=>l({linkValues:u}),placeholder:"Search Forge and Psyche records…"})]}):null]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"text-sm text-white/48",children:n<c.length-1?"Move through the night in steps, then save the reflection once the context is clear.":"Everything is ready. Save the night reflection back into Forge."}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Q,{type:"button",variant:"secondary",onClick:()=>r(Math.max(0,n-1)),disabled:n===0,children:"Back"}),n<c.length-1?e.jsxs(Q,{type:"button",onClick:()=>r(n+1),children:["Next",e.jsx(Gt,{className:"size-4"})]}):null,e.jsxs(Q,{type:"button",pending:a,pendingLabel:"Saving",onClick:o,children:[e.jsx(Yi,{className:"size-4"}),"Save night"]})]})]})]})}function dN(){var U;const t=Je(),s=We(),i=d.useRef(null),[a,n]=d.useState({}),[r,l]=d.useState(""),[o,c]=d.useState([]),[x,v]=d.useState(null),[u,f]=d.useState(0),h=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],m=fe({queryKey:["forge-sleep",...h],queryFn:async()=>(await Of(h)).sleep}),b=fe({queryKey:["forge-sleep-values",...h],queryFn:async()=>(await ps(h)).values}),w=fe({queryKey:["forge-sleep-patterns",...h],queryFn:async()=>(await Vs(h)).patterns}),M=fe({queryKey:["forge-sleep-behaviors",...h],queryFn:async()=>(await xs(h)).behaviors}),E=fe({queryKey:["forge-sleep-beliefs",...h],queryFn:async()=>(await As(h)).beliefs}),D=fe({queryKey:["forge-sleep-reports",...h],queryFn:async()=>(await bi(h)).reports});d.useEffect(()=>{m.data&&n(Object.fromEntries(m.data.sessions.map(I=>[I.id,ua(I)])))},[m.data]);const j=xe({mutationFn:async I=>ib(I.sleepId,{qualitySummary:I.qualitySummary,notes:I.notes,tags:I.tagsText.split(",").map(G=>G.trim()).filter(Boolean),links:bu(I.linkValues)}),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-sleep"]})}}),S=m.data,p=(S==null?void 0:S.sessions)??[],A=fu({goals:t.snapshot.dashboard.goals,projects:t.snapshot.dashboard.projects,tasks:t.snapshot.dashboard.tasks,habits:t.snapshot.dashboard.habits,values:b.data??[],patterns:w.data??[],behaviors:M.data??[],beliefs:E.data??[],reports:D.data??[]}),T=d.useMemo(()=>rN(p),[p]),k=d.useMemo(()=>{const I=vu(r);return[...p].sort((G,W)=>new Date(W.startedAt).getTime()-new Date(G.startedAt).getTime()).filter(G=>{const W=a[G.id]??ua(G);return(I.length===0||nN(G,W).includes(I))&&lN(G,o)})},[a,r,o,p]),$=k.length===p.length&&r.trim().length===0&&o.length===0?`${p.length} nights visible`:`${k.length} of ${p.length} nights visible`,g=k.find(I=>I.id===x)??p.find(I=>I.id===x)??null,C=g?a[g.id]??ua(g):null,F=Qi({count:k.length,getScrollElement:()=>i.current,estimateSize:()=>176,overscan:8});if(m.isLoading)return e.jsx(It,{eyebrow:"Sleep",title:"Loading sleep view",description:"Reading HealthKit sleep sessions and reflective links.",columns:2,blocks:6});if(m.isError||!S)return e.jsx(ze,{eyebrow:"Sleep",error:m.error??new Error("Sleep data unavailable"),onRetry:()=>void m.refetch()});const{summary:z,weeklyTrend:J,monthlyPattern:O,stageAverages:_,linkBreakdown:B}=S;function K(I,G){n(W=>{const ne=p.find(we=>we.id===I),de=W[I]??(ne?ua(ne):{qualitySummary:"",notes:"",tagsText:"",linkValues:[]});return{...W,[I]:{...de,...G}}})}async function Z(I){const G=p.find(ne=>ne.id===I);if(!G)return;const W=a[I]??ua(G);await j.mutateAsync({sleepId:I,qualitySummary:W.qualitySummary,notes:W.notes,tagsText:W.tagsText,linkValues:W.linkValues}),v(null),f(0)}return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{entityKind:"habit",title:"Sleep",description:"A reflective sleep surface linking rest, timing, and Psyche-aware context instead of treating nights as disposable telemetry.",badge:`${p.length} nights`}),e.jsx(Bt,{}),e.jsxs("section",{className:"grid gap-4 lg:grid-cols-4",children:[e.jsxs(ae,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Weekly sleep"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-[var(--primary)]",children:qs(z.totalSleepSeconds)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Total sleep across the recent week."})]}),e.jsxs(ae,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Average night"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:qs(z.averageSleepSeconds)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Mean sleep duration across recent nights."})]}),e.jsxs(ae,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Sleep score"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:z.averageSleepScore}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Derived score from duration, efficiency, and stages."})]}),e.jsxs(ae,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Regularity"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:z.averageRegularityScore}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Timing consistency across recent nights."})]}),e.jsxs(ae,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Efficiency"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Sa(z.averageEfficiency)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Average time asleep relative to time in bed."})]}),e.jsxs(ae,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Restorative share"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:Sa(z.averageRestorativeShare)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Deep and REM share across the recent week."})]}),e.jsxs(ae,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Reflected nights"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:z.reflectiveNightCount}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Nights carrying notes, tags, or linked Psyche context."})]}),e.jsxs(ae,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Bed and wake window"}),e.jsxs("div",{className:"mt-3 text-xl text-white",children:[z.averageBedtimeConsistencyMinutes,"m /"," ",z.averageWakeConsistencyMinutes,"m"]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Mean bedtime and wake-time drift against your recent baseline."})]})]}),e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[1.1fr_0.9fr]",children:[e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Trend"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Recent sleep pattern"})]}),e.jsx(L,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:"7 nights"})]}),e.jsx("div",{className:"grid gap-3",children:J.map(I=>e.jsxs("div",{className:"grid gap-2 rounded-[18px] bg-white/[0.04] px-4 py-3 md:grid-cols-[110px_minmax(0,1fr)_100px_100px]",children:[e.jsx("div",{className:"text-sm text-white/62",children:I.dateKey}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-2 flex-1 overflow-hidden rounded-full bg-white/[0.08]",children:e.jsx("div",{className:"h-full rounded-full bg-[var(--primary)]",style:{width:`${Math.min(100,I.sleepHours/10*100)}%`}})}),e.jsxs("div",{className:"text-sm text-white",children:[I.sleepHours.toFixed(1),"h"]})]}),e.jsxs("div",{className:"text-sm text-white/62",children:["Score ",I.score]}),e.jsxs("div",{className:"text-sm text-white/62",children:["Reg ",I.regularity]})]},I.id))}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Latest bedtime"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Uc(z.latestBedtime)})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Latest wake"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Uc(z.latestWakeTime)})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Linked nights"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:z.linkedNightCount})]})]})]}),e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Pattern surfaces"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Stage, timing, and linked context"})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Average stages"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:_.length>0?_.map(I=>e.jsxs(L,{tone:"meta",children:[I.stage," ",qs(I.averageSeconds)]},I.stage)):e.jsx("div",{className:"text-sm text-white/48",children:"Stage data will appear here when HealthKit exposes it."})})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Most-linked context"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:B.length>0?B.slice(0,6).map(I=>e.jsxs(L,{tone:"meta",children:[I.entityType.replaceAll("_"," ")," ",I.count]},I.entityType)):e.jsx("div",{className:"text-sm text-white/48",children:"Linked habits, beliefs, projects, and reports will accumulate here."})})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Monthly timing"}),e.jsx("div",{className:"mt-3 grid gap-2",children:O.slice(-5).map(I=>e.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm text-white/66",children:[e.jsx("span",{children:I.dateKey}),e.jsxs("span",{children:[I.onsetHour,":00 to ",I.wakeHour,":00"]}),e.jsxs("span",{children:[I.sleepHours.toFixed(1),"h"]})]},I.id))})]})]})]})]}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,25rem)_minmax(0,1fr)]",children:[e.jsx(Fa,{title:"Night browser",description:"Search previous nights by source, recovery state, reflective status, or whether they still need links.",query:r,onQueryChange:l,options:T,selectedOptionIds:o,onSelectedOptionIdsChange:c,resultSummary:$,placeholder:"Search nights, devices, summaries, notes, or filter chips",emptyStateMessage:"Keep typing or pick a filter chip to narrow the sleep history."}),e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Night history"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Open a night to add reflection and links in a guided modal."})]}),e.jsx(L,{tone:"meta",children:$})]}),e.jsx("div",{ref:i,className:"h-[34rem] overflow-y-auto rounded-[24px] border border-white/8 bg-white/[0.03]",children:k.length===0?e.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center text-sm leading-6 text-white/50",children:"No night matches the current search yet. Clear some filters or search by recovery state, device, or reflection text."}):e.jsx("div",{className:"relative w-full",style:{height:`${F.getTotalSize()}px`},children:F.getVirtualItems().map(I=>{const G=k[I.index],W=typeof G.annotations.notes=="string"&&G.annotations.notes.trim().length>0||typeof G.annotations.qualitySummary=="string"&&G.annotations.qualitySummary.trim().length>0||Array.isArray(G.annotations.tags)&&G.annotations.tags.length>0||G.links.length>0;return e.jsx("div",{"data-index":I.index,ref:F.measureElement,className:"absolute left-0 top-0 w-full px-3 py-2",style:{transform:`translateY(${I.start}px)`},children:e.jsxs("button",{type:"button",className:"grid w-full gap-3 rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3 text-left transition hover:bg-white/[0.07]",onClick:()=>{v(G.id),f(0)},children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[e.jsx(Nh,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"truncate text-base font-medium",children:fo(G.startedAt,G.endedAt)})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-sm text-white/56",children:[e.jsx(Xt,{className:"size-3.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[G.sourceType.replaceAll("_"," ")," · ",G.sourceDevice]})]})]}),e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full bg-white/[0.05] px-3 py-1.5 text-xs text-white/70",children:[e.jsx("span",{children:W?"Reflected":"Needs reflection"}),e.jsx(Gt,{className:"size-3.5"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(L,{children:[qs(G.asleepSeconds)," asleep"]}),e.jsxs(L,{tone:"meta",children:[qs(G.timeInBedSeconds)," in bed"]}),e.jsxs(L,{tone:"meta",children:["Score ",G.sleepScore??"n/a"]}),e.jsxs(L,{tone:"meta",children:["Eff"," ",Sa(typeof G.derived.efficiency=="number"?G.derived.efficiency:G.timeInBedSeconds>0?G.asleepSeconds/G.timeInBedSeconds:0)]}),typeof G.derived.recoveryState=="string"?e.jsx(L,{tone:"meta",className:"capitalize",children:G.derived.recoveryState}):null]})]})},G.id)})})})]})]}),g&&C?e.jsx(bs,{open:!!g,onOpenChange:I=>{I||(v(null),f(0))},eyebrow:"Sleep session",title:"Night reflection",description:"Capture context without crowding the main sleep surface.",children:e.jsx(oN,{session:g,draft:C,linkOptions:A,pending:j.isPending&&((U=j.variables)==null?void 0:U.sleepId)===g.id,step:u,onStepChange:f,onDraftChange:I=>K(g.id,I),onSave:()=>void Z(g.id)})}):null]})}function ul(t){return`${Math.round(t/60)}m`}function pl(t){return t?`${(t/1e3).toFixed(1)} km`:"n/a"}function bo(t,s){const i=new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short"}),a=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"});return`${i.format(new Date(t))} · ${a.format(new Date(t))} - ${a.format(new Date(s))}`}function pa(t){return{subjectiveEffort:t.subjectiveEffort!==null?String(t.subjectiveEffort):"",moodBefore:t.moodBefore??"",moodAfter:t.moodAfter??"",meaningText:t.meaningText??"",plannedContext:t.plannedContext??"",socialContext:t.socialContext??"",tagsText:Array.isArray(t.tags)?t.tags.join(", "):"",linkValues:Array.isArray(t.links)?t.links.map(s=>`${s.entityType}:${s.entityId}`):[]}}function wu(t){return t.trim().toLowerCase()}function cN(t,s){return wu([t.workoutType,t.sourceType,t.sourceDevice,t.reconciliationStatus,t.moodBefore,t.moodAfter,t.meaningText,t.plannedContext,t.socialContext,t.tags.join(" "),s.moodBefore,s.moodAfter,s.meaningText,s.plannedContext,s.socialContext,s.tagsText,bo(t.startedAt,t.endedAt)].join(" "))}function hN(t){const s=new Map;for(const i of t)s.set(`workout:${i.workoutType}`,{id:`workout:${i.workoutType}`,label:i.workoutType,description:"Workout type",searchText:`${i.workoutType} workout`,badge:e.jsx(L,{tone:"meta",children:i.workoutType})}),s.set(`source:${i.sourceType}`,{id:`source:${i.sourceType}`,label:i.sourceType.replaceAll("_"," "),description:"Source type",searchText:`${i.sourceType} source`,badge:e.jsx(L,{tone:"meta",className:"capitalize",children:i.sourceType.replaceAll("_"," ")})}),s.set(`status:${i.reconciliationStatus}`,{id:`status:${i.reconciliationStatus}`,label:i.reconciliationStatus.replaceAll("_"," "),description:"Reconciliation status",searchText:`${i.reconciliationStatus} status`,badge:e.jsx(L,{tone:"meta",className:"capitalize",children:i.reconciliationStatus.replaceAll("_"," ")})});return s.set("linked:yes",{id:"linked:yes",label:"Linked",description:"Already tied to Forge or Psyche context",badge:e.jsx(L,{tone:"meta",children:"Linked"})}),s.set("linked:no",{id:"linked:no",label:"Needs links",description:"No Forge or Psyche links yet",badge:e.jsx(L,{tone:"meta",children:"Needs links"})}),s.set("habit:yes",{id:"habit:yes",label:"Habit-generated",description:"Created from a habit completion",badge:e.jsx(L,{tone:"meta",children:"Habit-generated"})}),s.set("effort:rated",{id:"effort:rated",label:"Effort rated",description:"Already has a subjective effort score",badge:e.jsx(L,{tone:"meta",children:"Effort rated"})}),Array.from(s.values())}function mN(t,s){return s.every(i=>i.startsWith("workout:")?t.workoutType===i.slice(8):i.startsWith("source:")?t.sourceType===i.slice(7):i.startsWith("status:")?t.reconciliationStatus===i.slice(7):i==="linked:yes"?t.links.length>0:i==="linked:no"?t.links.length===0:i==="habit:yes"?!!t.generatedFromHabitId:i==="effort:rated"?t.subjectiveEffort!==null:!0)}function uN({session:t,draft:s,linkOptions:i,pending:a,step:n,onStepChange:r,onDraftChange:l,onSave:o}){const c=[{id:"context",title:"Session context",description:"Quick facts, effort, and how this session happened."},{id:"reflection",title:"Reflection",description:"Mood, meaning, and what the session actually did for you."},{id:"links",title:"Links",description:"Tie the session back to Forge and Psyche context."}];return e.jsxs("div",{className:"grid gap-5",children:[e.jsx("div",{className:"rounded-[24px] bg-white/[0.04] p-4",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-lg text-white",children:[e.jsx(yl,{className:"size-4 text-[var(--primary)]"}),e.jsx("span",{children:t.workoutType})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:bo(t.startedAt,t.endedAt)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(L,{children:ul(t.durationSeconds)}),t.totalEnergyKcal?e.jsxs(L,{tone:"meta",children:[Math.round(t.totalEnergyKcal)," kcal"]}):null,t.distanceMeters?e.jsx(L,{tone:"meta",children:pl(t.distanceMeters)}):null,e.jsx(L,{tone:"meta",className:"capitalize",children:t.reconciliationStatus.replaceAll("_"," ")})]})]})}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-3",children:c.map((x,v)=>e.jsxs("button",{type:"button",onClick:()=>r(v),className:`rounded-[20px] border px-4 py-3 text-left transition ${n===v?"border-[var(--primary)] bg-[var(--primary)]/10 text-white":"border-white/8 bg-white/[0.04] text-white/62 hover:bg-white/[0.06] hover:text-white"}`,children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:["Step ",v+1]}),e.jsx("div",{className:"mt-2 text-sm font-medium",children:x.title})]},x.id))}),e.jsxs("div",{className:"rounded-[24px] bg-white/[0.03] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:c[n].title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:c[n].description}),n===0?e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Source"}),e.jsx("div",{className:"mt-2 text-lg text-white capitalize",children:t.sourceType.replaceAll("_"," ")})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Steps"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:t.stepCount??"n/a"})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Max HR"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:t.maxHeartRate?Math.round(t.maxHeartRate):"n/a"})]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Effort"}),e.jsx(le,{type:"number",min:1,max:10,value:s.subjectiveEffort,onChange:x=>l({subjectiveEffort:x.target.value})})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Planned vs spontaneous"}),e.jsx(le,{value:s.plannedContext,onChange:x=>l({plannedContext:x.target.value}),placeholder:"Planned recovery block"})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Social context"}),e.jsx(le,{value:s.socialContext,onChange:x=>l({socialContext:x.target.value}),placeholder:"Solo, coach, group class, partner"})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Tags"}),e.jsx(le,{value:s.tagsText,onChange:x=>l({tagsText:x.target.value}),placeholder:"recovery, interval-block, stress-release"})]})]}):null,n===1?e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Mood before"}),e.jsx(le,{value:s.moodBefore,onChange:x=>l({moodBefore:x.target.value})})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Mood after"}),e.jsx(le,{value:s.moodAfter,onChange:x=>l({moodAfter:x.target.value})})]})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Meaning, impact, and why this session mattered"}),e.jsx(Me,{className:"min-h-[160px]",value:s.meaningText,onChange:x=>l({meaningText:x.target.value}),placeholder:"This session was planned as active recovery after a heavy work block and helped reset stress before sleep."})]})]}):null,n===2?e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Search goals, projects, habits, values, beliefs, patterns, or reports and attach the ones that explain this session."}),e.jsx(et,{options:i,selectedValues:s.linkValues,onChange:x=>l({linkValues:x}),placeholder:"Search Forge and Psyche records…"})]}):null]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"text-sm text-white/48",children:n<c.length-1?"Move through the session one step at a time, then save when the context is clean.":"Everything is in place. Save the session metadata back into Forge."}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Q,{type:"button",variant:"secondary",onClick:()=>r(Math.max(0,n-1)),disabled:n===0,children:"Back"}),n<c.length-1?e.jsxs(Q,{type:"button",onClick:()=>r(n+1),children:["Next",e.jsx(Gt,{className:"size-4"})]}):null,e.jsxs(Q,{type:"button",pending:a,pendingLabel:"Saving",onClick:o,children:[e.jsx(Yi,{className:"size-4"}),"Save session"]})]})]})]})}function pN(){var K;const t=Je(),s=We(),i=d.useRef(null),a=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],[n,r]=d.useState({}),[l,o]=d.useState(""),[c,x]=d.useState([]),[v,u]=d.useState(null),[f,h]=d.useState(0),m=fe({queryKey:["forge-fitness",...a],queryFn:async()=>(await Ff(a)).fitness}),b=fe({queryKey:["forge-health-values",...a],queryFn:async()=>(await ps(a)).values}),w=fe({queryKey:["forge-health-patterns",...a],queryFn:async()=>(await Vs(a)).patterns}),M=fe({queryKey:["forge-health-behaviors",...a],queryFn:async()=>(await xs(a)).behaviors}),E=fe({queryKey:["forge-health-beliefs",...a],queryFn:async()=>(await As(a)).beliefs}),D=fe({queryKey:["forge-health-reports",...a],queryFn:async()=>(await bi(a)).reports});d.useEffect(()=>{m.data&&r(Object.fromEntries(m.data.sessions.map(Z=>[Z.id,pa(Z)])))},[m.data]);const j=xe({mutationFn:async Z=>sb(Z.workoutId,{subjectiveEffort:Z.subjectiveEffort.trim().length>0?Number(Z.subjectiveEffort):null,moodBefore:Z.moodBefore,moodAfter:Z.moodAfter,meaningText:Z.meaningText,plannedContext:Z.plannedContext,socialContext:Z.socialContext,tags:Z.tagsText.split(",").map(U=>U.trim()).filter(Boolean),links:bu(Z.linkValues)}),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-fitness"]})}}),S=m.data,p=(S==null?void 0:S.sessions)??[],A=fu({goals:t.snapshot.dashboard.goals,projects:t.snapshot.dashboard.projects,tasks:t.snapshot.dashboard.tasks,habits:t.snapshot.dashboard.habits,values:b.data??[],patterns:w.data??[],behaviors:M.data??[],beliefs:E.data??[],reports:D.data??[]}),T=d.useMemo(()=>hN(p),[p]),k=d.useMemo(()=>{const Z=wu(l);return[...p].sort((U,I)=>new Date(I.startedAt).getTime()-new Date(U.startedAt).getTime()).filter(U=>{const I=n[U.id]??pa(U);return(Z.length===0||cN(U,I).includes(Z))&&mN(U,c)})},[n,l,c,p]),$=k.length===p.length&&l.trim().length===0&&c.length===0?`${p.length} workout sessions visible`:`${k.length} of ${p.length} workout sessions visible`,g=k.find(Z=>Z.id===v)??p.find(Z=>Z.id===v)??null,C=g?n[g.id]??pa(g):null,F=Qi({count:k.length,getScrollElement:()=>i.current,estimateSize:()=>108,overscan:8});if(m.isLoading)return e.jsx(It,{eyebrow:"Sports",title:"Loading sports view",description:"Reading synced workouts and local reflection metadata.",columns:2,blocks:6});if(m.isError||!S)return e.jsx(ze,{eyebrow:"Sports",error:m.error??new Error("Sports data unavailable"),onRetry:()=>void m.refetch()});const{summary:z,weeklyTrend:J,typeBreakdown:O}=S;function _(Z,U){r(I=>{const G=I[Z]??pa(p.find(W=>W.id===Z));return{...I,[Z]:{...G,...U}}})}async function B(Z){const U=p.find(G=>G.id===Z);if(!U)return;const I=n[Z]??pa(U);await j.mutateAsync({workoutId:Z,subjectiveEffort:I.subjectiveEffort,moodBefore:I.moodBefore,moodAfter:I.moodAfter,meaningText:I.meaningText,plannedContext:I.plannedContext,socialContext:I.socialContext,tagsText:I.tagsText,linkValues:I.linkValues}),u(null),h(0)}return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{entityKind:"project",title:"Sports",description:"A session-first training surface for workout data, subjective meaning, and links back into Forge execution and Psyche.",badge:`${p.length} sessions`}),e.jsxs("section",{className:"grid gap-4 lg:grid-cols-4",children:[e.jsxs(ae,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Weekly volume"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-[var(--primary)]",children:ul(z.weeklyVolumeSeconds)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Total training time in the recent week."})]}),e.jsxs(ae,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Exercise minutes"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:z.exerciseMinutes}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Aggregate exercise minutes from synced sessions."})]}),e.jsxs(ae,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Energy burned"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:z.energyBurnedKcal}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Recent weekly kcal."})]}),e.jsxs(ae,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Training streak"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:z.streakDays}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Distinct workout days in the recent week."})]}),e.jsxs(ae,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Average session"}),e.jsxs("div",{className:"mt-3 font-display text-4xl text-white",children:[z.averageSessionMinutes,"m"]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Mean duration across recent sessions."})]}),e.jsxs(ae,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Average effort"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:z.averageEffort||"n/a"}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Subjective effort across sessions that carry a rating."})]}),e.jsxs(ae,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Linked sessions"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:z.linkedSessionCount}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Sessions already tied to Forge or Psyche entities."})]}),e.jsxs(ae,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Top block"}),e.jsx("div",{className:"mt-3 text-xl text-white",children:z.topWorkoutType??"n/a"}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Dominant workout type across the recent window."})]})]}),e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[1.05fr_0.95fr]",children:[e.jsxs(ae,{className:"grid gap-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Recent volume"}),e.jsx("div",{className:"grid gap-3",children:J.map(Z=>e.jsxs("div",{className:"grid gap-2 rounded-[18px] bg-white/[0.04] px-4 py-3 md:grid-cols-[110px_150px_minmax(0,1fr)_90px]",children:[e.jsx("div",{className:"text-sm text-white/62",children:Z.dateKey}),e.jsx("div",{className:"text-sm text-white",children:Z.workoutType}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-2 flex-1 overflow-hidden rounded-full bg-white/[0.08]",children:e.jsx("div",{className:"h-full rounded-full bg-[var(--primary)]",style:{width:`${Math.min(100,Z.durationMinutes/120*100)}%`}})}),e.jsxs("div",{className:"text-sm text-white",children:[Z.durationMinutes,"m"]})]}),e.jsxs("div",{className:"text-sm text-white/62",children:[Z.energyKcal," kcal"]})]},Z.id))}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Distance"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:pl(z.distanceMeters)})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Planned sessions"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:z.plannedSessionCount})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Imported / merged"}),e.jsxs("div",{className:"mt-2 text-lg text-white",children:[z.importedSessionCount," / ",z.reconciledSessionCount]})]})]})]}),e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Training composition"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Workout type and provenance mix"})]}),e.jsx("div",{className:"grid gap-3",children:O.slice(0,6).map(Z=>e.jsxs("div",{className:"grid gap-2 rounded-[18px] bg-white/[0.04] px-4 py-3 md:grid-cols-[minmax(0,1fr)_90px_90px]",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-white",children:Z.workoutType}),e.jsxs("div",{className:"mt-1 text-sm text-white/58",children:[Z.sessionCount," sessions"]})]}),e.jsxs("div",{className:"text-sm text-white/72",children:[Z.totalMinutes,"m"]}),e.jsxs("div",{className:"text-sm text-white/72",children:[Z.energyKcal," kcal"]})]},Z.workoutType))}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Habit-generated"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:z.habitGeneratedSessionCount})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Forge-linked"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:z.linkedSessionCount})]})]})]})]}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,25rem)_minmax(0,1fr)]",children:[e.jsx(Fa,{title:"Session browser",description:"Search past activities by workout type, source, reconciliation state, or whether they still need context.",query:l,onQueryChange:o,options:T,selectedOptionIds:c,onSelectedOptionIdsChange:x,resultSummary:$,placeholder:"Search workouts, devices, notes, moods, or filter chips",emptyStateMessage:"Keep typing or pick a filter chip to narrow the activity history."}),e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Activity history"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Open a workout to add reflection and links in a guided modal."})]}),e.jsx(L,{tone:"meta",children:$})]}),e.jsx("div",{ref:i,className:"h-[34rem] overflow-y-auto rounded-[24px] border border-white/8 bg-white/[0.03]",children:k.length===0?e.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center text-sm leading-6 text-white/50",children:"No workout matches the current search yet. Clear some filters or search by workout type, device, or reflection text."}):e.jsx("div",{className:"relative w-full",style:{height:`${F.getTotalSize()}px`},children:F.getVirtualItems().map(Z=>{const U=k[Z.index],I=U.meaningText.trim().length>0||U.moodBefore.trim().length>0||U.moodAfter.trim().length>0||U.tags.length>0||U.links.length>0;return e.jsx("div",{className:"absolute left-0 top-0 w-full px-3 py-2",style:{transform:`translateY(${Z.start}px)`},children:e.jsxs("button",{type:"button",className:"grid w-full gap-3 rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3 text-left transition hover:bg-white/[0.07]",onClick:()=>{u(U.id),h(0)},children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[e.jsx(yl,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"truncate text-base font-medium",children:U.workoutType})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-sm text-white/56",children:[e.jsx(Xt,{className:"size-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:bo(U.startedAt,U.endedAt)})]})]}),e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full bg-white/[0.05] px-3 py-1.5 text-xs text-white/70",children:[e.jsx("span",{children:I?"Reflected":"Needs reflection"}),e.jsx(Gt,{className:"size-3.5"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(L,{children:ul(U.durationSeconds)}),U.totalEnergyKcal?e.jsxs(L,{tone:"meta",children:[Math.round(U.totalEnergyKcal)," kcal"]}):null,U.distanceMeters?e.jsx(L,{tone:"meta",children:pl(U.distanceMeters)}):null,U.averageHeartRate?e.jsxs(L,{tone:"meta",children:[e.jsx(Wp,{className:"mr-1 size-3.5"}),Math.round(U.averageHeartRate)," bpm"]}):null,e.jsx(L,{tone:"meta",className:"capitalize",children:U.sourceType.replaceAll("_"," ")}),e.jsx(L,{tone:"meta",className:"capitalize",children:U.reconciliationStatus.replaceAll("_"," ")})]})]})},U.id)})})})]})]}),g&&C?e.jsx(bs,{open:!!g,onOpenChange:Z=>{Z||(u(null),h(0))},eyebrow:"Sports session",title:g.workoutType,description:"Add contextual meaning without crowding the main training surface.",children:e.jsx(uN,{session:g,draft:C,linkOptions:A,pending:j.isPending&&((K=j.variables)==null?void 0:K.workoutId)===g.id,step:f,onStepChange:h,onDraftChange:Z=>_(g.id,Z),onSave:()=>void B(g.id)})}):null]})}function Ai({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(it,{content:s,label:`Explain ${t}`}):null]})}const xa=[{status:"backlog",label:"Backlog",description:"Not started yet.",icon:gi},{status:"focus",label:"Focus",description:"Ready to start soon.",icon:Fn},{status:"in_progress",label:"In progress",description:"Work is active now.",icon:Cs},{status:"blocked",label:"Blocked",description:"Something is stopping progress.",icon:gh},{status:"done",label:"Done",description:"The task is completed.",icon:Ia}];function xN(){var Z,U;const{t,formatDate:s,formatDateTime:i}=lt(),a=Je(),n=Array.isArray(a.selectedUserIds)?a.selectedUserIds:[],r=es(),l=ut(),o=We(),c=Mt(n),[x,v]=d.useState(!1),[u,f]=d.useState(!1),[h,m]=d.useState(!1),[b,w]=d.useState(()=>typeof window<"u"?window.matchMedia("(max-width: 1023px)").matches:!1),[M]=d.useState(()=>{const I=new Date,G=new Date(I);G.setHours(0,0,0,0);const W=new Date(I);return W.setHours(23,59,59,999),{from:G.toISOString(),to:W.toISOString()}});d.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const I=window.matchMedia("(max-width: 1023px)"),G=W=>w(W?W.matches:I.matches);return G(),typeof I.addEventListener=="function"?(I.addEventListener("change",G),()=>I.removeEventListener("change",G)):(I.addListener(G),()=>I.removeListener(G))},[]);const E=fe({queryKey:["task-context",r.taskId],queryFn:()=>Ib(r.taskId),enabled:!!r.taskId}),D=fe({queryKey:["task-calendar-overview",r.taskId,M.from,M.to,...n],queryFn:()=>Xn({...M,userIds:n}),enabled:!!r.taskId}),j=async()=>{await Promise.all([o.invalidateQueries({queryKey:["forge-snapshot"]}),o.invalidateQueries({queryKey:["task-context",r.taskId]}),o.invalidateQueries({queryKey:["activity-archive"]}),o.invalidateQueries({queryKey:["project-board"]}),o.invalidateQueries({queryKey:["forge-xp-metrics"]}),o.invalidateQueries({queryKey:["forge-reward-ledger"]}),o.invalidateQueries({queryKey:["forge-operator-context"]})])},S=xe({mutationFn:({taskId:I,patch:G})=>Oa(I,G),onSuccess:j}),p=xe({mutationFn:I=>Ql(I),onSuccess:j}),A=xe({mutationFn:I=>Xh(I),onSuccess:j}),T=xe({mutationFn:({runId:I,actor:G,note:W})=>Jh(I,{actor:G,note:W??""}),onSuccess:j}),k=xe({mutationFn:({runId:I,actor:G,note:W})=>Vh(I,{actor:G,note:W??""}),onSuccess:j}),$=xe({mutationFn:Gh,onSuccess:j}),g=xe({mutationFn:I=>Ul(I),onSuccess:j}),C=E.data;if(E.isLoading)return e.jsx(It,{});if(E.isError)return e.jsx(ze,{eyebrow:t("common.taskDetail.errorEyebrow"),error:E.error,onRetry:()=>void E.refetch()});if(!C)return e.jsx(ze,{eyebrow:t("common.taskDetail.errorEyebrow"),error:new Error(t("common.taskDetail.emptyPayload")),onRetry:()=>void E.refetch()});const F=C.activeTaskRun??null,z=xa.find(I=>I.status===C.task.status)??xa[0];xa.filter(I=>I.status!==C.task.status);const J=Yy(C.task,(Z=C.project)==null?void 0:Z.schedulingRules),O=Wm({rules:J,overview:(U=D.data)==null?void 0:U.calendar}),_=I=>{switch(I){case"active":return"Active";case"completed":return"Completed";case"released":return"Paused";case"timed_out":return"Timed out";default:return I}},B=async I=>{await S.mutateAsync({taskId:C.task.id,patch:{status:I}}),m(!1)},K=async()=>{window.confirm(t("common.taskDetail.deleteTaskConfirm",{title:C.task.title}))&&(await g.mutateAsync(C.task.id),l(C.project?`/projects/${C.project.id}`:C.goal?`/goals/${C.goal.id}`:"/kanban"))};return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{entityKind:"task",title:e.jsx(Xe,{kind:"task",label:C.task.title,variant:"heading",size:"lg",lines:3,className:"max-w-full",labelClassName:"[overflow-wrap:anywhere]"}),titleText:C.task.title,description:C.task.description?e.jsx(ms,{markdown:C.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:`${C.task.points} xp`,actions:e.jsx(er,{userId:c,domain:"tasks",entityType:"task",entityId:C.task.id,label:C.task.title,description:C.task.description})}),C.task.user?e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-white/62",children:[e.jsx("span",{className:"text-white/42",children:"Owned by"}),e.jsx(Ue,{user:C.task.user})]}):null,e.jsxs(ae,{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(Xe,{kind:"task",label:C.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:C.task.description?e.jsx(ms,{markdown:C.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(Q,{pending:E.isFetching,pendingLabel:F?"Opening":"Starting",onClick:async()=>{await a.startTaskNow(C.task.id),await j()},children:[e.jsx(Cs,{className:"size-4 fill-current"}),F?"Focus work":"Start work"]}),F?e.jsxs(e.Fragment,{children:[e.jsx(Q,{variant:"secondary",pending:T.isPending,pendingLabel:"Pausing",onClick:async()=>{await T.mutateAsync({runId:F.id,actor:F.actor,note:F.note})},children:"Pause"}),e.jsx(Q,{variant:"secondary",pending:k.isPending,pendingLabel:"Completing",onClick:async()=>{await k.mutateAsync({runId:F.id,actor:F.actor,note:F.note})},children:"Complete"})]}):null,e.jsxs(Q,{variant:"secondary",onClick:()=>f(!0),children:[e.jsx(gi,{className:"size-4"}),"Adjust work"]}),b?e.jsxs(e.Fragment,{children:[e.jsx(Q,{variant:"secondary",size:"sm","aria-label":"Change task status",onClick:()=>m(!0),children:e.jsx(z.icon,{className:"size-4"})}),e.jsx(Q,{variant:"secondary",size:"sm","aria-label":"Edit task",onClick:()=>v(!0),children:e.jsx(mi,{className:"size-4"})})]}):e.jsxs(Q,{variant:"secondary",onClick:()=>v(!0),children:[e.jsx(mi,{className:"size-4"}),"Edit task"]}),C.task.status==="done"?e.jsx(Q,{variant:"secondary",onClick:async()=>{await p.mutateAsync(C.task.id)},children:"Mark as not done"}):null,e.jsx(Q,{variant:"ghost",className:"text-rose-200 hover:bg-rose-500/10",pending:g.isPending,pendingLabel:t("common.taskDetail.deleting"),onClick:()=>void K(),children:t("common.taskDetail.deleteTask")})]})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap gap-2",children:[e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:z.label}),e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:t(`common.enums.priority.${C.task.priority}`)}),e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:t(`common.enums.effort.${C.task.effort}`)}),e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:t(`common.enums.energy.${C.task.energy}`)}),e.jsxs(L,{className:"bg-white/[0.08] text-white/72",children:[C.task.points," xp"]}),C.task.time.totalCreditedSeconds>0?e.jsxs(L,{className:"bg-white/[0.08] text-white/72",children:[Math.floor(C.task.time.totalCreditedSeconds/60)," min tracked"]}):null,F?e.jsx(L,{className:"bg-emerald-500/12 text-emerald-200",children:"Timer active"}):null]}),b?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:xa.map(I=>{const G=I.icon,W=I.status===C.task.status;return e.jsxs("button",{type:"button",disabled:W||S.isPending,className:`rounded-[18px] border px-3.5 py-3 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/72 hover:bg-white/[0.08]"}`,onClick:()=>void B(I.status),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"font-medium",children:I.label})]}),e.jsx("div",{className:"mt-2 text-xs leading-5 text-white/54",children:I.description})]},I.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(Ai,{label:"Project",help:"The project is the main work stream this task belongs to."}),e.jsx("div",{className:"mt-2",children:C.project?e.jsx(Ae,{to:`/projects/${C.project.id}`,className:"inline-flex max-w-full",children:e.jsx(Te,{kind:"project",label:C.project.title,compact:!0,gradient:!1,wrap:!0,className:"max-w-full"})}):e.jsx(L,{className:"bg-white/[0.08] text-white/65",children:"No project linked"})})]}),e.jsxs("div",{children:[e.jsx(Ai,{label:"Goal",help:"The goal shows the longer-term result this task supports."}),e.jsx("div",{className:"mt-2",children:C.goal?e.jsx(Ae,{to:`/goals/${C.goal.id}`,className:"inline-flex max-w-full",children:e.jsx(Te,{kind:"goal",label:C.goal.title,compact:!0,gradient:!1,wrap:!0,className:"max-w-full"})}):e.jsx(L,{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(Ai,{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(C.task.dueDate)})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Ai,{label:"Owner",help:"The owner is the person or role expected to carry this task."}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2 text-white",children:[C.task.user?e.jsx(Ue,{user:C.task.user,compact:!0}):null,e.jsx("span",{children:C.task.owner})]})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Ai,{label:"Created"}),e.jsx("div",{className:"mt-2 text-white",children:i(C.task.createdAt)})]}),e.jsxs("div",{className:"rounded-[16px] bg-white/[0.03] px-3.5 py-3",children:[e.jsx(Ai,{label:"Updated"}),e.jsx("div",{className:"mt-2 text-white",children:i(C.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(it,{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:F?`${F.timerMode==="planned"?"Planned":"Unlimited"} timer active with ${Math.floor(F.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(Yl,{title:"Task scheduling",subtitle:"Set when this task can run. If you leave it empty, the project defaults stay in force.",initialRules:C.task.schedulingRules,initialPlannedDurationSeconds:C.task.plannedDurationSeconds,allowPlannedDuration:!0,saveLabel:"Save task scheduling",onSave:async({schedulingRules:I,plannedDurationSeconds:G})=>{await S.mutateAsync({taskId:C.task.id,patch:{schedulingRules:I,plannedDurationSeconds:G}}),await o.invalidateQueries({queryKey:["task-calendar-overview",r.taskId]})}}),e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Calendar status"}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(L,{className:O.tone==="blocked"?"bg-rose-500/14 text-rose-100":O.tone==="waiting"?"bg-amber-500/14 text-amber-100":"bg-emerald-500/14 text-emerald-100",children:O.label}),e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:C.task.schedulingRules?"Task override":"Using project defaults"}),C.task.plannedDurationSeconds?e.jsxs(L,{className:"bg-white/[0.08] text-white/72",children:[Math.round(C.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."}),O.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:O.context.map(I=>e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:I},I))})]}):null,O.conflicts.length>0?e.jsx("div",{className:"mt-4 grid gap-2",children:O.conflicts.map(I=>e.jsx("div",{className:"rounded-[16px] bg-rose-500/10 px-3 py-2 text-sm text-rose-100",children:I},I))}):null,e.jsx("div",{className:"mt-4",children:e.jsx(Ae,{to:"/calendar",children:e.jsx(Q,{variant:"secondary",children:"Open calendar workspace"})})})]})]}),e.jsx("div",{className:"mt-5",children:e.jsx(Zn,{entityType:"task",entityId:C.task.id,title:"Task notes",description:"Capture real progress, blockers, and context in Markdown so the task keeps a durable work log.",invalidateQueryKeys:[["task-context",r.taskId],...C.task.projectId?[["project-board",C.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:[C.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,C.activity.map(I=>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:tr(I)}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:sr(I)}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.16em] text-white/35",children:i(I.createdAt)})]}),e.jsx(Q,{variant:"ghost",className:"shrink-0",onClick:async()=>{await A.mutateAsync(I.id)},children:"Remove"})]}),Gs(I)&&In(I)?e.jsx(Ae,{to:Gs(I),className:"mt-3 inline-flex text-[11px] uppercase tracking-[0.16em] text-[var(--primary)]",children:In(I)}):null]},I.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:[C.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,C.taskRuns.map(I=>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:I.actor}),e.jsx(L,{children:_(I.status)})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:I.note||t("common.labels.noRunNote")}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.16em] text-white/35",children:i(I.updatedAt)})]},I.id))]})]})]}),e.jsx(Jn,{open:x,goals:a.snapshot.goals,projects:a.snapshot.dashboard.projects,tags:a.snapshot.tags,users:a.snapshot.users,editingTask:C.task,defaultUserId:C.task.userId??c,onOpenChange:v,onSubmit:async(I,G)=>{G&&await S.mutateAsync({taskId:G,patch:I})}}),e.jsx(Um,{open:u,onOpenChange:f,entityType:"task",entityId:C.task.id,targetLabel:C.task.title,currentCreditedSeconds:C.task.time.totalCreditedSeconds,pending:$.isPending,onSubmit:async I=>{await $.mutateAsync(I)}}),e.jsx(bs,{open:h,onOpenChange:m,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:xa.map(I=>{const G=I.icon,W=I.status===C.task.status;return e.jsx("button",{type:"button",disabled:W||S.isPending,className:`rounded-[22px] 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/72 hover:bg-white/[0.08]"}`,onClick:()=>void B(I.status),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(G,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:I.label}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:I.description})]})]})},I.status)})})})]})}function Qc(t,s,i){var a;return((a=s.find(n=>n.id===t.goalId))==null?void 0:a.title)??i}function gN(t,s){return t.tagIds.map(i=>s.find(a=>a.id===i)).filter(Boolean)}function fN(t,s){(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),s())}function bN(t,s){switch(t.status){case"backlog":return{label:s.backlog,action:"start",icon:Cs};case"focus":return{label:s.focus,action:"start",icon:Cs};case"in_progress":return{label:s.in_progress,nextStatus:"done",action:"move",icon:Ia};case"blocked":return{label:s.blocked,action:"start",icon:Cs};default:return null}}function vN({tasks:t,timeline:s,goals:i,tags:a,notesSummaryByEntity:n,selectedTaskId:r,onSelectTask:l,onMove:o,onStartTask:c}){const{t:x,formatDate:v}=lt(),u={backlog:x("common.dailyRunway.actionBacklog"),focus:x("common.dailyRunway.actionFocus"),in_progress:x("common.dailyRunway.actionProgress"),blocked:x("common.dailyRunway.actionBlocked")};return e.jsxs("div",{className:"grid min-w-0 gap-4 2xl:grid-cols-[minmax(0,1.3fr)_minmax(17rem,0.9fr)]",children:[e.jsxs("div",{className:"min-w-0 rounded-[24px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:x("common.dailyRunway.runwayEyebrow")}),e.jsx(it,{content:"These are the tasks that matter most for today. Click a card to open the task details. Use Start to begin work immediately."})]}),e.jsx("h4",{className:"mt-2 font-display text-2xl text-white",children:x("common.dailyRunway.runwayTitle")})]}),e.jsx(L,{className:"shrink-0 text-[var(--primary)]",children:x(t.length===1?"common.dailyRunway.prioritiesOne":"common.dailyRunway.prioritiesOther",{count:t.length})})]}),e.jsx("div",{className:"mt-4 grid min-w-0 gap-3",children:t.map((f,h)=>{const m=bN(f,u),b=gN(f,a).slice(0,2),w=r===f.id,M=is(n,"task",f.id).count;return e.jsxs("article",{role:"button",tabIndex:0,"aria-pressed":w,className:`grid w-full gap-3 rounded-[22px] px-4 py-4 text-left transition ${w?"bg-[linear-gradient(180deg,rgba(192,193,255,0.16),rgba(192,193,255,0.05))] shadow-[inset_0_0_0_1px_rgba(192,193,255,0.2)]":"bg-white/[0.03] hover:bg-white/[0.06]"}`,onClick:()=>l(f.id),onKeyDown:E=>fN(E,()=>l(f.id)),children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:x("common.dailyRunway.runwayItem",{index:h+1})}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(Te,{kind:"goal",label:Qc(f,i,x("common.dailyRunway.unassigned")),compact:!0,gradient:!1}),f.time.activeRunCount>0?e.jsx(L,{className:"bg-emerald-500/12 text-emerald-200",children:"Live"}):null]}),e.jsx("div",{className:"mt-2",children:e.jsx(Xe,{kind:"task",label:f.title,variant:"heading",size:"md"})}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:f.description||x("common.dailyRunway.noNote")})]}),e.jsx(L,{className:"shrink-0 self-start",children:f.status.replaceAll("_"," ")})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(L,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[f.points," xp"]}),e.jsx(Vt,{entityType:"task",entityId:f.id,count:M}),f.time.totalCreditedSeconds>0?e.jsxs(L,{className:"bg-white/[0.08] text-white/70",children:[Math.floor(f.time.totalCreditedSeconds/60)," min tracked"]}):null,e.jsx(L,{className:"bg-white/[0.08] text-white/70",children:f.effort}),e.jsx(L,{className:"bg-white/[0.08] text-white/70",children:v(f.dueDate)}),b.map(E=>e.jsx(L,{className:"bg-white/[0.08]",style:{color:E.color},children:E.name},E.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:f.owner}),m?e.jsxs(Q,{variant:m.action==="start"?"primary":"secondary",className:"px-3 py-2 text-[11px] uppercase tracking-[0.16em]",onClick:async E=>{if(E.stopPropagation(),m.action==="start"){await c(f.id);return}m.nextStatus&&await o(f.id,m.nextStatus)},children:[e.jsx(m.icon,{className:"mr-2 size-3.5"}),m.label]}):null]})]},f.id)})})]}),e.jsxs("div",{className:"min-w-0 rounded-[24px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:x("common.dailyRunway.timelineEyebrow")}),e.jsx(it,{content:"This groups today's tasks by status, so you can see what is already moving, what is ready to start, what is blocked, and what is done."})]}),e.jsx("h4",{className:"mt-2 font-display text-2xl text-white",children:x("common.dailyRunway.timelineTitle")}),e.jsx("div",{className:"mt-4 grid min-w-0 gap-3",children:s.map(f=>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:f.label}),e.jsx(L,{className:"bg-white/[0.08] text-white/65",children:f.tasks.length})]}),e.jsxs("div",{className:"mt-3 grid gap-2",children:[f.tasks.slice(0,3).map(h=>e.jsxs("button",{type:"button",className:"flex min-w-0 items-center justify-between gap-3 overflow-hidden rounded-[16px] bg-white/[0.03] px-3 py-3 text-left transition hover:bg-white/[0.06]",onClick:()=>l(h.id),children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx(Xe,{kind:"task",label:h.title,className:"max-w-full",labelClassName:"[overflow-wrap:anywhere]"}),e.jsx("div",{className:"mt-2",children:e.jsx(Te,{kind:"goal",label:Qc(h,i,x("common.dailyRunway.unassigned")),compact:!0,gradient:!1})})]}),e.jsx(Gt,{className:"size-4 shrink-0 text-white/35"})]},h.id)),f.tasks.length===0?e.jsx("div",{className:"text-sm text-white/42",children:x("common.dailyRunway.emptyBucket")}):null]})]},f.id))})]})]})}const wN=5;function yN(){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 jN(t,s){const i=new Date(t.startAt),a=new Date(t.endAt);return i<s.end&&a>s.start}function NN(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 kN(){var m;const{t}=lt(),s=Je(),i=ut(),a=d.useMemo(()=>yN(),[]),n=Array.isArray(s.selectedUserIds)?s.selectedUserIds:[],r=fe({queryKey:["forge-calendar-overview",a.from,a.to,...n],queryFn:()=>Xn({from:a.from,to:a.to,userIds:n})}),l=s.snapshot.today.directive.task,o=s.snapshot.today.milestoneRewards.find(b=>!b.completed)??s.snapshot.today.milestoneRewards[0]??null,c=s.snapshot.risk.blockedTasks[0]??s.snapshot.risk.overdueTasks[0]??null,x=Math.max(0,s.snapshot.metrics.nextLevelXp-s.snapshot.metrics.currentLevelXp),v=d.useMemo(()=>{var b;return(((b=r.data)==null?void 0:b.calendar.events)??[]).filter(w=>!w.deletedAt&&w.status!=="cancelled"&&jN(w,a)).sort((w,M)=>new Date(w.startAt).getTime()-new Date(M.startAt).getTime())},[(m=r.data)==null?void 0:m.calendar.events,a]),u=v.slice(0,wN);if(!(l!==null||s.snapshot.overview.topTasks.length>0||s.snapshot.today.dueHabits.length>0||s.snapshot.today.dailyQuests.length>0||s.snapshot.today.milestoneRewards.length>0||v.length>0)&&!r.isLoading)return e.jsxs("div",{className:"grid gap-4",children:[e.jsx(qe,{title:"Today",titleText:"Today",description:"Start a task, earn XP, and keep today's work clear.",badge:`${s.snapshot.metrics.weeklyXp} weekly xp`}),e.jsx(gt,{eyebrow:t("common.todayPage.heroEyebrow"),title:t("common.todayPage.emptyTitle"),description:t("common.todayPage.emptyDescription"),action:e.jsx(Ae,{to:"/goals",className:"inline-flex min-h-10 min-w-max shrink-0 items-center justify-center rounded-full bg-[var(--primary)] px-4 py-2 text-sm font-medium whitespace-nowrap text-slate-950 transition hover:opacity-90",children:t("common.todayPage.emptyAction")})})]});const h=[{id:"hero",title:"Today",description:"Compact page header.",defaultWidth:12,defaultHeight:2,removable:!1,surfaceChrome:"none",defaultTitleVisible:!1,defaultDescriptionVisible:!1,render:()=>e.jsx(qe,{title:"Today",titleText:"Today",description:(l==null?void 0:l.description)??"Start one real task, collect XP, and keep today's work moving.",badge:`${s.snapshot.metrics.weeklyXp} weekly xp`})},{id:"metrics",title:"Live metrics",description:"XP, level, and momentum stay visible but lighter than before.",defaultWidth:5,defaultHeight:4,minWidth:4,render:({compact:b})=>e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs(ae,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Weekly XP"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-[var(--primary)]",children:s.snapshot.metrics.weeklyXp}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[s.snapshot.metrics.totalXp," total XP"]})]}),e.jsxs(ae,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Level"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-white",children:s.snapshot.metrics.level}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[x," xp to the next level"]}),b?null:e.jsx("div",{className:"mt-3",children:e.jsx(us,{value:s.snapshot.metrics.currentLevelXp/s.snapshot.metrics.nextLevelXp*100,tone:"tertiary"})})]}),e.jsxs(ae,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Momentum"}),e.jsxs("div",{className:"mt-2 font-display text-4xl text-white",children:[s.snapshot.metrics.momentumScore,"%"]}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[s.snapshot.metrics.streakDays," day streak"]})]}),e.jsxs(ae,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Next reward"}),e.jsx("div",{className:"mt-2 text-base font-semibold text-white",children:(o==null?void 0:o.title)??"Keep showing up"}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:(o==null?void 0:o.progressLabel)??"The next visible win comes from a task completion or aligned habit check-in."})]})]})},{id:"runway",title:"Runway",description:"The execution lane itself can be widened or narrowed.",defaultWidth:7,defaultHeight:6,minWidth:5,render:()=>e.jsx(vN,{tasks:s.snapshot.overview.topTasks,timeline:s.snapshot.today.timeline,goals:s.snapshot.goals,tags:s.snapshot.tags,notesSummaryByEntity:s.snapshot.dashboard.notesSummaryByEntity,selectedTaskId:(l==null?void 0:l.id)??null,onSelectTask:b=>i(`/tasks/${b}`),onStartTask:async b=>{await s.startTaskNow(b)},onMove:async(b,w)=>{await s.patchTaskStatus(b,w)}})},{id:"calendar",title:"Calendar",description:"Today's events stay grouped with their results instead of splitting search from outcome.",defaultWidth:5,defaultHeight:5,minWidth:4,render:({compact:b})=>e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"inline-flex size-10 shrink-0 items-center justify-center rounded-2xl bg-[var(--primary)]/14 text-[var(--primary)]",children:e.jsx(Xt,{className:"size-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Today's calendar"}),e.jsx("div",{className:"text-sm font-semibold text-white",children:new Intl.DateTimeFormat(void 0,{weekday:"short",month:"short",day:"numeric"}).format(a.start)}),e.jsxs("div",{className:"text-sm text-white/58",children:[v.length," event",v.length===1?"":"s"]})]})]}),e.jsxs(Ae,{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(yh,{className:"size-3.5"})]})]}),v.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4 text-sm text-white/58",children:"Nothing is scheduled yet for today."}):u.map(w=>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:()=>i("/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:w.title}),e.jsx("div",{className:"mt-1 text-sm text-white/58",children:NN(w)})]}),e.jsx(L,{className:"shrink-0 bg-white/[0.08] text-white/72",children:w.originType==="native"?"Forge":w.originType})]}),!b&&w.description?e.jsx("div",{className:"line-clamp-2 text-sm leading-6 text-white/52",children:w.description}):null]},w.id))]})},{id:"focus",title:"Current focus",description:"Current task, comeback task, and due habits stay in one movable stack.",defaultWidth:12,defaultHeight:4,minWidth:6,render:({compact:b})=>{var w;return e.jsxs("div",{className:"grid min-w-0 gap-4 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]",children:[e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Current task"}),l?e.jsx(Vt,{entityType:"task",entityId:l.id,count:((w=s.snapshot.dashboard.notesSummaryByEntity[`task:${l.id}`])==null?void 0:w.count)??0}):null]}),e.jsx("div",{className:"mt-3 text-base font-semibold text-white",children:(l==null?void 0:l.title)??"Pick a task from the runway"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(l==null?void 0:l.description)??"Once a task is active, the timer rail and this panel stay aligned."}),l?e.jsx("button",{type:"button",className:"mt-4 inline-flex min-h-10 items-center justify-center rounded-2xl bg-[rgba(192,193,255,0.16)] px-3.5 py-2 text-sm font-medium text-[var(--primary)] transition hover:bg-[rgba(192,193,255,0.24)]",onClick:async()=>{await s.startTaskNow(l.id)},children:"Start work"}):null]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Recovery task"}),e.jsx("div",{className:"mt-3 text-sm font-semibold text-white",children:(c==null?void 0:c.title)??"No blocked or overdue task is dominating today"}),b?null:e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:(c==null?void 0:c.description)??"If something slips, it will surface here as the clean comeback move."})]}),e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Due habits"}),e.jsx("div",{className:"mt-3 grid gap-2",children:s.snapshot.today.dueHabits.slice(0,b?2:3).map(M=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-3 py-2.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white",children:M.title}),b?null:e.jsx("div",{className:"text-sm text-white/52",children:M.frequency})]}),e.jsxs(L,{className:"bg-[rgba(78,222,163,0.14)] text-[var(--secondary)]",children:[M.rewardXp," xp"]})]},M.id))})]})]})]})}},{id:"time",title:"Clock",description:"Optional utility widget.",defaultWidth:3,defaultHeight:2,defaultHidden:!0,render:({compact:b})=>e.jsx(ro,{compact:b})},{id:"weather",title:"Weather",description:"Optional utility widget.",defaultWidth:3,defaultHeight:2,defaultHidden:!0,render:({compact:b})=>e.jsx(co,{compact:b})},{id:"mini-calendar",title:"Mini calendar",description:"Optional utility widget.",defaultWidth:4,defaultHeight:3,defaultHidden:!0,render:({compact:b})=>e.jsx(lo,{compact:b})},{id:"spotify",title:"Spotify",description:"Optional utility widget.",defaultWidth:4,defaultHeight:2,defaultHidden:!0,render:()=>e.jsx(oo,{surfaceId:"today"})},{id:"quick-capture",title:"Quick capture",description:"Save a note or wiki draft without leaving Today.",defaultWidth:5,defaultHeight:3,defaultHidden:!0,render:({compact:b})=>{var w;return e.jsx(ho,{compact:b,defaultUserId:s.selectedUserIds[0]??((w=s.snapshot.users[0])==null?void 0:w.id)??null})}}];return e.jsx(_a,{surfaceId:"today",baseWidgets:h})}function SN(t){const s=[];let i,a;for(const n of t){const r=n.trim();if(!r)continue;const l=r.indexOf(":");if(l<=0){s.push({label:"Note",value:r});continue}const o=r.slice(0,l).trim(),c=r.slice(l+1).trim();if(!c)continue;const x=o.toLowerCase();if(x==="title"){i=c;continue}if(x==="summary"){a=c;continue}s.push({label:o,value:c})}return{title:i,summary:a,rows:s}}function CN(t){const s=[],i=/(!?\[\[([^\]]+)\]\]|\[([^\]]+)\]\(([^)]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|\*([^*]+)\*)/g;let a=0,n=null;for(;(n=i.exec(t))!==null;){if(n.index>a&&s.push({type:"text",value:t.slice(a,n.index)}),n[1]&&n[2]){const r=n[2].trim(),l=n[1].startsWith("!"),o=r.indexOf("|"),c=o>=0?r.slice(0,o).trim():r,x=o>=0?r.slice(o+1).trim():c;if(c.toLowerCase().startsWith("forge:")){const[,v,...u]=c.split(":");s.push({type:"forge-link",entityType:v??"",entityId:u.join(":").trim(),label:x})}else s.push({type:"wiki-link",target:c,label:x,embed:l})}else n[3]&&n[4]?s.push({type:"link",label:n[3],href:n[4].trim()}):n[5]?s.push({type:"code",value:n[5]}):n[6]?s.push({type:"strong",value:n[6]}):n[7]&&s.push({type:"em",value:n[7]});a=i.lastIndex}return a<t.length&&s.push({type:"text",value:t.slice(a)}),s}function IN(t){const s=t.replace(/\r/g,"").split(`
|
|
39
|
-
`),i=[],a=[];let n=null,r=0;for(;r<s.length;){const l=s[r]??"",o=l.trim();if(!o){r+=1;continue}if(o.startsWith("```")){const u=[];for(r+=1;r<s.length&&!(s[r]??"").trim().startsWith("```");)u.push(s[r]??""),r+=1;r+=1,i.push({type:"code",code:u.join(`
|
|
40
|
-
`)});continue}const c=o.match(/^:::([a-z0-9-]+)\s*$/i);if(c){const u=c[1].toLowerCase(),f=[];for(r+=1;r<s.length&&(s[r]??"").trim()!==":::";)f.push(s[r]??""),r+=1;r<s.length&&(r+=1);const h=[`:::${u}`,...f,":::"].join(`
|
|
41
|
-
`);a.push({kind:u,lines:f,raw:h}),u==="forge-infobox"?n=SN(f):u==="note"||u==="tip"||u==="warning"||u==="danger"?i.push({type:"admonition",kind:u,lines:f}):(u==="forge-links"||u==="forge-media"||u==="forge-related")&&i.push({type:u,lines:f});continue}const x=l.match(/^(#{1,6})\s+(.*)$/);if(x){i.push({type:"heading",level:x[1].length,text:x[2].trim()}),r+=1;continue}if(/^>\s?/.test(l)){const u=[];for(;r<s.length&&/^>\s?/.test(s[r]??"");)u.push((s[r]??"").replace(/^>\s?/,"")),r+=1;i.push({type:"quote",text:u.join(" ").trim()});continue}if(/^[-*+]\s+/.test(l)||/^\d+\.\s+/.test(l)){const u=/^\d+\.\s+/.test(l),f=[];for(;r<s.length&&(/^[-*+]\s+/.test(s[r]??"")||/^\d+\.\s+/.test(s[r]??""));)f.push((s[r]??"").replace(/^[-*+]\s+/,"").replace(/^\d+\.\s+/,"").trim()),r+=1;i.push({type:"list",ordered:u,items:f});continue}const v=[];for(;r<s.length;){const u=s[r]??"",f=u.trim();if(!f||f.startsWith("```")||f.startsWith(":::")||/^#{1,6}\s+/.test(u)||/^>\s?/.test(u)||/^[-*+]\s+/.test(u)||/^\d+\.\s+/.test(u))break;v.push(f),r+=1}if(v.length>0){i.push({type:"paragraph",text:v.join(" ")});continue}r+=1}return{blocks:i,infobox:n,directives:a}}function TN(t,s,i){return t.map((a,n)=>{const r=`${s}-${n}`;switch(a.type){case"text":return e.jsx(d.Fragment,{children:a.value},r);case"code":return e.jsx("code",{className:"rounded bg-black/10 px-1.5 py-0.5 font-mono text-[0.92em] text-white",children:a.value},r);case"strong":return e.jsx("strong",{className:"font-semibold text-white",children:a.value},r);case"em":return e.jsx("em",{className:"italic text-white/82",children:a.value},r);case"link":{const l=/^https?:\/\//i.test(a.href);return e.jsx("a",{href:a.href,target:l?"_blank":void 0,rel:l?"noreferrer":void 0,className:"text-[var(--secondary)] underline decoration-current/30 underline-offset-2 transition hover:text-white",children:a.label},r)}case"forge-link":{const l=Xs(a.entityType,a.entityId),o=l?ui(l):null;return o?e.jsx("a",{href:o,className:"rounded-sm bg-white/[0.08] px-1.5 py-0.5 text-white no-underline ring-1 ring-black/5 transition hover:bg-white/[0.12]",children:a.label},r):e.jsx("span",{className:"rounded-sm bg-white/[0.08] px-1.5 py-0.5 text-white/64",children:a.label},r)}case"wiki-link":return e.jsx(Ae,{to:{pathname:`/wiki/page/${encodeURIComponent(a.target)}`,search:i?`?spaceId=${encodeURIComponent(i)}`:""},className:re("underline decoration-current/30 underline-offset-2 transition hover:text-white",a.embed?"text-[var(--primary)]":"text-[var(--secondary)]"),children:a.label},r)}})}function Bs(t,s,i){return TN(CN(t),s,i)}function PN(t,s){const i=t.map(a=>a.trim()).filter(Boolean);return i.length===0?null:e.jsx("ul",{className:"space-y-1.5 pl-4 text-[13px] leading-6 text-white/76",children:i.map((a,n)=>e.jsx("li",{children:Bs(a,`directive-${n}`,s)},`${a}-${n}`))})}function Wc(t,s,i){switch(t.type){case"heading":{const a=t.level===1?"text-[1.9rem] leading-[1.08]":t.level===2?"text-[1.25rem] leading-[1.2]":t.level===3?"text-[1.05rem] leading-[1.3]":"text-[0.92rem] leading-[1.35]";return e.jsx("h2",{className:re("font-semibold tracking-[-0.02em] text-white",s>0&&"mt-6",a),children:Bs(t.text,`heading-${s}`,i)},`heading-${s}`)}case"paragraph":return e.jsx("p",{className:"text-[14px] leading-7 text-white/78",children:Bs(t.text,`paragraph-${s}`,i)},`paragraph-${s}`);case"quote":return e.jsx("blockquote",{className:"border-l-[3px] border-white/16 pl-4 text-[14px] leading-7 text-white/62",children:Bs(t.text,`quote-${s}`,i)},`quote-${s}`);case"list":{const a=t.ordered?"ol":"ul";return e.jsx(a,{className:re("space-y-1.5 pl-5 text-[14px] leading-7 text-white/78",t.ordered?"list-decimal":"list-disc"),children:t.items.map((n,r)=>e.jsx("li",{children:Bs(n,`list-${s}-${r}`,i)},`item-${s}-${r}`))},`list-${s}`)}case"code":return e.jsx("pre",{className:"overflow-x-auto rounded-xl bg-[rgba(10,16,30,0.9)] px-4 py-3 text-[12px] leading-6 text-white ring-1 ring-black/5",children:e.jsx("code",{children:t.code})},`code-${s}`);case"admonition":return e.jsxs("aside",{className:re("rounded-xl border px-4 py-3",t.kind==="warning"||t.kind==="danger"?"border-amber-500/25 bg-amber-500/8":"border-white/12 bg-white/[0.04]"),children:[e.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-white/48",children:t.kind}),e.jsx("div",{className:"grid gap-2 text-[13px] leading-6 text-white/76",children:t.lines.map((a,n)=>e.jsx("p",{children:Bs(a,`admonition-${s}-${n}`,i)},`admonition-line-${n}`))})]},`admonition-${s}`);case"forge-links":case"forge-media":case"forge-related":return e.jsxs("section",{className:"rounded-xl border border-white/10 bg-white/[0.03] px-4 py-3",children:[e.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-white/48",children:t.type.replace("forge-","")}),PN(t.lines,i)]},`${t.type}-${s}`)}}function MN(t,s,i){return e.jsx("div",{className:"text-[13px] leading-6 text-white/76",children:Bs(t,s,i)})}function AN({infobox:t,spaceId:s,className:i}){return e.jsxs("aside",{className:re("wiki-infobox rounded-2xl border border-white/10 bg-white/[0.03] p-4",i),children:[t.title?e.jsx("div",{className:"text-[1rem] font-semibold leading-tight text-white",children:t.title}):null,t.summary?e.jsx("p",{className:"mt-2 text-[13px] leading-6 text-white/60",children:Bs(t.summary,"infobox-summary",s)}):null,e.jsx("dl",{className:"mt-3 grid gap-2",children:t.rows.map((a,n)=>e.jsxs("div",{className:"grid gap-1 border-t border-white/10 pt-2 first:border-t-0 first:pt-0",children:[e.jsx("dt",{className:"text-[10px] font-semibold uppercase tracking-[0.16em] text-white/48",children:a.label}),e.jsx("dd",{children:MN(a.value,`infobox-row-${n}`,s)})]},`${a.label}-${n}`))})]})}function EN(t){const s=[],i=[];let a=!1;for(const n of t)!a&&n.type==="heading"&&n.level<=2&&s.length>0&&(a=!0),a?i.push(n):s.push(n);return{intro:s.length>0?s:t.slice(0,1),rest:s.length>0?i:t.slice(1)}}function yu({markdown:t,spaceId:s,className:i}){const a=IN(t),{intro:n,rest:r}=EN(a.blocks);return e.jsxs("div",{className:re("grid gap-4",i),children:[e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1fr)_19rem] xl:items-start",children:[e.jsx("div",{className:"grid gap-4",children:n.map((l,o)=>Wc(l,o,s))}),a.infobox?e.jsx(AN,{infobox:a.infobox,spaceId:s,className:"order-2 xl:order-none"}):null]}),r.length>0?e.jsx("div",{className:"grid gap-4",children:r.map((l,o)=>Wc(l,o+n.length,s))}):null]})}const Ei=new Set(["queued","processing"]),Hc=15e3,LN=["goal","project","task","habit","strategy","psyche_value","note"];function Gc(t){return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(t))}function Us(t,s){const i=t[s];return typeof i=="number"&&Number.isFinite(i)?i:null}function Zt(t,s){const i=t[s];return typeof i=="string"&&i.trim().length>0?i:null}function DN(t,s){const i=Zt(t.metadata,"currentFileName")??Zt(t.metadata,"fileName")??"current source",a=Zt(t.metadata,"status")??"in_progress",n=Us(t.metadata,"chunkIndex"),r=Us(t.metadata,"chunkCount"),l=Us(t.metadata,"currentFileIndex"),o=Us(t.metadata,"currentFileTotal"),c=l!==null&&o!==null?`${i} (${l}/${o})`:i,x=n!==null&&r!==null&&r>1?` · chunk ${n}/${r}`:"";return`Waiting for OpenAI on ${c}${x}. ${s} polls · ${a}.`}function $N(t){const s=[];for(const i of t){const a=Zt(i.metadata,"scope"),r=Zt(i.metadata,"eventKey")==="llm_compile_background_polled",l=Zt(i.metadata,"currentFileName")??Zt(i.metadata,"fileName"),o=Us(i.metadata,"chunkIndex"),c=Us(i.metadata,"chunkCount"),x=r?["poll",a??"",l??"",o??"",c??""].join(":"):null,v=s[s.length-1],u=v&&Zt(v.metadata,"eventKey"),f=v&&(Zt(v.metadata,"currentFileName")??Zt(v.metadata,"fileName")),h=v&&Us(v.metadata,"chunkIndex"),m=v&&Us(v.metadata,"chunkCount"),b=v&&u==="llm_compile_background_polled"?["poll",Zt(v.metadata,"scope")??"",f??"",h??"",m??""].join(":"):null;if(r&&v&&b===x){s[s.length-1]={...i,repetitionCount:v.repetitionCount+1,metadata:{...i.metadata,aggregatedPollCount:v.repetitionCount+1}};continue}s.push({...i,repetitionCount:1})}return s}function on(t){switch(t){case"goal":case"project":case"task":case"habit":case"strategy":return t;case"psyche_value":return"value";default:return null}}function Xc(t){return typeof t=="string"&&LN.includes(t)}function ON(t,s){return typeof s.title=="string"&&s.title.trim().length>0?s.title:typeof s.displayName=="string"&&s.displayName.trim().length>0?s.displayName:typeof s.statement=="string"&&s.statement.trim().length>0?s.statement:`${t}:${String(s.id??"")}`}function FN(t,s){const a=[s.description,s.summary,s.overview,s.valuedDirection,s.whyItMatters,s.originNote].find(n=>typeof n=="string"&&n.trim().length>0);return a||(t==="note"&&typeof s.kind=="string"?s.kind:"")}function _N({candidate:t,decision:s,onDecisionChange:i,spaceId:a}){const n=Xc(t.payload.entityType)?t.payload.entityType:null,[r,l]=d.useState(s.mappedEntityLabel||t.title||""),[o,c]=d.useState(s.targetNoteLabel||t.title||""),x=typeof t.payload.contentMarkdown=="string"?t.payload.contentMarkdown:typeof t.payload.patchSummary=="string"?t.payload.patchSummary:typeof t.payload.rationale=="string"?t.payload.rationale:t.summary,v=fe({queryKey:["forge-wiki-ingest-map-search",n,r.trim()],enabled:t.candidateType==="entity"&&s.action==="map_existing"&&n!==null&&r.trim().length>0,queryFn:async()=>{var E;const M=(await Uh({searches:[{entityTypes:n?[n]:void 0,query:r.trim(),limit:8}]})).results[0];return((E=M==null?void 0:M.matches)==null?void 0:E.filter(D=>!!(D&&Xc(D.entityType)&&typeof D.id=="string"&&D.entity&&typeof D.entity=="object")).map(D=>({entityType:D.entityType,entityId:D.id,label:ON(D.entityType,D.entity),description:FN(D.entityType,D.entity),kind:on(D.entityType)})))??[]}}),u=v.data??[],f=fe({queryKey:["forge-wiki-ingest-merge-search",a,o.trim()],enabled:t.candidateType==="page"&&s.action==="merge_existing"&&o.trim().length>0,queryFn:async()=>(await Og({spaceId:a,kind:"wiki",mode:"text",query:o.trim(),limit:8})).results.map(M=>({noteId:M.page.id,title:M.page.title,slug:M.page.slug,summary:M.page.summary}))}),h=f.data??[],m=s.mappedEntityId&&s.mappedEntityType?u.find(w=>w.entityId===s.mappedEntityId&&w.entityType===s.mappedEntityType)??(s.mappedEntityLabel?{entityId:s.mappedEntityId,entityType:s.mappedEntityType,label:s.mappedEntityLabel,kind:on(s.mappedEntityType)}:null):null,b=s.targetNoteId?h.find(w=>w.noteId===s.targetNoteId)??(s.targetNoteLabel?{noteId:s.targetNoteId,title:s.targetNoteLabel}:null):null;return e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/40",children:t.candidateType.replaceAll("_"," ")}),e.jsx("div",{className:"mt-2 text-base font-semibold text-white",children:t.title||t.targetKey||"Untitled candidate"}),n?e.jsx("div",{className:"mt-2",children:on(n)?e.jsx(Te,{kind:on(n),label:n.replaceAll("_"," "),compact:!0,gradient:!1}):e.jsx(L,{className:"bg-white/[0.08] text-white/72",children:n.replaceAll("_"," ")})}):null,t.summary?e.jsx("div",{className:"mt-1 text-sm leading-6 text-white/58",children:t.summary}):null]}),e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.03] p-1",children:[e.jsx("button",{type:"button",className:re("rounded-full px-3 py-1.5 text-xs font-medium transition",s.action==="keep"?"bg-[rgba(192,193,255,0.2)] text-white":"text-white/54 hover:text-white"),onClick:()=>i({...s,action:"keep"}),children:"Keep"}),t.candidateType==="entity"&&n?e.jsx("button",{type:"button",className:re("rounded-full px-3 py-1.5 text-xs font-medium transition",s.action==="map_existing"?"bg-[rgba(133,222,255,0.18)] text-white":"text-white/54 hover:text-white"),onClick:()=>i({...s,action:"map_existing",mappedEntityType:n}),children:"Map existing"}):null,t.candidateType==="page"?e.jsx("button",{type:"button",className:re("rounded-full px-3 py-1.5 text-xs font-medium transition",s.action==="merge_existing"?"bg-[rgba(133,222,255,0.18)] text-white":"text-white/54 hover:text-white"),onClick:()=>i({...s,action:"merge_existing"}),children:"Merge existing"}):null,e.jsx("button",{type:"button",className:re("rounded-full px-3 py-1.5 text-xs font-medium transition",s.action==="discard"?"bg-[rgba(255,255,255,0.12)] text-white":"text-white/54 hover:text-white"),onClick:()=>i({...s,action:"discard"}),children:"Discard"})]})]}),t.candidateType==="entity"&&n&&s.action==="map_existing"?e.jsxs("div",{className:"mt-4 grid gap-3 rounded-[18px] border border-white/8 bg-[rgba(6,10,20,0.55)] p-4",children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:["Map to existing ",n.replaceAll("_"," ")]}),m?e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-white/8 bg-white/[0.06] px-2.5 py-1.5",children:[m.kind?e.jsx(Te,{kind:m.kind,label:m.label,compact:!0,gradient:!1,className:"max-w-[20rem]"}):e.jsx(L,{className:"bg-white/[0.08] text-white/78",children:m.label}),e.jsx("button",{type:"button",className:"rounded-full text-white/50 transition hover:text-white",onClick:()=>i({...s,mappedEntityId:void 0,mappedEntityLabel:void 0}),"aria-label":"Clear mapped entity",children:e.jsx(mt,{className:"size-3.5"})})]})}):null,e.jsxs("div",{className:"flex items-center gap-3 rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[e.jsx(bt,{className:"size-4 text-white/34"}),e.jsx("input",{value:r,onChange:w=>{l(w.target.value),s.mappedEntityId&&i({...s,mappedEntityId:void 0,mappedEntityLabel:void 0})},placeholder:`Search existing ${n.replaceAll("_"," ")}`,className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]}),e.jsx("div",{className:"grid gap-2",children:v.isPending?e.jsx("div",{className:"rounded-[16px] border border-white/8 bg-white/[0.03] px-3 py-3 text-sm text-white/48",children:"Searching Forge…"}):u.length===0?e.jsxs("div",{className:"rounded-[16px] border border-dashed border-white/10 px-3 py-3 text-sm text-white/42",children:["No existing ",n.replaceAll("_"," ")," matches yet."]}):u.map(w=>{const M=s.mappedEntityType===w.entityType&&s.mappedEntityId===w.entityId;return e.jsx("button",{type:"button",className:re("flex w-full items-start justify-between gap-3 rounded-[18px] border px-3 py-3 text-left transition",M?"border-[rgba(133,222,255,0.24)] bg-[rgba(133,222,255,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/72 hover:bg-white/[0.06] hover:text-white"),onClick:()=>i({action:"map_existing",mappedEntityType:w.entityType,mappedEntityId:w.entityId,mappedEntityLabel:w.label}),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:w.kind?e.jsx(Te,{kind:w.kind,label:w.label,compact:!0,gradient:!1}):w.label}),w.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/46",children:w.description}):null]})},`${w.entityType}:${w.entityId}`)})})]}):null,t.candidateType==="page"&&s.action==="merge_existing"?e.jsxs("div",{className:"mt-4 grid gap-3 rounded-[18px] border border-white/8 bg-[rgba(6,10,20,0.55)] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Merge into existing page"}),b?e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-white/8 bg-white/[0.06] px-2.5 py-1.5",children:[e.jsx(L,{className:"bg-white/[0.08] text-white/78",children:b.title}),e.jsx("button",{type:"button",className:"rounded-full text-white/50 transition hover:text-white",onClick:()=>i({...s,targetNoteId:void 0,targetNoteLabel:void 0}),"aria-label":"Clear merge target",children:e.jsx(mt,{className:"size-3.5"})})]})}):null,e.jsxs("div",{className:"flex items-center gap-3 rounded-[20px] border border-white/8 bg-white/[0.04] px-4 py-3",children:[e.jsx(bt,{className:"size-4 text-white/34"}),e.jsx("input",{value:o,onChange:w=>{c(w.target.value),s.targetNoteId&&i({...s,targetNoteId:void 0,targetNoteLabel:void 0})},placeholder:"Search existing wiki pages",className:"min-w-0 flex-1 bg-transparent text-sm text-white placeholder:text-white/34 focus:outline-none"})]}),e.jsx("div",{className:"grid gap-2",children:f.isPending?e.jsx("div",{className:"rounded-[16px] border border-white/8 bg-white/[0.03] px-3 py-3 text-sm text-white/48",children:"Searching Forge…"}):h.length===0?e.jsx("div",{className:"rounded-[16px] border border-dashed border-white/10 px-3 py-3 text-sm text-white/42",children:"No existing wiki pages match yet."}):h.map(w=>{const M=s.targetNoteId===w.noteId;return e.jsx("button",{type:"button",className:re("flex w-full items-start justify-between gap-3 rounded-[18px] border px-3 py-3 text-left transition",M?"border-[rgba(133,222,255,0.24)] bg-[rgba(133,222,255,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/72 hover:bg-white/[0.06] hover:text-white"),onClick:()=>i({action:"merge_existing",targetNoteId:w.noteId,targetNoteLabel:w.title}),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:w.title}),e.jsxs("div",{className:"mt-1 text-xs leading-5 text-white/46",children:[w.slug?`${w.slug}`:"",w.summary?`${w.slug?" · ":""}${w.summary}`:""]})]})},w.noteId)})})]}):null,x?e.jsx("div",{className:"mt-4 rounded-[18px] border border-white/8 bg-[rgba(6,10,20,0.65)] px-4 py-3 text-sm leading-6 text-white/72",children:e.jsx("pre",{className:"whitespace-pre-wrap font-sans",children:x})}):null]})}function ju({open:t,onOpenChange:s,spaces:i,llmProfiles:a,initialSpaceId:n,selectedJobId:r,onJobSelected:l,linkedEntityHints:o=[]}){var pe;const c=ut(),x=We(),[v,u]=d.useState("files"),[f,h]=d.useState(n),[m,b]=d.useState(""),[w,M]=d.useState(""),[E,D]=d.useState(""),[j,S]=d.useState([]),[p,A]=d.useState(!1),[T,k]=d.useState(!1),$=d.useMemo(()=>a.filter(ee=>ee.enabled&&!!ee.secretId),[a]),[g,C]=d.useState(((pe=$[0])==null?void 0:pe.id)??""),[F,z]=d.useState("auto"),[J,O]=d.useState({}),[_,B]=d.useState(null),[K,Z]=d.useState(null),U=d.useRef({});d.useEffect(()=>{n&&h(n)},[n]),d.useEffect(()=>{var ee;!g&&((ee=$[0])!=null&&ee.id)&&C($[0].id)},[g,$]);const I=$.find(ee=>ee.id===g)??$[0]??null,G=fe({queryKey:["forge-wiki-ingest-job",r],queryFn:()=>$g(r),enabled:t&&!!r,refetchInterval:ee=>{const Y=ee.state.data;return Y&&Ei.has(Y.job.status)?2e3:!1}});d.useEffect(()=>{const ee=G.data;ee&&O(Y=>{const R={};for(const X of ee.candidates)R[X.id]=Y[X.id]??(X.status==="rejected"?{action:"discard"}:{action:"keep"});return R})},[G.data]),d.useEffect(()=>{K&&Z(null)},[J,K]);const W=xe({mutationFn:async ee=>_g(ee),onSuccess:(ee,Y)=>{ee.job&&x.setQueryData(["forge-wiki-ingest-job",Y],ee.job),x.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),x.invalidateQueries({queryKey:["forge-wiki-ingest-history"]})}});d.useEffect(()=>{const ee=G.data;if(!ee||!Ei.has(ee.job.status))return;const Y=ee.logs.reduce((ce,Se)=>{const he=Number(new Date(Se.createdAt));return Number.isFinite(he)?Math.max(ce,he):ce},0),R=Number(new Date(ee.job.updatedAt)),X=Math.max(Number.isFinite(R)?R:0,Y);if(!Number.isFinite(X)||X<=0)return;const be=Date.now();if(!(be-X>=Hc)||W.isPending)return;const te=U.current[ee.job.id]??0;be-te<Hc||(U.current[ee.job.id]=be,W.mutate(ee.job.id))},[G.data,W]);const ne=xe({mutationFn:async()=>{if(!I)throw new Error("Set up an OpenAI wiki ingest profile first. Forge now requires an LLM profile before auto-ingest can turn source material into draft pages and entities.");if(v==="files"){if(j.length===0)throw new Error("Select at least one file to ingest.");return Dg({files:j,spaceId:f||void 0,titleHint:m.trim()||void 0,llmProfileId:I.id,parseStrategy:F,createAsKind:"wiki",linkedEntityHints:o})}if(v==="url"){if(!w.trim())throw new Error("Enter a URL to ingest.");return ed({spaceId:f||void 0,titleHint:m.trim()||void 0,sourceKind:"url",sourceUrl:w.trim(),llmProfileId:I.id,parseStrategy:F,createAsKind:"wiki",linkedEntityHints:o})}if(!E.trim())throw new Error("Paste some text to ingest.");return ed({spaceId:f||void 0,titleHint:m.trim()||void 0,sourceKind:"raw_text",sourceText:E,mimeType:"text/plain",llmProfileId:I.id,parseStrategy:F,createAsKind:"wiki",linkedEntityHints:o})},onSuccess:async ee=>{var R;const Y=((R=ee.job)==null?void 0:R.job.id)??null;await x.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),await x.invalidateQueries({queryKey:["forge-wiki-ingest-history"]}),Y&&l(Y),B(null),Z(null)},onError:ee=>{B(ee instanceof Error?ee.message:"Unable to start ingest.")}}),de=xe({mutationFn:async()=>{if(!r||!G.data)throw new Error("Choose an ingest job first.");const ee=G.data.candidates.map(Y=>{const R=J[Y.id]??{action:"keep"};if(R.action==="map_existing"&&(!R.mappedEntityType||!R.mappedEntityId))throw new Error(`Choose an existing ${String(Y.payload.entityType??"entity").replaceAll("_"," ")} before publishing the review.`);if(R.action==="merge_existing"&&!R.targetNoteId)throw new Error(`Choose an existing wiki page before publishing the review for ${Y.title||"this page candidate"}.`);return R.action==="map_existing"?{candidateId:Y.id,action:"map_existing",mappedEntityType:R.mappedEntityType,mappedEntityId:R.mappedEntityId}:R.action==="merge_existing"?{candidateId:Y.id,action:"merge_existing",targetNoteId:R.targetNoteId}:{candidateId:Y.id,action:R.action}});return Rg({jobId:r,decisions:ee})},onSuccess:async ee=>{Z(null),x.setQueryData(["forge-wiki-ingest-job",ee.job.job.id],ee.job),await Promise.all([x.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),x.invalidateQueries({queryKey:["forge-wiki-ingest-history"]}),x.invalidateQueries({queryKey:["forge-wiki-ingest-job",ee.job.job.id]}),x.invalidateQueries({queryKey:["forge-wiki-home"]}),x.invalidateQueries({queryKey:["forge-wiki-page-by-slug"]}),x.invalidateQueries({queryKey:["forge-wiki-tree"]})])},onError:ee=>{Z(ee instanceof Error?ee.message:"Unable to publish review.")}}),we=xe({mutationFn:async()=>{if(!r)throw new Error("Choose an ingest job first.");return Fg(r)},onSuccess:async ee=>{var R;const Y=((R=ee.job)==null?void 0:R.job.id)??null;await Promise.all([x.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),x.invalidateQueries({queryKey:["forge-wiki-ingest-history"]}),x.invalidateQueries({queryKey:["forge-wiki-ingest-job",r]})]),Y&&l(Y),B(null),Z(null)},onError:ee=>{B(ee instanceof Error?ee.message:"Unable to rerun ingest.")}}),Ne=xe({mutationFn:async()=>{if(!r)throw new Error("Choose an ingest job first.");return Rh(r)},onSuccess:async()=>{await Promise.all([x.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),x.invalidateQueries({queryKey:["forge-wiki-ingest-history"]}),x.invalidateQueries({queryKey:["forge-wiki-ingest-job",r]})]),q(),B(null),Z(null)},onError:ee=>{B(ee instanceof Error?ee.message:"Unable to delete ingest.")}}),H=G.data??null,me=H&&!Ei.has(H.job.status),y=d.useMemo(()=>(H==null?void 0:H.candidates.filter(ee=>["suggested","rejected","failed"].includes(ee.status)))??[],[H]),P=d.useMemo(()=>$N((H==null?void 0:H.logs)??[]),[H==null?void 0:H.logs]),q=()=>{l(null),S([]),M(""),D(""),b(""),B(null),Z(null)};return e.jsx(Et,{open:t,onOpenChange:ee=>{s(ee),ee||(B(null),Z(null))},children:e.jsxs(Lt,{children:[e.jsx(Dt,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.78)] backdrop-blur-sm"}),e.jsxs($t,{className:"fixed inset-x-4 bottom-4 top-4 z-50 mx-auto flex max-w-[min(74rem,calc(100vw-2rem))] flex-col overflow-hidden rounded-[32px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,27,42,0.98),rgba(10,15,28,0.98))] shadow-[0_36px_110px_rgba(3,8,18,0.48)]",children:[e.jsx("div",{className:"border-b border-white/8 px-5 py-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Wiki Ingest"}),e.jsx(Ot,{className:"mt-2 font-display text-[1.5rem] tracking-[-0.04em] text-white",children:H?"Ingest review and progress":"Build wiki memory from source files"}),e.jsx(qt,{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:"Upload notes, media, ZIP archives, links, or pasted text. Forge will process them in the background, propose pages and entities, and let you keep only what belongs."})]}),e.jsx(Ft,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white","aria-label":"Close ingest modal",children:e.jsx(mt,{className:"size-4"})})})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto px-5 py-5",children:H?e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-white/[0.04] p-4 sm:p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:["Job ",H.job.id]}),e.jsx("div",{className:"mt-2 text-xl font-semibold text-white",children:H.job.latestMessage||"Ingest job"}),e.jsxs("div",{className:"mt-2 text-sm leading-6 text-white/56",children:[H.job.status," · ",H.job.phase," · started ",Gc(H.job.createdAt)]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Q,{variant:"secondary",size:"sm",onClick:q,children:"New ingest"}),me?e.jsxs(e.Fragment,{children:[e.jsxs(Q,{variant:"secondary",size:"sm",pending:we.isPending,pendingLabel:"Rerunning",onClick:()=>void we.mutateAsync(),children:[e.jsx(Tt,{className:"size-3.5"}),"Rerun"]}),e.jsx(Q,{variant:"ghost",size:"sm",className:"border border-rose-300/18 bg-rose-400/10 text-rose-100 hover:bg-rose-400/16",pending:Ne.isPending,pendingLabel:"Deleting",onClick:()=>{window.confirm("Delete this ingest history entry? Published pages or entities will stay, but discarded or unreviewed ingest data will be removed.")&&Ne.mutateAsync()},children:"Delete"})]}):null]})]}),e.jsx("div",{className:"mt-5 grid gap-3 sm:grid-cols-4",children:[{label:"Progress",value:`${H.job.progressPercent}%`},{label:"Files",value:`${H.job.processedFiles}/${H.job.totalFiles}`},{label:"Pages",value:String(H.job.createdPageCount)},{label:"Entities",value:String(H.job.createdEntityCount)}].map(ee=>e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-[rgba(8,12,22,0.68)] px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:ee.label}),e.jsx("div",{className:"mt-2 text-lg font-semibold text-white",children:ee.value})]},ee.label))}),e.jsx("div",{className:"mt-5",children:e.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-white/[0.06]",children:e.jsx("div",{className:"h-full rounded-full bg-[linear-gradient(90deg,rgba(192,193,255,0.8),rgba(133,222,255,0.8))] transition-all duration-300",style:{width:`${H.job.progressPercent}%`}})})}),_?e.jsx("div",{className:"mt-4 rounded-[20px] border border-rose-300/22 bg-rose-400/10 px-4 py-3 text-sm text-rose-100",children:_}):null]}),e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-white/[0.04] p-4 sm:p-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Rich log"}),e.jsx(Q,{variant:"secondary",size:"sm",onClick:()=>c(`/settings/logs?jobId=${encodeURIComponent(H.job.id)}`),children:"Open full logs"})]}),e.jsx("div",{className:"mt-4 grid max-h-[28rem] gap-2 overflow-y-auto",children:P.length===0?e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 px-4 py-4 text-sm text-white/45",children:"Waiting for the backend to emit progress."}):P.map(ee=>e.jsx("div",{className:"rounded-[18px] border border-white/8 bg-[rgba(7,11,21,0.72)] px-4 py-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-white/55",children:ee.level}),typeof ee.metadata.scope=="string"?e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-white/38",children:ee.metadata.scope}):null,typeof ee.metadata.eventKey=="string"?e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-white/38",children:ee.metadata.eventKey}):null]}),e.jsx("div",{className:"mt-2 text-sm text-white/82",children:Zt(ee.metadata,"eventKey")==="llm_compile_background_polled"?DN(ee,ee.repetitionCount):ee.message}),ee.repetitionCount>1?e.jsxs("div",{className:"mt-2 text-xs text-white/44",children:["Combined ",ee.repetitionCount," repeated polling updates."]}):null,Object.keys(ee.metadata).length>0?e.jsxs("details",{className:"mt-3",children:[e.jsx("summary",{className:"cursor-pointer text-xs text-white/45",children:"View metadata"}),e.jsx("pre",{className:"mt-2 overflow-x-auto whitespace-pre-wrap rounded-[14px] border border-white/8 bg-black/20 px-3 py-3 text-[11px] leading-5 text-white/52",children:JSON.stringify(ee.metadata,null,2)})]}):null]}),e.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-white/38",children:Gc(ee.createdAt)})]})},ee.id))})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-white/[0.04] p-4 sm:p-5",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Source files"}),e.jsx("div",{className:"mt-4 grid gap-2",children:H.assets.map(ee=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[18px] border border-white/8 bg-[rgba(7,11,21,0.72)] px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white",children:ee.fileName||ee.sourceLocator||"Source"}),e.jsx("div",{className:"mt-1 text-xs text-white/45",children:ee.mimeType||ee.sourceKind})]}),e.jsx("div",{className:"shrink-0 text-[11px] uppercase tracking-[0.14em] text-white/40",children:ee.status})]},ee.id))})]}),e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-white/[0.04] p-4 sm:p-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Review"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Keep the candidates that belong in Forge and discard the rest."})]}),Ei.has(H.job.status)?e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-xs text-white/58",children:[e.jsx(_n,{className:"size-3.5 animate-spin"}),"Processing"]}):null]}),e.jsx("div",{className:"mt-4 grid gap-3",children:y.length===0?e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 px-4 py-4 text-sm text-white/45",children:Ei.has(H.job.status)?"Candidates will appear here while the job progresses.":"This job has no reviewable candidates left."}):y.map(ee=>e.jsx(_N,{candidate:ee,spaceId:H.job.spaceId,decision:J[ee.id]??{action:"keep"},onDecisionChange:Y=>O(R=>({...R,[ee.id]:Y}))},ee.id))}),K?e.jsx("div",{className:"mt-4 rounded-[20px] border border-rose-300/22 bg-rose-400/10 px-4 py-3 text-sm text-rose-100",children:K}):null,y.length>0&&!Ei.has(H.job.status)?e.jsx("div",{className:"mt-5",children:e.jsxs(Q,{className:"min-h-12",pending:de.isPending,pendingLabel:"Publishing review",onClick:()=>void de.mutateAsync(),children:[e.jsx(Wo,{className:"size-4"}),"Publish kept candidates"]})}):null]})]})]}):e.jsxs("div",{className:"grid gap-5 lg:grid-cols-[minmax(0,1.15fr)_minmax(18rem,0.85fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:[{id:"files",label:"Files and ZIP",detail:"Drag many files or one archive.",icon:lr},{id:"url",label:"URL",detail:"Pull a webpage or remote file.",icon:Hp},{id:"text",label:"Paste text",detail:"Turn notes or transcripts into pages.",icon:xl}].map(ee=>{const Y=ee.icon,R=ee.id===v;return e.jsxs("button",{type:"button",className:re("rounded-[24px] border px-4 py-4 text-left transition",R?"border-[rgba(192,193,255,0.24)] bg-[rgba(192,193,255,0.12)] text-white":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07] hover:text-white"),onClick:()=>u(ee.id),children:[e.jsx(Y,{className:"size-4 text-[var(--secondary)]"}),e.jsx("div",{className:"mt-3 text-sm font-semibold",children:ee.label}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-white/48",children:ee.detail})]},ee.id)})}),e.jsx("div",{className:"rounded-[28px] border border-white/8 bg-[rgba(9,14,26,0.72)] p-4 sm:p-5",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsx(le,{value:m,onChange:ee=>b(ee.target.value),placeholder:"Optional title hint"}),v==="files"?e.jsxs("div",{className:re("rounded-[28px] border-2 border-dashed px-5 py-8 text-center transition",p?"border-[rgba(192,193,255,0.35)] bg-[rgba(192,193,255,0.08)]":"border-white/10 bg-white/[0.03]"),onDragEnter:ee=>{ee.preventDefault(),A(!0)},onDragLeave:ee=>{ee.preventDefault(),A(!1)},onDragOver:ee=>{ee.preventDefault(),A(!0)},onDrop:ee=>{ee.preventDefault(),A(!1);const Y=Array.from(ee.dataTransfer.files);S(R=>[...R,...Y])},children:[e.jsx("div",{className:"mx-auto flex size-14 items-center justify-center rounded-full border border-white/10 bg-white/[0.05]",children:e.jsx(lr,{className:"size-5 text-white/72"})}),e.jsx("div",{className:"mt-4 text-base font-semibold text-white",children:"Drop files, media, notes, or ZIP archives here"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/50",children:"Forge accepts many files at once and queues the ingest in the background so the UI stays responsive."}),e.jsxs("label",{className:"mt-5 inline-flex cursor-pointer items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm text-white/78 transition hover:bg-white/[0.08] hover:text-white",children:[e.jsx(lr,{className:"size-4"}),"Choose files",e.jsx("input",{type:"file",multiple:!0,className:"hidden",onChange:ee=>S(Array.from(ee.target.files??[]))})]}),j.length>0?e.jsx("div",{className:"mt-5 grid gap-2 text-left",children:j.map(ee=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-3 text-sm text-white/72",children:[e.jsx("span",{className:"truncate",children:ee.name}),e.jsx("span",{className:"shrink-0 text-xs text-white/42",children:ee.name.toLowerCase().endsWith(".zip")?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Gp,{className:"size-3.5"}),"ZIP"]}):`${Math.max(1,Math.round(ee.size/1024))} KB`})]},`${ee.name}-${ee.size}-${ee.lastModified}`))}):null]}):null,v==="url"?e.jsx(le,{value:w,onChange:ee=>M(ee.target.value),placeholder:"https://example.com/source"}):null,v==="text"?e.jsx(Me,{value:E,onChange:ee=>D(ee.target.value),placeholder:"Paste notes, transcripts, meeting writeups, or source material here…",className:"min-h-[18rem]"}):null]})})]}),e.jsxs("aside",{className:"grid h-fit gap-4",children:[I?null:e.jsxs("div",{className:"rounded-[30px] border border-amber-300/28 bg-[linear-gradient(180deg,rgba(120,74,14,0.28),rgba(37,22,8,0.42))] p-5 shadow-[0_24px_64px_rgba(12,6,0,0.22)]",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 flex size-10 shrink-0 items-center justify-center rounded-full border border-amber-200/20 bg-amber-300/12 text-amber-100",children:e.jsx(Il,{className:"size-4.5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-amber-100/62",children:"OpenAI setup required for smart ingest"}),e.jsx("div",{className:"mt-2 text-lg font-semibold text-white",children:"Forge can only do a raw import without OpenAI"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/78",children:"Without an OpenAI ingest profile, Forge cannot extract key insights, split the source into draft wiki pages, or propose Forge entities. The fallback is just a direct text import or media reference with no structured synthesis."}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/62",children:"Set up the API key, model, thinking, and verbosity first, then come back here to build real draft pages and reviewable entity proposals."})]})]}),e.jsxs("div",{className:"mt-5 grid gap-3 sm:grid-cols-2",children:[e.jsxs(Q,{className:"w-full",onClick:()=>{s(!1),c("/settings/wiki?setupLlm=1")},children:[e.jsx(Tt,{className:"size-4"}),"Open OpenAI setup"]}),e.jsx(Q,{variant:"secondary",className:"w-full",onClick:()=>{s(!1),c("/settings/wiki")},children:"Open Wiki settings"})]})]}),e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 text-left",onClick:()=>k(ee=>!ee),children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Advanced"}),e.jsx("div",{className:"mt-2 text-sm text-white/72",children:"Model, parse, and target controls."})]}),e.jsx(Tt,{className:"size-4 text-white/58"})]}),T?e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"mb-2 text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Space"}),e.jsx("div",{className:"grid gap-2",children:i.map(ee=>e.jsxs("button",{type:"button",className:re("rounded-[18px] border px-3 py-3 text-left text-sm transition",f===ee.id?"border-[rgba(192,193,255,0.24)] bg-[rgba(192,193,255,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/68 hover:bg-white/[0.06] hover:text-white"),onClick:()=>h(ee.id),children:[e.jsx("div",{children:ee.label}),e.jsx("div",{className:"mt-1 text-xs text-white/45",children:ee.description||`/${ee.slug}`})]},ee.id))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-2 text-[11px] uppercase tracking-[0.16em] text-white/42",children:"LLM profile"}),e.jsxs("div",{className:"grid gap-2",children:[$.map(ee=>e.jsxs("button",{type:"button",className:re("rounded-[18px] border px-3 py-3 text-left text-sm transition",g===ee.id?"border-[rgba(192,193,255,0.24)] bg-[rgba(192,193,255,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/68 hover:bg-white/[0.06] hover:text-white"),onClick:()=>C(ee.id),children:[e.jsx("div",{children:ee.label}),e.jsx("div",{className:"mt-1 text-xs text-white/45",children:ee.model})]},ee.id)),$.length===0?e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 px-4 py-4 text-sm text-white/48",children:"No enabled profile with a saved key yet."}):null]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-2 text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Parse mode"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-3",children:[{id:"auto",label:"Auto"},{id:"multimodal",label:"Multimodal"},{id:"text_only",label:"Text only"}].map(ee=>e.jsx("button",{type:"button",className:re("rounded-[18px] border px-3 py-3 text-sm transition",F===ee.id?"border-[rgba(192,193,255,0.24)] bg-[rgba(192,193,255,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/68 hover:bg-white/[0.06] hover:text-white"),onClick:()=>z(ee.id),children:ee.label},ee.id))})]})]}):null]}),e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(192,193,255,0.12),rgba(192,193,255,0.05))] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white",children:[e.jsx(Wo,{className:"size-4 text-[var(--secondary)]"}),e.jsx("span",{className:"text-sm font-semibold",children:"Publish only what belongs"})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/62",children:"Forge stages candidate pages, proposed entity records, and page updates first. You review the output before anything is committed to the live memory graph."})]}),_?e.jsx("div",{className:"rounded-[20px] border border-rose-300/22 bg-rose-400/10 px-4 py-3 text-sm text-rose-100",children:_}):null,e.jsxs(Q,{className:"min-h-12",pending:ne.isPending,pendingLabel:"Starting ingest",disabled:!I,onClick:()=>void ne.mutateAsync(),children:[e.jsx(Tt,{className:"size-4"}),"Start background ingest"]})]})]})})]})]})})}function RN(t){return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",year:"numeric"}).format(new Date(t))}function zN(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Nu({nodes:t,activeSlug:s,spaceId:i,depth:a=0}){return e.jsx("ul",{className:re("grid gap-1",a>0&&"mt-1"),children:t.map(n=>{const r=n.page.slug===s;return e.jsxs("li",{className:"grid gap-1",children:[e.jsx(Ae,{to:{pathname:n.page.slug==="index"?"/wiki":`/wiki/page/${encodeURIComponent(n.page.slug)}`,search:`?spaceId=${encodeURIComponent(i)}`},className:re("rounded-lg px-2 py-1.5 text-[12px] leading-5 transition",r?"bg-white/[0.08] text-white":"text-white/64 hover:bg-white/[0.04] hover:text-white"),style:{paddingLeft:`${.5+a*.7}rem`},children:n.page.title}),n.children.length>0?e.jsx(Nu,{nodes:n.children,activeSlug:s,spaceId:i,depth:a+1}):null]},n.page.id)})})}function qN({open:t,onOpenChange:s,spaces:i,activeSpaceId:a,onSelect:n}){return e.jsx(Et,{open:t,onOpenChange:s,children:e.jsxs(Lt,{children:[e.jsx(Dt,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.72)] backdrop-blur-sm"}),e.jsxs($t,{className:"fixed left-1/2 top-[14vh] z-50 w-[min(28rem,calc(100vw-1.5rem))] -translate-x-1/2 rounded-[28px] border border-white/10 bg-[rgba(10,15,28,0.97)] p-4 shadow-[0_32px_90px_rgba(0,0,0,0.45)] sm:p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(Ot,{className:"font-display text-[1.2rem] tracking-[-0.04em] text-white",children:"Choose wiki space"}),e.jsx(qt,{className:"mt-1 text-[13px] leading-6 text-white/56",children:"Switch the reading space without leaving the article surface."})]}),e.jsx(Ft,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white","aria-label":"Close space picker",children:e.jsx(mt,{className:"size-4"})})})]}),e.jsx("div",{className:"mt-4 grid gap-2",children:i.map(r=>{const l=r.id===a;return e.jsxs("button",{type:"button",className:re("flex items-center justify-between gap-3 rounded-[22px] border px-4 py-3 text-left transition",l?"border-[rgba(192,193,255,0.22)] bg-[rgba(192,193,255,0.12)] text-white":"border-white/8 bg-white/[0.03] text-white/78 hover:bg-white/[0.06] hover:text-white"),onClick:()=>{n(r.id),s(!1)},children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[14px] font-semibold text-inherit",children:r.label}),e.jsx("span",{className:"mt-1 block text-[12px] leading-5 text-white/52",children:r.description||`/${r.slug}`})]}),l?e.jsx(Vi,{className:"size-4 shrink-0 text-[var(--primary)]"}):null]},r.id)})})]})]})})}function Vc(){var Ne,H,me,y,P,q,pe,ee,Y;const t=ut(),s=We(),{slug:i}=es(),[a,n]=Pt(),[r,l]=d.useState(!1),[o,c]=d.useState(!1),[x,v]=d.useState(!1),[u,f]=d.useState("hybrid"),[h,m]=d.useState(""),[b,w]=d.useState(""),M=d.useRef(null),E=a.get("spaceId")??"",D=a.get("ingest")==="1",j=a.get("ingestJobId"),S=fe({queryKey:["forge-wiki-settings"],queryFn:Gn}),p=E||((H=(Ne=S.data)==null?void 0:Ne.settings.spaces[0])==null?void 0:H.id)||"",A=((me=S.data)==null?void 0:me.settings.embeddingProfiles.filter(R=>R.enabled))??[];d.useEffect(()=>{var R;!b&&((R=A[0])!=null&&R.id)&&w(A[0].id)},[A,b]),d.useEffect(()=>{var R,X;if(!E&&((X=(R=S.data)==null?void 0:R.settings.spaces[0])!=null&&X.id)){const be=new URLSearchParams(a);be.set("spaceId",S.data.settings.spaces[0].id),n(be,{replace:!0})}},[a,E,n,S.data]);const T=fe({queryKey:["forge-wiki-home",p],queryFn:()=>kg({spaceId:p||void 0}),enabled:!!p&&!i}),k=fe({queryKey:["forge-wiki-page-by-slug",p,i],queryFn:()=>Sg({slug:i??"index",spaceId:p||void 0}),enabled:!!p&&!!i}),$=fe({queryKey:["forge-wiki-tree",p],queryFn:()=>Cg({spaceId:p||void 0,kind:"wiki"}),enabled:!!p}),g=fe({queryKey:["forge-wiki-modal-search",p,u,h,b],queryFn:()=>Pg({spaceId:p||void 0,mode:u,query:h.trim(),profileId:(u==="semantic"||u==="hybrid")&&b||void 0,limit:30}),enabled:r&&!!p&&h.trim().length>0}),C=i?k.data??null:T.data??null,[F,z]=d.useState(null);d.useEffect(()=>{C&&z(C)},[C]);const J=!!p&&(i?k.isFetching:T.isFetching),O=C??(J?F:null),_=(O==null?void 0:O.page)??null,B=((y=S.data)==null?void 0:y.settings.spaces.find(R=>R.id===p))??null,K=(_==null?void 0:_.slug)!=="index",Z=i&&k.error instanceof Ea&&k.error.status===404?i.trim():null;d.useEffect(()=>{if(!p||!Z)return;const R=new URLSearchParams;R.set("spaceId",p),R.set("title",Z);const X=zN(Z);X&&R.set("slug",X),t(`/wiki/new?${R.toString()}`,{replace:!0})},[p,Z,t]);const U=d.useMemo(()=>((_==null?void 0:_.links)??[]).map(R=>({id:`${R.entityType}:${R.entityId}`,href:Xs(R.entityType,R.entityId),label:`${R.entityType} · ${R.entityId}`})),[_==null?void 0:_.links]),I=xe({mutationFn:async R=>Tg(R),onSuccess:async()=>{await Promise.all([s.invalidateQueries({queryKey:["forge-wiki-tree"]}),s.invalidateQueries({queryKey:["forge-wiki-home"]}),s.invalidateQueries({queryKey:["forge-wiki-page-by-slug"]}),s.invalidateQueries({queryKey:["forge-wiki-modal-search"]})]),t(`/wiki${p?`?spaceId=${encodeURIComponent(p)}`:""}`)}}),G=(R,X=!1)=>{const be=new URLSearchParams(a);R(be),n(be,{replace:X})},W=R=>{G(X=>{X.set("ingest","1"),R?X.set("ingestJobId",R):X.delete("ingestJobId"),p&&X.set("spaceId",p)})},ne=()=>{G(R=>{R.delete("ingest"),R.delete("ingestJobId")})},de=R=>{G(X=>{X.set("ingest","1"),R?X.set("ingestJobId",R):X.delete("ingestJobId"),p&&X.set("spaceId",p)})},we=()=>{!_||!K||I.isPending||!window.confirm(`Delete wiki page "${_.title}"? You can restore it later from the bin.`)||I.mutateAsync(_.id)};return d.useEffect(()=>{if(!x)return;const R=be=>{var Ie;(Ie=M.current)!=null&&Ie.contains(be.target)||v(!1)},X=be=>{be.key==="Escape"&&v(!1)};return document.addEventListener("pointerdown",R),document.addEventListener("keydown",X),()=>{document.removeEventListener("pointerdown",R),document.removeEventListener("keydown",X)}},[x]),!_&&(S.isLoading||$.isLoading||!i&&T.isLoading||i&&k.isLoading)?e.jsx(nt,{eyebrow:"Wiki",title:"Loading the article",description:"Preparing the current space, article, and wiki index."}):!_&&!Z&&(S.isError||T.isError||k.isError||$.isError)?e.jsx(ze,{eyebrow:"Wiki",error:S.error??T.error??k.error??$.error,onRetry:()=>{S.refetch(),T.refetch(),k.refetch(),$.refetch()}}):_?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-4 sm:px-5 lg:px-6",children:e.jsxs("div",{className:"mx-auto flex w-full max-w-[1680px] flex-col gap-4",children:[e.jsxs("section",{className:"wiki-frame px-3 py-3 sm:px-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] uppercase tracking-[0.16em] text-white/42",children:[e.jsx("span",{children:"Wiki"}),B?e.jsx("span",{children:B.label}):null,e.jsx("span",{children:RN(_.updatedAt)})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row lg:items-center",children:[e.jsxs("button",{type:"button",className:"wiki-search-launch flex min-h-[2.9rem] w-full items-center gap-3 rounded-[18px] border border-white/8 bg-white/[0.04] px-4 text-left text-[14px] text-white/56 transition hover:bg-white/[0.06] hover:text-white lg:flex-1",onClick:()=>l(!0),children:[e.jsx(bt,{className:"size-4 shrink-0 text-white/44"}),e.jsx("span",{children:"Search this wiki"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 lg:shrink-0",children:[e.jsx("button",{type:"button",className:"wiki-space-trigger inline-flex min-h-[2.9rem] items-center gap-2 rounded-[18px] border border-white/8 bg-white/[0.04] px-4 text-[13px] font-medium text-white/78 transition hover:bg-white/[0.07] hover:text-white",onClick:()=>c(!0),children:e.jsx("span",{className:"max-w-[16rem] truncate",children:(B==null?void 0:B.label)??"Wiki space"})}),e.jsxs("div",{className:"relative",ref:M,children:[e.jsxs(Q,{variant:"secondary",size:"sm",className:"min-h-[2.9rem]",onClick:()=>v(R=>!R),children:[e.jsx(Tt,{className:"size-3.5"}),"Ingest",e.jsx(Ji,{className:"size-3.5"})]}),x?e.jsxs("div",{className:"absolute right-0 top-[calc(100%+0.5rem)] z-20 grid min-w-[15rem] gap-2 rounded-[22px] border border-white/10 bg-[rgba(9,14,27,0.98)] p-2 shadow-[0_24px_60px_rgba(0,0,0,0.35)]",children:[e.jsxs("button",{type:"button",className:"flex items-start gap-3 rounded-[18px] px-3 py-3 text-left transition hover:bg-white/[0.06]",onClick:()=>{v(!1),W()},children:[e.jsx(Tt,{className:"mt-0.5 size-4 shrink-0 text-[var(--primary)]"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-medium text-white",children:"New ingest"}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-white/48",children:"Start a fresh import from files, URLs, or pasted text."})]})]}),e.jsxs("button",{type:"button",className:"flex items-start gap-3 rounded-[18px] px-3 py-3 text-left transition hover:bg-white/[0.06]",onClick:()=>{v(!1),t(`/wiki/ingest-history${p?`?spaceId=${encodeURIComponent(p)}`:""}`)},children:[e.jsx(jh,{className:"mt-0.5 size-4 shrink-0 text-[var(--secondary)]"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-medium text-white",children:"History"}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-white/48",children:"Browse prior ingests, reopen reviews, and delete old ingest records."})]})]})]}):null]}),e.jsxs(Q,{variant:"secondary",size:"sm",className:"min-h-[2.9rem]",onClick:()=>t(`/wiki/edit/${encodeURIComponent(_.id)}?spaceId=${encodeURIComponent(p)}`,{state:{initialPage:_}}),children:[e.jsx(Tl,{className:"size-3.5"}),"Edit"]}),e.jsxs(Q,{variant:"secondary",size:"sm",className:re("min-h-[2.9rem] border border-rose-400/18 bg-rose-500/10 text-rose-100 hover:bg-rose-500/18",!K&&"opacity-60"),onClick:we,pending:I.isPending,pendingLabel:"Deleting",disabled:!K,title:K?"Delete this wiki page":"The wiki home page cannot be deleted",children:[e.jsx(ct,{className:"size-3.5"}),"Delete"]}),e.jsxs(Q,{size:"sm",className:"min-h-[2.9rem]",onClick:()=>t(`/wiki/new?spaceId=${encodeURIComponent(p)}`),children:[e.jsx(zt,{className:"size-3.5"}),"New page"]})]})]})]}),e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[15rem_minmax(0,1fr)] xl:grid-cols-[16rem_minmax(0,1fr)]",children:[e.jsxs("aside",{className:"wiki-frame h-fit px-2 py-3 sm:px-3 lg:sticky lg:top-[5.75rem]",children:[e.jsx("div",{className:"px-2 pb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-white/42",children:"Index"}),e.jsx(Nu,{nodes:((P=$.data)==null?void 0:P.tree)??[],activeSlug:_.slug,spaceId:p})]}),e.jsxs("article",{"aria-busy":J,className:re("wiki-frame relative overflow-hidden px-4 py-5 transition-[opacity,transform] duration-200 sm:px-6 sm:py-6",J&&"opacity-[0.985]"),children:[J?e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-px bg-[linear-gradient(90deg,transparent,rgba(192,193,255,0.8),transparent)] opacity-90"}):null,e.jsxs("div",{className:"wiki-reading-copy wiki-reading-flow mx-auto max-w-[76rem]",children:[I.isError?e.jsx("div",{className:"mb-4 rounded-[18px] border border-rose-400/20 bg-rose-500/10 px-4 py-3 text-sm text-rose-100",children:I.error instanceof Error?I.error.message:"Forge could not delete this wiki page."}):null,e.jsx(yu,{markdown:_.contentMarkdown,spaceId:p}),_.summary.trim()?e.jsx("p",{className:"mt-5 border-t border-white/8 pt-4 text-[13px] leading-6 text-white/56",children:_.summary}):null,U.length>0?e.jsxs("section",{className:"mt-8 border-t border-white/8 pt-4",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-white/42",children:"Forge links"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:U.map(R=>e.jsx("a",{href:R.href?ui(R.href):void 0,className:"rounded-full bg-white/[0.05] px-3 py-1.5 text-[12px] text-white/76 transition hover:bg-white/[0.1] hover:text-white",children:R.label},R.id))})]}):null,O!=null&&O.backlinkSourceNotes.length?e.jsxs("section",{className:"mt-8 border-t border-white/8 pt-4",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-white/42",children:"Linked here"}),e.jsx("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:O.backlinkSourceNotes.map(R=>e.jsxs(Ae,{to:{pathname:R.slug==="index"?"/wiki":`/wiki/page/${encodeURIComponent(R.slug)}`,search:`?spaceId=${encodeURIComponent(R.spaceId)}`},className:"rounded-xl border border-white/8 bg-white/[0.03] px-4 py-3 transition hover:bg-white/[0.06]",children:[e.jsx("div",{className:"text-[13px] font-semibold text-white",children:R.title}),R.summary?e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/56",children:R.summary}):null]},R.id))})]}):null]})]})]})]})}),e.jsx(Et,{open:r,onOpenChange:l,children:e.jsxs(Lt,{children:[e.jsx(Dt,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.8)] backdrop-blur-sm"}),e.jsxs($t,{className:"fixed left-1/2 top-[8vh] z-50 w-[min(54rem,calc(100vw-1.5rem))] -translate-x-1/2 rounded-[28px] border border-white/10 bg-[rgba(10,15,28,0.96)] p-4 shadow-[0_30px_90px_rgba(0,0,0,0.45)] sm:p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsx("div",{children:e.jsx(Ot,{className:"font-display text-[1.35rem] tracking-[-0.04em] text-white",children:"Search the wiki"})}),e.jsx(Ft,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white","aria-label":"Close search",children:e.jsx(mt,{className:"size-4"})})})]}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsx(le,{autoFocus:!0,value:h,onChange:R=>m(R.target.value),placeholder:"Search wiki pages",className:"h-11 rounded-2xl border-white/10 bg-white/[0.04] text-[14px] text-white placeholder:text-white/28"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[["text","hybrid","semantic","entity"].map(R=>e.jsx("button",{type:"button",className:re("rounded-full px-3 py-1.5 text-[12px] font-medium uppercase tracking-[0.14em] transition",u===R?"bg-white/[0.12] text-white":"bg-white/[0.04] text-white/54 hover:bg-white/[0.08] hover:text-white"),onClick:()=>f(R),children:R},R)),(u==="semantic"||u==="hybrid")&&A.length>0?e.jsx("select",{className:"ml-auto rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-[12px] text-white",value:b,onChange:R=>w(R.target.value),children:A.map(R=>e.jsx("option",{value:R.id,children:R.label},R.id))}):null]})]}),e.jsx("div",{className:"mt-4 max-h-[60vh] overflow-y-auto",children:h.trim()?g.isLoading?e.jsx(nt,{eyebrow:"Wiki search",title:"Searching",description:"Ranking matching pages for this query."}):g.isError?e.jsx(ze,{eyebrow:"Wiki search",error:g.error,onRetry:()=>void g.refetch()}):(q=g.data)!=null&&q.results.length?e.jsx("div",{className:"grid gap-2",children:g.data.results.map(R=>e.jsx("button",{type:"button",className:"rounded-2xl border border-white/8 bg-white/[0.03] px-4 py-3 text-left transition hover:bg-white/[0.06]",onClick:()=>{l(!1),t({pathname:R.page.slug==="index"?"/wiki":`/wiki/page/${encodeURIComponent(R.page.slug)}`,search:`?spaceId=${encodeURIComponent(R.page.spaceId)}`})},children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[14px] font-semibold text-white",children:R.page.title}),R.page.summary?e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/56",children:R.page.summary}):null]}),e.jsx(L,{size:"sm",tone:"meta",children:R.score.toFixed(2)})]})},R.page.id))}):e.jsx("div",{className:"rounded-2xl border border-dashed border-white/10 px-4 py-10 text-center text-[13px] leading-6 text-white/42",children:"No pages matched this search."}):e.jsx("div",{className:"rounded-2xl border border-dashed border-white/10 px-4 py-10 text-center text-[13px] leading-6 text-white/42",children:"Start typing to search the current wiki space."})})]})]})}),e.jsx(qN,{open:o,onOpenChange:c,spaces:((pe=S.data)==null?void 0:pe.settings.spaces)??[],activeSpaceId:p,onSelect:R=>{const X=new URLSearchParams(a);X.set("spaceId",R),n(X,{replace:!0}),t("/wiki",{replace:!0})}}),e.jsx(ju,{open:D,onOpenChange:R=>{if(R){W(j);return}ne()},spaces:((ee=S.data)==null?void 0:ee.settings.spaces)??[],llmProfiles:((Y=S.data)==null?void 0:Y.settings.llmProfiles)??[],initialSpaceId:p,selectedJobId:j,onJobSelected:de,linkedEntityHints:_.links.map(R=>({entityType:R.entityType,entityId:R.entityId,anchorKey:null}))??[]})]}):Z?e.jsx(nt,{eyebrow:"Wiki",title:"Opening a new page",description:`Creating a draft for ${Z}.`}):e.jsx(gt,{eyebrow:"Wiki",title:"Article not found",description:"This page does not exist in the selected space."})}const BN=[{value:"all",label:"All"},{value:"queued",label:"Queued"},{value:"processing",label:"Processing"},{value:"completed",label:"Completed"},{value:"failed",label:"Failed"},{value:"review",label:"Review"},{value:"reviewed",label:"Reviewed"}];function KN(t){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(t))}function UN(t,s){return s==="all"?!0:t.job.status===s||t.job.phase===s}function QN(){var D,j,S,p,A,T;const t=ut(),s=We(),[i,a]=Pt(),n=i.get("spaceId")||"",r=i.get("q")||"",l=i.get("tag")||"all",o=i.get("from")||"",c=i.get("to")||"",x=i.get("ingest")==="1",v=i.get("ingestJobId"),u=fe({queryKey:["forge-wiki-settings"],queryFn:Gn}),f=fe({queryKey:["forge-wiki-ingest-history",n],queryFn:()=>_h({spaceId:n||void 0,limit:200}),enabled:u.isSuccess}),h=xe({mutationFn:k=>Rh(k),onSuccess:async(k,$)=>{if(await s.invalidateQueries({queryKey:["forge-wiki-ingest-history"]}),await s.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),v===$){const g=new URLSearchParams(i);g.delete("ingest"),g.delete("ingestJobId"),a(g,{replace:!0})}}}),m=(k,$)=>{const g=new URLSearchParams(i);$.trim()?g.set(k,$.trim()):g.delete(k),a(g,{replace:!0})},b=d.useMemo(()=>{var g;const k=((g=f.data)==null?void 0:g.jobs)??[],$=r.trim().toLowerCase();return k.filter(C=>{if(!UN(C,l))return!1;const F=C.job.createdAt.slice(0,10);return o&&F<o||c&&F>c?!1:$?[C.job.titleHint,C.job.latestMessage,C.job.sourceLocator,C.job.status,C.job.phase,C.job.mimeType].join(" ").toLowerCase().includes($):!0})},[o,(D=f.data)==null?void 0:D.jobs,r,l,c]),w=n||((S=(j=u.data)==null?void 0:j.settings.spaces[0])==null?void 0:S.id)||"",M=k=>{const $=new URLSearchParams(i);$.set("ingest","1"),k?$.set("ingestJobId",k):$.delete("ingestJobId"),a($,{replace:!0})},E=()=>{const k=new URLSearchParams(i);k.delete("ingest"),k.delete("ingestJobId"),a(k,{replace:!0})};return u.isLoading||f.isLoading?e.jsx(It,{eyebrow:"Wiki",title:"Loading ingest history",description:"Gathering prior imports, statuses, and review state.",columns:1,blocks:6}):u.isError||f.isError?e.jsx(ze,{eyebrow:"Wiki",error:u.error??f.error,onRetry:()=>{u.refetch(),f.refetch()}}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-4 sm:px-5 lg:px-6",children:e.jsxs("div",{className:"mx-auto grid w-full max-w-[1480px] gap-5",children:[e.jsx(qe,{title:"Wiki Ingest History",description:"Search prior ingests, reopen a review, or clear ingest records without touching pages and entities that were already published.",badge:`${b.length} matching jobs`}),e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"History Filters"}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Narrow by free text, date range, space, or status tags."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Q,{variant:"secondary",onClick:()=>t(`/wiki${n?`?spaceId=${encodeURIComponent(n)}`:""}`),children:"Back to wiki"}),e.jsxs(Q,{onClick:()=>M(),children:[e.jsx(Tt,{className:"size-3.5"}),"New ingest"]})]})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1.4fr)_minmax(0,0.8fr)_minmax(0,0.8fr)_minmax(0,0.8fr)]",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Free text"}),e.jsx(le,{value:r,onChange:k=>m("q",k.target.value),placeholder:"title, source, status, failure message…"})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"From"}),e.jsx(le,{type:"date",value:o,onChange:k=>m("from",k.target.value)})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"To"}),e.jsx(le,{type:"date",value:c,onChange:k=>m("to",k.target.value)})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Space"}),e.jsxs("select",{className:"h-11 rounded-[18px] border border-white/10 bg-white/[0.04] px-3 text-sm text-white",value:n,onChange:k=>m("spaceId",k.target.value),children:[e.jsx("option",{value:"",children:"All spaces"}),(((p=u.data)==null?void 0:p.settings.spaces)??[]).map(k=>e.jsx("option",{value:k.id,children:k.label},k.id))]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:BN.map(k=>e.jsx("button",{type:"button",className:re("rounded-full px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] transition",l===k.value?"bg-[var(--primary)]/[0.18] text-[var(--primary)]":"bg-white/[0.04] text-white/58 hover:bg-white/[0.08] hover:text-white"),onClick:()=>m("tag",k.value==="all"?"":k.value),children:k.label},k.value))})]}),b.length===0?e.jsx(gt,{eyebrow:"Wiki ingest",title:"No ingest jobs match these filters",description:"Try widening the dates or clearing a status tag."}):e.jsx("div",{className:"grid gap-3",children:b.map(k=>{const $=k.job.titleHint||k.job.latestMessage||k.job.sourceLocator||"Wiki ingest",g=!["queued","processing"].includes(k.job.status);return e.jsxs(ae,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("button",{type:"button",className:"min-w-0 flex-1 text-left",onClick:()=>M(k.job.id),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Wiki ingest"}),e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] uppercase tracking-[0.16em] text-white/60",children:k.job.status}),e.jsx("span",{className:"rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] uppercase tracking-[0.16em] text-white/44",children:k.job.phase})]}),e.jsx("div",{className:"mt-3 text-lg font-semibold text-white",children:$}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-x-4 gap-y-1 text-sm text-white/56",children:[e.jsxs("span",{children:[k.job.progressPercent,"% · ",k.job.createdPageCount," pages ·"," ",k.job.createdEntityCount," entities"]}),e.jsx("span",{children:KN(k.job.createdAt)}),k.job.sourceLocator?e.jsx("span",{className:"truncate",children:k.job.sourceLocator}):null]})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx(Q,{variant:"secondary",size:"sm",onClick:()=>M(k.job.id),children:"Open review"}),e.jsxs(Q,{variant:"secondary",size:"sm",disabled:!g||h.isPending,pending:h.isPending&&h.variables===k.job.id,pendingLabel:"Deleting",onClick:()=>{!g||!window.confirm("Delete this ingest history entry? Published pages and entities will stay, but discarded or unreviewed ingest artifacts will be removed.")||h.mutateAsync(k.job.id)},children:[e.jsx(ct,{className:"size-3.5"}),"Delete"]})]})]}),k.job.errorMessage?e.jsx("div",{className:"rounded-[18px] border border-rose-400/18 bg-rose-500/[0.08] px-4 py-3 text-sm text-rose-100/86",children:k.job.errorMessage}):null,["queued","processing"].includes(k.job.status)?e.jsxs("div",{className:"inline-flex items-center gap-2 text-sm text-white/50",children:[e.jsx(_n,{className:"size-4 animate-spin"}),"This ingest is still active and cannot be deleted yet."]}):null]},k.job.id)})})]})}),e.jsx(ju,{open:x,onOpenChange:k=>{k||E()},spaces:((A=u.data)==null?void 0:A.settings.spaces)??[],llmProfiles:((T=u.data)==null?void 0:T.settings.llmProfiles)??[],initialSpaceId:w,selectedJobId:v,onJobSelected:k=>M(k)})]})}const ga={goal:"goal",project:"project",task:"task",strategy:"strategy",habit:"habit"};function zi(t,s){return`${t}:${s}`}function WN(t){const s=t.indexOf(":");return s<=0||s>=t.length-1?null:{entityType:t.slice(0,s),entityId:t.slice(s+1)}}function ku(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Li(t){return Array.from(new Set(t.split(",").map(s=>s.trim()).filter(Boolean)))}function HN(t){if(!t.trim())return{};try{const s=JSON.parse(t);return s&&typeof s=="object"&&!Array.isArray(s)?s:{}}catch{return{}}}function Su(){return{pageId:null,kind:"wiki",title:"",slug:"",parentSlug:"index",indexOrder:0,showInIndex:!0,summary:"",aliasesText:"",contentMarkdown:`# Untitled
|
|
42
|
-
|
|
43
|
-
`,author:"",tagsText:"",frontmatterText:`{
|
|
44
|
-
"status": "draft"
|
|
45
|
-
}`,linkedValues:[]}}function GN(t,s){const i=t.trim()||"Untitled";return{...Su(),title:i,slug:(s==null?void 0:s.trim())||ku(i),contentMarkdown:`# ${i}
|
|
46
|
-
|
|
47
|
-
`}}function Jc(t){return{pageId:t.id,kind:t.kind,title:t.title,slug:t.slug,parentSlug:t.parentSlug,indexOrder:t.indexOrder,showInIndex:t.showInIndex,summary:t.summary,aliasesText:t.aliases.join(", "),contentMarkdown:t.contentMarkdown,author:t.author??"",tagsText:(t.tags??[]).join(", "),frontmatterText:JSON.stringify(t.frontmatter??{},null,2),linkedValues:t.links.map(s=>zi(s.entityType,s.entityId))}}function Di({open:t,title:s,description:i,children:a,onOpenChange:n}){return e.jsx(Et,{open:t,onOpenChange:n,children:e.jsxs(Lt,{children:[e.jsx(Dt,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.8)] backdrop-blur-sm"}),e.jsxs($t,{className:"fixed left-1/2 top-[12vh] z-50 w-[min(32rem,calc(100vw-1.5rem))] -translate-x-1/2 rounded-[24px] border border-white/10 bg-[rgba(10,15,28,0.96)] p-4 shadow-[0_24px_80px_rgba(0,0,0,0.45)] sm:p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(Ot,{className:"text-[1.05rem] font-semibold text-white",children:s}),e.jsx(qt,{className:"mt-1 text-[13px] leading-6 text-white/56",children:i})]}),e.jsx(Ft,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white","aria-label":"Close",children:e.jsx(mt,{className:"size-4"})})})]}),e.jsx("div",{className:"mt-4",children:a})]})]})})}const XN="w-full rounded-[18px] border border-white/10 bg-[rgba(10,16,30,0.78)] px-3.5 py-3 text-[13px] text-white outline-none transition focus:border-[rgba(192,193,255,0.35)]";function Yc(t){return t.trim().toLowerCase()}function VN(t){const s=t.trim();return s?s.split(/\s+/).length:0}function JN({icon:t,label:s,onClick:i}){return e.jsxs("div",{className:"group relative",children:[e.jsx("button",{type:"button","aria-label":s,className:"inline-flex size-10 items-center justify-center rounded-[14px] border border-white/8 bg-white/[0.04] text-white/62 transition hover:bg-white/[0.08] hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[rgba(192,193,255,0.35)]",onClick:i,children:e.jsx(t,{className:"size-4"})}),e.jsx("div",{className:"pointer-events-none absolute left-1/2 top-[calc(100%+0.55rem)] z-20 -translate-x-1/2 rounded-[12px] border border-white/8 bg-[rgba(10,15,28,0.96)] px-2.5 py-1.5 text-[11px] font-medium text-white/76 opacity-0 shadow-[0_18px_40px_rgba(0,0,0,0.32)] transition group-hover:opacity-100 group-focus-within:opacity-100",children:s})]})}function YN(t){return t.map(s=>({value:s.label,label:s.label,description:s.description,searchText:`${s.label} ${s.description}`,badge:e.jsx(L,{className:"bg-white/[0.08] text-white/80",style:s.color?{color:s.color}:void 0,children:s.label}),menuBadge:e.jsx(L,{className:"bg-white/[0.08] text-white/80",style:s.color?{color:s.color}:void 0,children:s.label})}))}function Zc(){var H,me,y,P,q,pe,ee,Y,R,X,be,Ie;const t=Je(),s=We(),i=fi(),a=ut(),{pageId:n}=es(),[r,l]=Pt(),[o,c]=d.useState(()=>Su()),[x,v]=d.useState(null),[u,f]=d.useState(""),[h,m]=d.useState(""),[b,w]=d.useState(!1),[M,E]=d.useState(!1),[D,j]=d.useState(""),[S,p]=d.useState(""),A=d.useRef(null),T=d.useRef(!1),k=((H=i.state)==null?void 0:H.initialPage)??null,$=((me=r.get("title"))==null?void 0:me.trim())??"",g=((y=r.get("slug"))==null?void 0:y.trim())??"",C=fe({queryKey:["forge-wiki-settings"],queryFn:Gn}),F=fe({queryKey:["forge-wiki-page",n],queryFn:()=>Ng(n??""),enabled:!!n}),z=r.get("spaceId")||((P=F.data)==null?void 0:P.page.spaceId)||(k==null?void 0:k.spaceId)||((pe=(q=C.data)==null?void 0:q.settings.spaces[0])==null?void 0:pe.id)||"",J=((Y=(ee=C.data)==null?void 0:ee.settings.spaces.find(te=>te.id===z))==null?void 0:Y.label)??"Current space",O=fe({queryKey:["forge-wiki-pages",z],queryFn:()=>jg({spaceId:z||void 0,limit:500}),enabled:!!z});d.useEffect(()=>{k&&(!n||k.id===n)&&c(Jc(k))},[n,k]),d.useEffect(()=>{n||k||T.current||!$||(T.current=!0,c(GN($,g)))},[g,$,n,k]),d.useEffect(()=>{var te;(te=F.data)!=null&&te.page&&c(Jc(F.data.page))},[F.data]);const _=d.useMemo(()=>{var te;return(((te=O.data)==null?void 0:te.pages)??[]).filter(ce=>ce.id!==o.pageId).sort((ce,Se)=>ce.title.localeCompare(Se.title))},[o.pageId,(R=O.data)==null?void 0:R.pages]),B=d.useMemo(()=>{var ce;const te=new Map;for(const Se of((ce=O.data)==null?void 0:ce.pages)??[])for(const he of Se.aliases??[]){const Ge=he.trim();Ge&&te.set(Ge.toLowerCase(),{value:Ge,label:Ge,description:`Alias on ${Se.title}`,searchText:`${Ge} ${Se.title} ${Se.slug}`,badge:e.jsx(L,{className:"bg-white/[0.08] text-white/80",children:Ge}),menuBadge:e.jsx(L,{className:"bg-white/[0.08] text-white/80",children:Ge})})}for(const Se of Li(o.aliasesText))te.set(Se.toLowerCase(),{value:Se,label:Se,description:"Wiki alias",searchText:Se,badge:e.jsx(L,{className:"bg-white/[0.08] text-white/80",children:Se}),menuBadge:e.jsx(L,{className:"bg-white/[0.08] text-white/80",children:Se})});return Array.from(te.values()).sort((Se,he)=>Se.label.localeCompare(he.label))},[o.aliasesText,(X=O.data)==null?void 0:X.pages]),K=d.useMemo(()=>[{value:"index",label:"Home",description:"Top-level index page",searchText:"home index top level root"},..._.map(te=>({value:te.slug,label:te.title,description:te.summary||te.slug,searchText:`${te.title} ${te.slug} ${te.summary}`}))],[_]),Z=d.useMemo(()=>{const te=Yc(D);return te?_.filter(ce=>`${ce.title} ${ce.slug} ${ce.summary}`.toLowerCase().includes(te)).slice(0,12):_.slice(0,12)},[D,_]),U=d.useMemo(()=>{const te=t.snapshot.goals.map(De=>({value:zi("goal",De.id),label:De.title,description:De.description,searchText:`${De.title} ${De.description}`,kind:ga.goal})),ce=t.snapshot.dashboard.projects.map(De=>({value:zi("project",De.id),label:De.title,description:[De.goalTitle,De.description].filter(Boolean).join(" · "),searchText:`${De.title} ${De.goalTitle} ${De.description}`,kind:ga.project})),Se=t.snapshot.tasks.map(De=>({value:zi("task",De.id),label:De.title,description:De.owner||De.description,searchText:`${De.title} ${De.owner} ${De.description}`,kind:ga.task})),he=t.snapshot.strategies.map(De=>({value:zi("strategy",De.id),label:De.title,description:De.overview,searchText:`${De.title} ${De.overview} ${De.endStateDescription}`,kind:ga.strategy})),Ge=t.snapshot.habits.map(De=>({value:zi("habit",De.id),label:De.title,description:De.description,searchText:`${De.title} ${De.description}`,kind:ga.habit}));return[...te,...ce,...Se,...he,...Ge].sort((De,ue)=>De.label.localeCompare(ue.label))},[t.snapshot.dashboard.projects,t.snapshot.goals,t.snapshot.habits,t.snapshot.strategies,t.snapshot.tasks]),I=d.useMemo(()=>{const te=Yc(S);return te?U.filter(ce=>`${ce.label} ${ce.description??""} ${ce.searchText??""}`.toLowerCase().includes(te)).slice(0,12):U.slice(0,12)},[U,S]),G=d.useMemo(()=>{const te=t.snapshot.tags.map(he=>({label:he.name,description:`Forge ${he.kind} tag`,color:he.color})),ce=Li(o.tagsText).map(he=>({label:he,description:"Wiki tag"})),Se=new Map;return[...te,...ce].forEach(he=>{Se.set(he.label.toLowerCase(),he)}),YN(Array.from(Se.values()).sort((he,Ge)=>he.label.localeCompare(Ge.label)))},[o.tagsText,t.snapshot.tags]);function W(te){const ce=A.current;c(Se=>{const he=Se.contentMarkdown;if(!ce)return{...Se,contentMarkdown:`${he}${he.endsWith(`
|
|
48
|
-
`)?"":`
|
|
49
|
-
`}${te}`};const Ge=ce.selectionStart??he.length,De=ce.selectionEnd??he.length,ue=`${he.slice(0,Ge)}${te}${he.slice(De)}`;return requestAnimationFrame(()=>{ce.focus();const Fe=Ge+te.length;ce.setSelectionRange(Fe,Fe)}),{...Se,contentMarkdown:ue}})}const ne=xe({mutationFn:async te=>{const ce={kind:te.kind,title:te.title.trim(),slug:te.slug.trim()||ku(te.title),parentSlug:te.parentSlug&&te.parentSlug!=="none"?te.parentSlug:null,indexOrder:te.indexOrder,showInIndex:te.showInIndex,summary:te.summary.trim(),aliases:Li(te.aliasesText),contentMarkdown:te.contentMarkdown.trim(),author:te.author.trim()||null,tags:Li(te.tagsText),spaceId:z,frontmatter:HN(te.frontmatterText),links:te.linkedValues.map(Se=>WN(Se)).filter(Se=>Se!==null)};return te.pageId?Ig(te.pageId,ce):Fh(ce)},onSuccess:async te=>{await Promise.all([s.invalidateQueries({queryKey:["forge-wiki-pages"]}),s.invalidateQueries({queryKey:["forge-wiki-page"]}),s.invalidateQueries({queryKey:["forge-wiki-home"]}),s.invalidateQueries({queryKey:["forge-wiki-page-by-slug"]}),s.invalidateQueries({queryKey:["forge-wiki-tree"]})]),a({pathname:te.page.slug==="index"?"/wiki":`/wiki/page/${encodeURIComponent(te.page.slug)}`,search:`?spaceId=${encodeURIComponent(te.page.spaceId)}`})}});if(C.isLoading||n&&F.isLoading&&!k)return e.jsx(nt,{eyebrow:"Wiki editor",title:"Preparing the editor",description:"Loading the draft, hierarchy, and link helpers."});if(C.isError||F.isError||O.isError)return e.jsx(ze,{eyebrow:"Wiki editor",error:C.error??F.error??O.error,onRetry:()=>{C.refetch(),F.refetch(),O.refetch()}});if(n&&!((be=F.data)!=null&&be.page))return e.jsx(gt,{eyebrow:"Wiki editor",title:"Page not found",description:"This wiki entry does not exist anymore."});const de=[{kind:"wiki-link",icon:fs,label:"Wiki link"},{kind:"forge-link",icon:lh,label:"Forge link"},{kind:"infobox",icon:Xp,label:"Infobox"},{kind:"admonition",icon:Il,label:"Admonition"},{kind:"related",icon:Vp,label:"Related"},{kind:"media",icon:Jp,label:"Media"}],we=VN(o.contentMarkdown),Ne=o.contentMarkdown.length;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-4 sm:px-5 lg:px-6",children:e.jsxs("div",{className:"mx-auto flex w-full max-w-[1720px] flex-col gap-4",children:[e.jsx("section",{className:"wiki-frame px-4 py-3 sm:px-5",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-white/42",children:"Wiki editor"}),e.jsx("h1",{className:"mt-1 text-[1.25rem] font-semibold tracking-[-0.04em] text-white",children:o.pageId?"Edit page":"New page"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(Q,{variant:"secondary",size:"sm",className:"xl:hidden",onClick:()=>E(te=>!te),"aria-expanded":M,children:[M?e.jsx(Bn,{className:"size-3.5"}):e.jsx(Ji,{className:"size-3.5"}),"Metadata"]}),e.jsxs(Q,{variant:"secondary",size:"sm",onClick:()=>a(-1),children:[e.jsx(fn,{className:"size-3.5"}),"Back"]}),e.jsxs(Q,{size:"sm",pending:ne.isPending,pendingLabel:"Saving",disabled:!o.title.trim()||!o.contentMarkdown.trim(),onClick:()=>void ne.mutateAsync(o),children:[e.jsx(Yi,{className:"size-3.5"}),"Save page"]})]})]})}),e.jsxs("section",{className:"grid min-w-0 gap-4 xl:grid-cols-[minmax(19rem,23rem)_minmax(0,1fr)] xl:items-start",children:[e.jsx("aside",{className:re("order-2 min-w-0 xl:order-1 xl:block",M?"block":"hidden"),children:e.jsxs("section",{className:"wiki-frame px-4 py-4 sm:px-5 xl:sticky xl:top-[5.75rem]",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3 border-b border-white/8 pb-3",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-white/42",children:"Metadata"}),e.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-white/34",children:J})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Wiki space"}),e.jsxs("button",{type:"button",className:"flex min-h-[2.9rem] items-center justify-between gap-3 rounded-[18px] border border-white/8 bg-white/[0.04] px-3.5 text-[13px] text-white/82 transition hover:bg-white/[0.06] hover:text-white",onClick:()=>w(!0),children:[e.jsx("span",{className:"truncate",children:J}),e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Change"})]})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Title"}),e.jsx(le,{value:o.title,onChange:te=>c(ce=>({...ce,title:te.target.value})),placeholder:"Page title"})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Slug"}),e.jsx(le,{value:o.slug,onChange:te=>c(ce=>({...ce,slug:te.target.value})),placeholder:"page-slug"})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Summary"}),e.jsx(Me,{value:o.summary,onChange:te=>c(ce=>({...ce,summary:te.target.value})),rows:4,placeholder:"Short summary"})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Tags"}),e.jsx(et,{options:G,selectedValues:Li(o.tagsText),onChange:te=>c(ce=>({...ce,tagsText:te.join(", ")})),placeholder:"Search or add tags",emptyMessage:"No tags yet.",createLabel:"Add tag",onCreate:async te=>{const ce=te.trim();return{value:ce,label:ce,description:"Wiki tag",searchText:ce,badge:e.jsx(L,{className:"bg-white/[0.08] text-white/80",children:ce}),menuBadge:e.jsx(L,{className:"bg-white/[0.08] text-white/80",children:ce})}}})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Forge entities"}),e.jsx(et,{options:U,selectedValues:o.linkedValues,onChange:te=>c(ce=>({...ce,linkedValues:te})),placeholder:"Search Forge entities"})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Aliases"}),e.jsx(et,{options:B,selectedValues:Li(o.aliasesText),onChange:te=>c(ce=>({...ce,aliasesText:te.join(", ")})),placeholder:"Search or add aliases",emptyMessage:"No aliases yet.",createLabel:"Add alias",onCreate:async te=>{const ce=te.trim();return{value:ce,label:ce,description:"Wiki alias",searchText:ce,badge:e.jsx(L,{className:"bg-white/[0.08] text-white/80",children:ce}),menuBadge:e.jsx(L,{className:"bg-white/[0.08] text-white/80",children:ce})}}})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Author"}),e.jsx(le,{value:o.author,onChange:te=>c(ce=>({...ce,author:te.target.value})),placeholder:"Optional author"})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("label",{className:"grid gap-1.5",children:[e.jsxs("span",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.16em] text-white/42",children:[e.jsx("span",{children:"Parent"}),e.jsx(it,{content:"Choose the page that should own this page in the wiki tree.",label:"Explain parent page"})]}),e.jsx(et,{options:K,selectedValues:o.parentSlug?[o.parentSlug]:[],onChange:te=>c(ce=>({...ce,parentSlug:te[0]??null})),placeholder:"Search parent page",emptyMessage:"No matching pages.",className:"[&_.max-w-\\\\[16rem\\\\]]:max-w-full"})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsxs("span",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.16em] text-white/42",children:[e.jsx("span",{children:"Order"}),e.jsx(it,{content:"Lower numbers appear earlier within the same parent page.",label:"Explain page order"})]}),e.jsx(le,{type:"number",value:String(o.indexOrder),onChange:te=>c(ce=>({...ce,indexOrder:Number(te.target.value||0)}))})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-[18px] border border-white/8 bg-white/[0.03] px-3.5 py-3 text-[13px] text-white/74",children:[e.jsx("input",{type:"checkbox",className:"mt-0.5",checked:o.showInIndex,onChange:te=>c(ce=>({...ce,showInIndex:te.target.checked}))}),e.jsx("span",{children:"Show in index"})]})]})]})}),e.jsxs("div",{className:"order-1 grid min-w-0 gap-4 xl:order-2",children:[e.jsxs("section",{className:"wiki-frame overflow-hidden",children:[e.jsxs("div",{className:"flex min-h-12 w-full flex-wrap items-center justify-between gap-3 border-b border-white/8 bg-[rgba(10,16,30,0.5)] px-3 py-2 sm:px-4",children:[e.jsx("div",{className:"flex min-w-0 flex-wrap items-center justify-start gap-1.5",children:de.map(te=>e.jsx(JN,{icon:te.icon,label:te.label,onClick:()=>{v(te.kind),f(""),m(""),j(""),p("")}},te.kind))}),e.jsx("div",{className:"ml-auto flex min-w-0 flex-wrap items-center justify-end gap-3 pr-1",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-[11px] uppercase tracking-[0.14em] text-white/36",children:[e.jsxs("span",{children:[we.toLocaleString()," words"]}),e.jsxs("span",{children:[Ne.toLocaleString()," chars"]})]})})]}),e.jsx("div",{className:"bg-[linear-gradient(180deg,rgba(8,13,24,0.98),rgba(9,14,26,0.94))]",children:e.jsx(Me,{ref:A,value:o.contentMarkdown,onChange:te=>c(ce=>({...ce,contentMarkdown:te.target.value})),rows:26,className:"min-h-[38rem] resize-y rounded-none border-0 bg-transparent px-5 py-4 font-mono text-[13px] leading-6 text-white shadow-none outline-none focus-visible:ring-0 sm:min-h-[44rem] sm:px-6",placeholder:"Write the page in Markdown"})})]}),e.jsxs("section",{className:"wiki-frame overflow-hidden",children:[e.jsx("div",{className:"border-b border-white/8 px-4 py-3 sm:px-6",children:e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-white/42",children:"Preview"})}),e.jsx("div",{className:"px-4 py-5 sm:px-6",children:e.jsx("div",{className:"wiki-reading-copy wiki-reading-flow mx-auto max-w-[76rem]",children:e.jsx(yu,{markdown:o.contentMarkdown,spaceId:z})})})]})]})]})]})}),e.jsx(Di,{open:x==="wiki-link",onOpenChange:te=>!te&&v(null),title:"Insert wiki link",description:"Search pages.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx(le,{autoFocus:!0,value:D,onChange:te=>j(te.target.value),placeholder:"Search wiki pages",className:"h-11 rounded-2xl border-white/10 bg-white/[0.04] text-[14px] text-white placeholder:text-white/28"}),e.jsx("div",{className:"grid max-h-[22rem] gap-2 overflow-y-auto",children:Z.length>0?Z.map(te=>e.jsxs("button",{type:"button",className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-3 text-left transition hover:bg-white/[0.06]",onClick:()=>{W(`[[${te.slug}]]`),v(null),j("")},children:[e.jsx("div",{className:"text-[14px] font-semibold text-white",children:te.title}),e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/46",children:te.slug}),te.summary?e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/56",children:te.summary}):null]},te.id)):e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 px-4 py-8 text-center text-[13px] text-white/42",children:"No pages match this search."})})]})}),e.jsx(Di,{open:x==="forge-link",onOpenChange:te=>!te&&v(null),title:"Insert Forge link",description:"Search Forge entities.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx(le,{autoFocus:!0,value:S,onChange:te=>p(te.target.value),placeholder:"Search Forge entities",className:"h-11 rounded-2xl border-white/10 bg-white/[0.04] text-[14px] text-white placeholder:text-white/28"}),e.jsx("div",{className:"grid max-h-[22rem] gap-2 overflow-y-auto",children:I.length>0?I.map(te=>e.jsxs("button",{type:"button",className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-3 text-left transition hover:bg-white/[0.06]",onClick:()=>{const[ce,Se]=te.value.split(":");W(`[[forge:${ce}:${Se}]]`),v(null),p("")},children:[e.jsx("div",{className:"text-[14px] font-semibold text-white",children:te.label}),te.description?e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/56",children:te.description}):null]},te.value)):e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 px-4 py-8 text-center text-[13px] text-white/42",children:"No entities match this search."})})]})}),e.jsx(Di,{open:x==="infobox",onOpenChange:te=>!te&&v(null),title:"Insert infobox",description:"Create the article metadata box rendered beside the intro.",children:e.jsx("div",{className:"grid gap-3",children:e.jsx(Q,{onClick:()=>{W(`:::forge-infobox
|
|
50
|
-
Title: ${o.title||"Article title"}
|
|
51
|
-
Summary: ${o.summary||"Short summary"}
|
|
52
|
-
Tags: ${o.tagsText||"tag-one, tag-two"}
|
|
53
|
-
Related: [[index|Home]]
|
|
54
|
-
:::
|
|
55
|
-
`),v(null)},children:"Insert infobox"})})}),e.jsx(Di,{open:x==="admonition",onOpenChange:te=>!te&&v(null),title:"Insert admonition",description:"Add a callout block inside the article.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("select",{className:XN,value:u,onChange:te=>f(te.target.value),children:[e.jsx("option",{value:"",children:"Select type"}),e.jsx("option",{value:"note",children:"Note"}),e.jsx("option",{value:"tip",children:"Tip"}),e.jsx("option",{value:"warning",children:"Warning"}),e.jsx("option",{value:"danger",children:"Danger"})]}),e.jsx(Me,{value:h,onChange:te=>m(te.target.value),rows:4,placeholder:"Admonition text"}),e.jsx(Q,{disabled:!u||!h.trim(),onClick:()=>{W(`:::${u}
|
|
56
|
-
${h.trim()}
|
|
57
|
-
:::
|
|
58
|
-
`),v(null)},children:"Insert admonition"})]})}),e.jsx(Di,{open:x==="related",onOpenChange:te=>!te&&v(null),title:"Insert related block",description:"Add an explicit related-pages block.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx(Me,{value:h,onChange:te=>m(te.target.value),rows:5,placeholder:`[[page-one]]
|
|
59
|
-
[[page-two|Readable label]]`}),e.jsx(Q,{disabled:!h.trim(),onClick:()=>{W(`:::forge-related
|
|
60
|
-
${h.trim()}
|
|
61
|
-
:::
|
|
62
|
-
`),v(null)},children:"Insert related block"})]})}),e.jsx(Di,{open:x==="media",onOpenChange:te=>!te&&v(null),title:"Insert media block",description:"Reference media or assets in a structured block.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx(Me,{value:h,onChange:te=>m(te.target.value),rows:5,placeholder:`Image: /path/to/file.png
|
|
63
|
-
Caption: Inspiration frame`}),e.jsx(Q,{disabled:!h.trim(),onClick:()=>{W(`:::forge-media
|
|
64
|
-
${h.trim()}
|
|
65
|
-
:::
|
|
66
|
-
`),v(null)},children:"Insert media block"})]})}),e.jsx(Et,{open:b,onOpenChange:w,children:e.jsxs(Lt,{children:[e.jsx(Dt,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.72)] backdrop-blur-sm"}),e.jsxs($t,{className:"fixed left-1/2 top-[14vh] z-50 w-[min(28rem,calc(100vw-1.5rem))] -translate-x-1/2 rounded-[28px] border border-white/10 bg-[rgba(10,15,28,0.97)] p-4 shadow-[0_32px_90px_rgba(0,0,0,0.45)] sm:p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(Ot,{className:"font-display text-[1.2rem] tracking-[-0.04em] text-white",children:"Choose wiki space"}),e.jsx(qt,{className:"mt-1 text-[13px] leading-6 text-white/56",children:"Save this page into a different wiki space."})]}),e.jsx(Ft,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white","aria-label":"Close space picker",children:e.jsx(mt,{className:"size-4"})})})]}),e.jsx("div",{className:"mt-4 grid gap-2",children:(Ie=C.data)==null?void 0:Ie.settings.spaces.map(te=>{const ce=te.id===z;return e.jsxs("button",{type:"button",className:ce?"flex items-center justify-between gap-3 rounded-[22px] border border-[rgba(192,193,255,0.22)] bg-[rgba(192,193,255,0.12)] px-4 py-3 text-left text-white transition":"flex items-center justify-between gap-3 rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-3 text-left text-white/78 transition hover:bg-white/[0.06] hover:text-white",onClick:()=>{const Se=new URLSearchParams(r);Se.set("spaceId",te.id),l(Se,{replace:!0}),w(!1)},children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[14px] font-semibold",children:te.label}),e.jsx("span",{className:"mt-1 block text-[12px] leading-5 text-white/52",children:te.description||`/${te.slug}`})]}),ce?e.jsx(Vi,{className:"size-4 shrink-0 text-[var(--primary)]"}):null]},te.id)})})]})]})})]})}function ZN(){var x;const{t}=lt(),s=We(),i=fe({queryKey:["forge-weekly-review"],queryFn:qg}),a=xe({mutationFn:Bg,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"]})])}}),n=(x=i.data)==null?void 0:x.review;if(i.isLoading)return e.jsx(It,{});if(i.isError)return e.jsx(ze,{eyebrow:t("common.weeklyReview.heroEyebrow"),error:i.error,onRetry:()=>void i.refetch()});if(!n)return e.jsx(ze,{eyebrow:t("common.weeklyReview.heroEyebrow"),error:new Error("Forge returned an empty weekly review payload."),onRetry:()=>void i.refetch()});const r=n.wins[0]??null,l=n.calibration.find(v=>v.mode==="recover")??n.calibration[0]??null,o=n.calibration.find(v=>v.mode==="accelerate")??n.calibration[0]??null,c=[{id:"week",label:"This week",title:`${n.momentumSummary.totalXp} XP with ${n.momentumSummary.focusHours} focus hours`,detail:`Peak window: ${n.momentumSummary.peakWindow}. Efficiency score is holding at ${n.momentumSummary.efficiencyScore}.`,badge:n.windowLabel},{id:"wins",label:"Wins",title:(r==null?void 0:r.title)??t("common.weeklyReview.noWin"),detail:(r==null?void 0:r.summary)??t("common.weeklyReview.noWinDetail"),badge:r?`+${r.rewardXp} xp`:`${n.wins.length} wins`},{id:"recovery",label:"Recovery",title:(l==null?void 0:l.title)??t("common.weeklyReview.noRecovery"),detail:(l==null?void 0:l.note)??t("common.weeklyReview.noRecoveryDetail"),badge:(l==null?void 0:l.mode)??"maintain"},{id:"next-intent",label:"Next intent",title:(o==null?void 0:o.title)??n.reward.title,detail:(o==null?void 0:o.note)??n.reward.summary,badge:`+${n.reward.rewardXp} xp`}];return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(qe,{title:"Weekly Review",description:`${n.windowLabel}. ${t("common.weeklyReview.heroDescription")}`,badge:`${n.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(ae,{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(Kn,{width:"100%",height:"100%",children:e.jsxs(hx,{data:n.chart,children:[e.jsx(Un,{dataKey:"label",tick:{fill:"rgba(255,255,255,0.42)",fontSize:11}}),e.jsx(Qn,{hide:!0}),e.jsx(mx,{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:n.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:n.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:n.momentumSummary.peakWindow})]})]})]}),e.jsxs(ae,{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:n.calibration.map(v=>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:v.title}),e.jsx(L,{className:"max-w-[9rem] shrink-0 self-start",children:v.mode})]}),e.jsx("div",{className:"mt-3 text-sm text-white/58",children:v.note})]},v.id))})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(ae,{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:n.wins.map(v=>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:v.title}),e.jsxs(L,{className:"max-w-[8rem] shrink-0 self-start text-emerald-300",children:["+",v.rewardXp," xp"]})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:v.summary})]},v.id))})]}),e.jsxs(ae,{children:[e.jsx("h2",{className:"font-display text-3xl text-white",children:n.reward.title}),e.jsx("p",{className:"mt-3 text-sm leading-7 text-white/60",children:n.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:["+",n.reward.rewardXp," XP"]})]}),e.jsx(Q,{className:"mt-4 w-full",disabled:n.completion.finalized,pending:a.isPending,pendingLabel:t("common.weeklyReview.finalizePending"),onClick:async()=>{await a.mutateAsync()},children:n.completion.finalized?t("common.weeklyReview.finalized"):t("common.weeklyReview.finalize")}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:n.completion.finalized?`${t("common.weeklyReview.finalizedDetail")} ${n.completion.finalizedBy?`By ${n.completion.finalizedBy}. `:""}${n.completion.finalizedAt?new Date(n.completion.finalizedAt).toLocaleString():""}`.trim():n.reward.summary})]})]})]}),e.jsx(Km,{eyebrow:t("common.weeklyReview.summaryEyebrow"),title:t("common.weeklyReview.summaryTitle"),description:t("common.weeklyReview.summaryDescription"),items:c})]})}const eh="workbench";function ek(){const t=Je(),s=[{id:"hero",title:"Workbench",description:"Custom view with utility widgets and AI processors.",defaultWidth:12,defaultHeight:1,removable:!1,surfaceChrome:"none",defaultTitleVisible:!1,defaultDescriptionVisible:!1,processorCapability:{label:"Workbench summary",mode:"content",metadata:{source:"hero"}},render:()=>e.jsx(qe,{title:"Workbench",titleText:"Workbench",description:"This surface supports utility widgets, AI processor widgets, and explicit widget-to-processor graph links.",badge:"surface runtime"})},{id:"time",title:"Clock",description:"Live time widget.",defaultWidth:3,defaultHeight:2,processorCapability:{label:"Time context",mode:"content",metadata:{widgetType:"time"}},render:({compact:i})=>e.jsx(ro,{compact:i})},{id:"weather",title:"Weather",description:"Location-based weather widget.",defaultWidth:3,defaultHeight:2,processorCapability:{label:"Weather context",mode:"content",metadata:{widgetType:"weather"}},render:({compact:i})=>e.jsx(co,{compact:i})},{id:"mini-calendar",title:"Mini calendar",description:"Compact month view.",defaultWidth:4,defaultHeight:3,processorCapability:{label:"Calendar context",mode:"content",metadata:{widgetType:"mini-calendar"}},render:({compact:i})=>e.jsx(lo,{compact:i})},{id:"spotify",title:"Spotify",description:"Pinned music link.",defaultWidth:5,defaultHeight:2,processorCapability:{label:"Spotify link",mode:"content",metadata:{widgetType:"spotify"}},render:()=>e.jsx(oo,{surfaceId:eh})},{id:"quick-capture",title:"Quick capture",description:"Save a note or wiki page from a simple editor.",defaultWidth:7,defaultHeight:4,processorCapability:{label:"Quick capture actions",mode:"mcp",metadata:{widgetType:"quick-capture",noteEndpoint:"/api/v1/notes",wikiEndpoint:"/api/v1/wiki/pages"}},render:({compact:i})=>{var a;return e.jsx(ho,{compact:i,defaultUserId:t.selectedUserIds[0]??((a=t.snapshot.users[0])==null?void 0:a.id)??null})}}];return e.jsx(_a,{surfaceId:eh,baseWidgets:s})}function tk(){const t=fi();return d.useEffect(()=>{const s=`${t.pathname}${t.search}${t.hash}`,i=Mx({scope:"frontend_runtime",route:s}),a=r=>{i({level:"error",eventKey:"window_error",message:r.message||"Unhandled browser error",functionName:"window.onerror",details:{fileName:r.filename||null,line:r.lineno||null,column:r.colno||null,error:r.error??null}})},n=r=>{i({level:"error",eventKey:"unhandled_rejection",message:"Unhandled promise rejection",functionName:"window.onunhandledrejection",details:{reason:r.reason??null}})};return window.addEventListener("error",a),window.addEventListener("unhandledrejection",n),()=>{window.removeEventListener("error",a),window.removeEventListener("unhandledrejection",n)}},[t.hash,t.pathname,t.search]),d.useEffect(()=>{const s=`${t.pathname}${t.search}${t.hash}`;kn({level:"info",scope:"frontend_navigation",eventKey:"route_view",message:`Viewed route ${t.pathname}`,route:s,functionName:"DiagnosticsBootstrap.routeView",details:{pathname:t.pathname,search:t.search||null,hash:t.hash||null}})},[t.hash,t.pathname,t.search]),null}function sk(){function t(s,i,a,n){return n}return e.jsxs(e.Fragment,{children:[e.jsx(tk,{}),e.jsxs(Yp,{children:[e.jsxs(Re,{element:e.jsx(Ev,{}),children:[e.jsx(Re,{index:!0,element:e.jsx(or,{to:"/overview",replace:!0})}),e.jsx(Re,{path:"overview",element:e.jsx(Hy,{})}),e.jsx(Re,{path:"goals",element:t("goals-index","Goals","Goal planning and long-horizon direction.",e.jsx(uw,{}))}),e.jsx(Re,{path:"habits",element:t("habits-index","Habits","Recurring commitments, streaks, and check-ins.",e.jsx(Iw,{}))}),e.jsx(Re,{path:"goals/:goalId",element:t("goal-detail","Goal detail","Goal detail, progress, and linked execution context.",e.jsx(hw,{}))}),e.jsx(Re,{path:"projects",element:e.jsx(n0,{})}),e.jsx(Re,{path:"projects/:projectId",element:t("project-detail","Project detail","Project detail, tasks, and execution health.",e.jsx(e0,{}))}),e.jsx(Re,{path:"strategies",element:t("strategies-index","Strategies","Strategy graphs and long-range execution plans.",e.jsx(v0,{}))}),e.jsx(Re,{path:"strategies/:strategyId",element:t("strategy-detail","Strategy detail","Strategy DAG detail, targets, and progress.",e.jsx(C0,{}))}),e.jsx(Re,{path:"preferences",element:t("preferences-index","Preferences","Preference profiles, pairwise judgments, and model state.",e.jsx(D0,{}))}),e.jsx(Re,{path:"campaigns",element:e.jsx(or,{to:"/projects",replace:!0})}),e.jsx(Re,{path:"calendar",element:t("calendar-index","Calendar","Calendar planning, timeboxes, and provider sync.",e.jsx(Gv,{}))}),e.jsx(Re,{path:"connectors",element:e.jsx(iw,{})}),e.jsx(Re,{path:"connectors/:connectorId",element:e.jsx(sw,{})}),e.jsx(Re,{path:"movement",element:t("movement-index","Movement","Movement traces, places, and trip evidence.",e.jsx(Sy,{}))}),e.jsx(Re,{path:"sleep",element:t("sleep-index","Sleep","Sleep sessions, health context, and recovery trends.",e.jsx(dN,{}))}),e.jsx(Re,{path:"sports",element:t("sports-index","Sports","Fitness, workouts, and sports context.",e.jsx(pN,{}))}),e.jsx(Re,{path:"psyche",element:e.jsx(Q0,{})}),e.jsx(Re,{path:"psyche/values",element:t("psyche-values","Psyche values","Values and linked goal context.",e.jsx(d1,{}))}),e.jsx(Re,{path:"psyche/patterns",element:t("psyche-patterns","Psyche patterns","Behavior patterns and recurring loops.",e.jsx(vj,{}))}),e.jsx(Re,{path:"psyche/questionnaires",element:t("psyche-questionnaires","Questionnaires","Questionnaire library and recent runs.",e.jsx(Fj,{}))}),e.jsx(Re,{path:"psyche/questionnaires/new",element:t("psyche-questionnaire-new","New questionnaire","Questionnaire builder workspace.",e.jsx(Ic,{}))}),e.jsx(Re,{path:"psyche/questionnaires/:instrumentId",element:t("psyche-questionnaire-detail","Questionnaire detail","Questionnaire detail and scores.",e.jsx(kj,{}))}),e.jsx(Re,{path:"psyche/questionnaires/:instrumentId/edit",element:t("psyche-questionnaire-edit","Edit questionnaire","Questionnaire builder workspace.",e.jsx(Ic,{}))}),e.jsx(Re,{path:"psyche/questionnaires/:instrumentId/take",element:t("psyche-questionnaire-run","Take questionnaire","Questionnaire runner and answers.",e.jsx(Dj,{}))}),e.jsx(Re,{path:"psyche/questionnaire-runs/:runId",element:t("psyche-questionnaire-run-detail","Questionnaire run detail","Questionnaire result review.",e.jsx(Sj,{}))}),e.jsx(Re,{path:"psyche/self-observation",element:t("psyche-self-observation","Self observation","Self-observation notes and reflective tracking.",e.jsx(n1,{}))}),e.jsx(Re,{path:"psyche/behaviors",element:t("psyche-behaviors","Behaviors","Behavior records and linked evidence.",e.jsx(ij,{}))}),e.jsx(Re,{path:"psyche/reports",element:t("psyche-reports","Reports","Trigger and reflective report review.",e.jsx(Gj,{}))}),e.jsx(Re,{path:"psyche/reports/:reportId",element:t("psyche-report-detail","Report detail","Detailed reflective report view.",e.jsx(Wj,{}))}),e.jsx(Re,{path:"psyche/goal-map",element:t("psyche-goal-map","Goal map","Goal-to-values relationship map.",e.jsx(aj,{}))}),e.jsx(Re,{path:"psyche/schemas-beliefs",element:t("psyche-schemas-beliefs","Schemas and beliefs","Beliefs, schemas, and linked patterns.",e.jsx(l1,{}))}),e.jsx(Re,{path:"psyche/modes",element:t("psyche-modes","Modes","Mode profiles and guides.",e.jsx(mj,{}))}),e.jsx(Re,{path:"psyche/modes/guide",element:t("psyche-mode-guide","Mode guide","Guided mode session flow.",e.jsx(oj,{}))}),e.jsx(Re,{path:"kanban",element:t("kanban-index","Kanban","Task board execution surface.",e.jsx(Xw,{}))}),e.jsx(Re,{path:"notes",element:t("notes-index","Notes","Notes, evidence, and writing surfaces.",e.jsx(Ly,{}))}),e.jsx(Re,{path:"wiki",element:t("wiki-index","Wiki","Wiki memory search and page navigation.",e.jsx(Vc,{}))}),e.jsx(Re,{path:"wiki/ingest-history",element:t("wiki-ingest-history","Wiki ingest history","Ingest jobs and processing history.",e.jsx(QN,{}))}),e.jsx(Re,{path:"wiki/page/:slug",element:t("wiki-page-detail","Wiki page","Wiki page detail and backlinks.",e.jsx(Vc,{}))}),e.jsx(Re,{path:"wiki/new",element:t("wiki-new","New wiki page","Wiki editor for new pages.",e.jsx(Zc,{}))}),e.jsx(Re,{path:"wiki/edit/:pageId",element:t("wiki-edit","Edit wiki page","Wiki editor for existing pages.",e.jsx(Zc,{}))}),e.jsx(Re,{path:"today",element:e.jsx(kN,{})}),e.jsx(Re,{path:"workbench",element:e.jsx(ek,{})}),e.jsx(Re,{path:"activity",element:t("activity-index","Activity","Activity log and event history.",e.jsx($v,{}))}),e.jsx(Re,{path:"insights",element:t("insights-index","Insights","Insight review and decisions.",e.jsx(Bw,{}))}),e.jsx(Re,{path:"review/weekly",element:t("weekly-review","Weekly review","Weekly review workflow and closeout.",e.jsx(ZN,{}))}),e.jsx(Re,{path:"settings",element:t("settings-index","Settings","Operator settings and runtime configuration.",e.jsx(m1,{}))}),e.jsx(Re,{path:"settings/users",element:t("settings-users","Settings users","User directory and ownership settings.",e.jsx(aN,{}))}),e.jsx(Re,{path:"settings/calendar",element:t("settings-calendar","Settings calendar","Calendar provider settings and sync.",e.jsx(T1,{}))}),e.jsx(Re,{path:"settings/mobile",element:t("settings-mobile","Settings mobile","Mobile companion settings and pairing.",e.jsx(A1,{}))}),e.jsx(Re,{path:"settings/models",element:t("settings-models","Settings models","Model connections and defaults.",e.jsx(L1,{}))}),e.jsx(Re,{path:"settings/agents",element:t("settings-agents","Settings agents","Agent tokens and runtime access.",e.jsx(f1,{}))}),e.jsx(Re,{path:"settings/rewards",element:t("settings-rewards","Settings rewards","Rewards and XP rule settings.",e.jsx(G1,{}))}),e.jsx(Re,{path:"settings/wiki",element:t("settings-wiki","Settings wiki","Wiki ingestion and profile settings.",e.jsx(c0,{}))}),e.jsx(Re,{path:"settings/logs",element:t("settings-logs","Settings logs","Diagnostics and event logs.",e.jsx(K1,{}))}),e.jsx(Re,{path:"settings/bin",element:t("settings-bin","Settings bin","Deleted entity recovery.",e.jsx(w1,{}))}),e.jsx(Re,{path:"tasks/:taskId",element:t("task-detail","Task detail","Task detail, timer, and notes.",e.jsx(xN,{}))})]}),e.jsx(Re,{path:"*",element:e.jsx(or,{to:"/overview",replace:!0})})]})]})}const ik=new Zp({defaultOptions:{queries:{staleTime:2e4,refetchOnWindowFocus:!1}}});ex.createRoot(document.getElementById("root")).render(e.jsx(tx.StrictMode,{children:e.jsx(sx,{client:ik,children:e.jsx(ix,{basename:Ix("/forge/"),children:e.jsx(sk,{})})})}));
|
|
67
|
-
//# sourceMappingURL=index-CFCKDIMH.js.map
|