forge-openclaw-plugin 0.2.100 → 0.2.101

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/dist/assets/{activity-page-5oyCFOns.js → activity-page-CpjuNSHw.js} +1 -1
  2. package/dist/assets/{ai-surface-workspace-qgk_B57-.js → ai-surface-workspace-DEAFZruS.js} +1 -1
  3. package/dist/assets/{atlas-panel-rfH2qOez.js → atlas-panel-CdVNPotj.js} +1 -1
  4. package/dist/assets/{calendar-page-Bo2iua-a.js → calendar-page-DNNt6lfz.js} +1 -1
  5. package/dist/assets/{calendar-rules-DA1g3QUk.js → calendar-rules-DNJFNsxi.js} +1 -1
  6. package/dist/assets/{calendar-week-toolbar-DU1Q4RYj.js → calendar-week-toolbar-BbPwYeN0.js} +1 -1
  7. package/dist/assets/{companion-sync-lab-page-CosNknOK.js → companion-sync-lab-page-KxEDigM6.js} +1 -1
  8. package/dist/assets/{daily-metrics-dashboard-LjuGAB3f.js → daily-metrics-dashboard-B3cqJgDt.js} +1 -1
  9. package/dist/assets/{entity-note-count-link-BmGDB572.js → entity-note-count-link-DrhjJZ4i.js} +1 -1
  10. package/dist/assets/{entity-notes-surface-DgEgicaE.js → entity-notes-surface-CkcRsKJQ.js} +1 -1
  11. package/dist/assets/{execution-board-CDRXQB85.js → execution-board-D07gOocB.js} +1 -1
  12. package/dist/assets/{faceted-token-search-CE1YauRd.js → faceted-token-search-BxRRcM3q.js} +1 -1
  13. package/dist/assets/{flagship-signal-deck-DDds90Gl.js → flagship-signal-deck-cmy82b8_.js} +1 -1
  14. package/dist/assets/{floating-action-menu-CJkI2iFy.js → floating-action-menu-Fs_ZiUMo.js} +1 -1
  15. package/dist/assets/{goal-detail-page-cJvHaLMQ.js → goal-detail-page-CqLiNz4f.js} +1 -1
  16. package/dist/assets/{goals-page-f_39hvUV.js → goals-page-BTk7mg_T.js} +1 -1
  17. package/dist/assets/{habits-page-DKb96_mj.js → habits-page-BJxagdzx.js} +1 -1
  18. package/dist/assets/{index-BHTUu_4M.js → index-CF4J4R9L.js} +2 -2
  19. package/dist/assets/{insight-flow-dialog-pzAzyayN.js → insight-flow-dialog-8f3D0GuC.js} +1 -1
  20. package/dist/assets/{insights-page-Dc9oFltJ.js → insights-page-D6rOa7uk.js} +1 -1
  21. package/dist/assets/{kanban-page-JAxerYh6.js → kanban-page-XQ7Se6dH.js} +1 -1
  22. package/dist/assets/{knowledge-graph-page-UQ3skqEi.js → knowledge-graph-page-BtAg8iv3.js} +1 -1
  23. package/dist/assets/{life-force-page-BGDbQuVh.js → life-force-page-Dy0JTS2G.js} +1 -1
  24. package/dist/assets/{life-force-workspace-B1fYSXRC.js → life-force-workspace-OfyB9HJM.js} +1 -1
  25. package/dist/assets/{metric-tile-DX6TclqM.js → metric-tile-DKpo-8xw.js} +1 -1
  26. package/dist/assets/{movement-page-6HP6nGJx.js → movement-page-Bg_T_Stx.js} +1 -1
  27. package/dist/assets/{note-markdown-DiW2-5d3.js → note-markdown-N-uxD3Xt.js} +1 -1
  28. package/dist/assets/{note-tags-input-DDLXf54U.js → note-tags-input-Cdu7wiw6.js} +1 -1
  29. package/dist/assets/{notes-page-BuguDjhz.js → notes-page-CKXnF_KU.js} +1 -1
  30. package/dist/assets/{open-in-graph-button-Cg5VrKsC.js → open-in-graph-button-IXe9SGth.js} +1 -1
  31. package/dist/assets/{orbit-map-GD05-0oS.js → orbit-map-Dzi6KliQ.js} +1 -1
  32. package/dist/assets/{overview-page-DuOs2OCB.js → overview-page-1miYqaVS.js} +1 -1
  33. package/dist/assets/{page-hero-CQWo1Mm_.js → page-hero-DRy5b2MU.js} +1 -1
  34. package/dist/assets/{pill-cluster-BJogDRDJ.js → pill-cluster-C9QczVJ2.js} +1 -1
  35. package/dist/assets/{preference-entity-handoff-button-D4WAs9pC.js → preference-entity-handoff-button-5PzUn42S.js} +1 -1
  36. package/dist/assets/{preferences-page-BaJTMU1I.js → preferences-page-DtNaF5Q3.js} +1 -1
  37. package/dist/assets/{project-collections-DvaX20q_.js → project-collections-xPz2mlRr.js} +1 -1
  38. package/dist/assets/{project-detail-page-drPIFZGb.js → project-detail-page-BXK5-4xW.js} +1 -1
  39. package/dist/assets/{project-management-hierarchy-page-BUbRXvny.js → project-management-hierarchy-page-DtRpMABw.js} +1 -1
  40. package/dist/assets/{project-management-section-nav-C2Ud8Zdd.js → project-management-section-nav-P3ixzPa-.js} +1 -1
  41. package/dist/assets/{projects-page-BGzEZUtg.js → projects-page-C5ViRuf4.js} +1 -1
  42. package/dist/assets/{psyche-behaviors-page-Dmm_Io9D.js → psyche-behaviors-page-Dco46sC4.js} +1 -1
  43. package/dist/assets/{psyche-flashcards-page-BgNKJ6QJ.js → psyche-flashcards-page-ZcoEB8gV.js} +1 -1
  44. package/dist/assets/{psyche-goal-map-page-DXJs98Vr.js → psyche-goal-map-page-CLBAQOI0.js} +1 -1
  45. package/dist/assets/{psyche-graph-CFgs_Bqc.js → psyche-graph-k4tX2tdp.js} +1 -1
  46. package/dist/assets/{psyche-metrics-page-zYTJDbyZ.js → psyche-metrics-page-CuR9oqEy.js} +1 -1
  47. package/dist/assets/{psyche-mode-guide-page-XPgRfCOf.js → psyche-mode-guide-page-hIVXcCnE.js} +1 -1
  48. package/dist/assets/{psyche-modes-page-B-GA8oRF.js → psyche-modes-page-0lYtBlhO.js} +1 -1
  49. package/dist/assets/{psyche-page--r6a3e1t.js → psyche-page-VZ9k9ISp.js} +1 -1
  50. package/dist/assets/{psyche-patterns-page-BM5-3bMm.js → psyche-patterns-page-gx5nmdGq.js} +1 -1
  51. package/dist/assets/{psyche-questionnaire-builder-page-CJshQ-mg.js → psyche-questionnaire-builder-page-Bn0TOISd.js} +1 -1
  52. package/dist/assets/{psyche-questionnaire-detail-page-USmR5G5A.js → psyche-questionnaire-detail-page-CmVzSd_s.js} +1 -1
  53. package/dist/assets/{psyche-questionnaire-run-detail-page-D7iBCmTi.js → psyche-questionnaire-run-detail-page-BsMbmXCG.js} +1 -1
  54. package/dist/assets/{psyche-questionnaire-run-page-Cpil-kDh.js → psyche-questionnaire-run-page-CgkRL2vi.js} +1 -1
  55. package/dist/assets/{psyche-questionnaires-page-C-_y3VwS.js → psyche-questionnaires-page-D7V8uLXM.js} +1 -1
  56. package/dist/assets/{psyche-report-detail-page--dkSPRaj.js → psyche-report-detail-page-OlFq57eL.js} +1 -1
  57. package/dist/assets/{psyche-reports-page-CUaOXmIN.js → psyche-reports-page-dVUZjna1.js} +1 -1
  58. package/dist/assets/{psyche-schemas-beliefs-page-BX6xaap3.js → psyche-schemas-beliefs-page-BCgc8FUd.js} +1 -1
  59. package/dist/assets/{psyche-screen-time-page-CAAI4mD7.js → psyche-screen-time-page-B_6BT_WN.js} +1 -1
  60. package/dist/assets/{psyche-self-observation-page-BZ6FLuwa.js → psyche-self-observation-page-CEG5mluK.js} +1 -1
  61. package/dist/assets/{psyche-values-page-yEV6MGt8.js → psyche-values-page-DRbRfEd6.js} +1 -1
  62. package/dist/assets/{report-chain-fields-fZ8Xd4H6.js → report-chain-fields-CALCV3V5.js} +1 -1
  63. package/dist/assets/{rewards-page-C2HQjIAf.js → rewards-page-DmC4R_Ps.js} +1 -1
  64. package/dist/assets/{scheduling-rules-editor-BHOpHOrV.js → scheduling-rules-editor-D02s70hr.js} +1 -1
  65. package/dist/assets/{schema-badge-DyKbxb51.js → schema-badge-BZO-qNhO.js} +1 -1
  66. package/dist/assets/{select-menu-BX-pZNqL.js → select-menu-fYyreSdQ.js} +1 -1
  67. package/dist/assets/{settings-agents-page-VuYXTiyc.js → settings-agents-page-C_v_hMJF.js} +1 -1
  68. package/dist/assets/{settings-bin-page-BNzvYaOk.js → settings-bin-page-DY5bg81n.js} +1 -1
  69. package/dist/assets/{settings-calendar-page-CjSFB53S.js → settings-calendar-page-D1CzE6cg.js} +1 -1
  70. package/dist/assets/{settings-data-page-CGSlryuI.js → settings-data-page-CHRQFU9H.js} +1 -1
  71. package/dist/assets/{settings-logs-page-BTK5fine.js → settings-logs-page-B04pUwEv.js} +1 -1
  72. package/dist/assets/{settings-mobile-page-CRaObOGo.js → settings-mobile-page-D9kTlYDS.js} +1 -1
  73. package/dist/assets/{settings-models-page-DFshpYF8.js → settings-models-page-D26270R2.js} +1 -1
  74. package/dist/assets/{settings-page-BP81Mb5R.js → settings-page-DYDTFlnv.js} +1 -1
  75. package/dist/assets/{settings-rewards-page-CDJ1PH2G.js → settings-rewards-page-cl4vqqO_.js} +1 -1
  76. package/dist/assets/{settings-section-nav-CCFm27r2.js → settings-section-nav-DSOuht_F.js} +1 -1
  77. package/dist/assets/{settings-users-page-TdUocFPa.js → settings-users-page-BU79JB_T.js} +1 -1
  78. package/dist/assets/{settings-wiki-page-B2zX0QQG.js → settings-wiki-page-DwAUlyA3.js} +1 -1
  79. package/dist/assets/{sleep-page-cI1GMVzk.js → sleep-page-D8NbdhyS.js} +1 -1
  80. package/dist/assets/{sports-page-06LTqp0V.js → sports-page-CV4Cnzwn.js} +1 -1
  81. package/dist/assets/{strategies-page-DXP9Kx8s.js → strategies-page-C4qvXnql.js} +1 -1
  82. package/dist/assets/{strategy-detail-page-D6mx_Mik.js → strategy-detail-page-DJLo5rfy.js} +1 -1
  83. package/dist/assets/{strategy-dialog-BvzomTaF.js → strategy-dialog-D3AuUlVz.js} +1 -1
  84. package/dist/assets/{task-detail-page-BIWIggdp.js → task-detail-page-z-9u9rF0.js} +1 -1
  85. package/dist/assets/{timebox-planning-dialog-CaCnoslG.js → timebox-planning-dialog-DB6FLqmI.js} +1 -1
  86. package/dist/assets/{today-page-DO2mRPT2.js → today-page-BKlu6gx5.js} +1 -1
  87. package/dist/assets/{training-load-page-CyZ0mlEr.js → training-load-page-CyJQqo_3.js} +1 -1
  88. package/dist/assets/{vitals-page-BQvEjTc6.js → vitals-page-qre17Nw8.js} +1 -1
  89. package/dist/assets/{weekly-review-page-Tp6Q9CRj.js → weekly-review-page-Cz4vkRcx.js} +1 -1
  90. package/dist/assets/weight-loss-page-BQrnOI0y.js +1 -0
  91. package/dist/assets/{wiki-article-markdown-DQYohmW2.js → wiki-article-markdown-DdiR2TJE.js} +1 -1
  92. package/dist/assets/{wiki-editor-page-Dem_3eZv.js → wiki-editor-page-DqwoqVFb.js} +1 -1
  93. package/dist/assets/{wiki-ingest-history-page-BxoOcCoJ.js → wiki-ingest-history-page--evBLbOw.js} +1 -1
  94. package/dist/assets/{wiki-ingest-modal-DhguKk3J.js → wiki-ingest-modal--ohzFnj2.js} +1 -1
  95. package/dist/assets/{wiki-page-BLRxVXkl.js → wiki-page-B_VJFBPA.js} +1 -1
  96. package/dist/assets/{workbench-flow-page-DqMkCCTy.js → workbench-flow-page-Du62mtJU.js} +1 -1
  97. package/dist/assets/{workbench-page-BWd02wPw.js → workbench-page-4MKr3iRm.js} +1 -1
  98. package/dist/assets/{workout-detail-page-BD8u7GyL.js → workout-detail-page-DfUbYYw1.js} +1 -1
  99. package/dist/index.html +1 -1
  100. package/dist/server/server/src/watch-mobile.js +22 -10
  101. package/openclaw.plugin.json +1 -1
  102. package/package.json +1 -1
  103. package/dist/assets/weight-loss-page-BBzlhLVV.js +0 -1
@@ -1 +1 @@
1
- import{r as g,j as e,aV as te,cq as se,bX as ae}from"./vendor-DHkYh85p.js";import{j as re,i as A,k as ie}from"./state-B-4sS1xO.js";import{u as ne,eC as de,S as le,E as ce,ck as oe,eD as xe,eE as me,C as S,c as p,eF as he,Z as v,B as C,I as Q,T as pe,m as ue,bL as ge,eG as we,bw as be,bx as ve,by as fe,bz as je,bC as ye}from"./index-BHTUu_4M.js";import{P as Ne}from"./page-hero-CQWo1Mm_.js";import{p as Se,b as ke}from"./health-link-options-Cpx8w7uM.js";import"./board-BkDRaMp6.js";import"./ui-C13Nbgas.js";import"./motion-BeD44FeG.js";import"./forms-BFlTgZ3W.js";import"./graph-D6JLqDbD.js";const Ae=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],W={awake:{label:"Awake",strong:"rgba(251, 191, 36, 0.95)",soft:"rgba(251, 191, 36, 0.16)",text:"text-amber-200"},core:{label:"Core",strong:"rgba(165, 180, 252, 0.96)",soft:"rgba(165, 180, 252, 0.18)",text:"text-indigo-100"},deep:{label:"Deep",strong:"rgba(45, 212, 191, 0.96)",soft:"rgba(45, 212, 191, 0.18)",text:"text-teal-100"},rem:{label:"REM",strong:"rgba(96, 165, 250, 0.96)",soft:"rgba(96, 165, 250, 0.18)",text:"text-sky-100"},in_bed:{label:"In bed",strong:"rgba(255, 255, 255, 0.4)",soft:"rgba(255, 255, 255, 0.1)",text:"text-white/72"},asleep_unspecified:{label:"Asleep",strong:"rgba(196, 181, 253, 0.96)",soft:"rgba(196, 181, 253, 0.16)",text:"text-violet-100"}};function I(t){return W[t]??W.asleep_unspecified}function u(t){if(t<=0)return"0m";const s=Math.floor(t/3600),a=Math.round(t%3600/60);return s===0?`${a}m`:a===0?`${s}h`:`${s}h ${a}m`}function Te(t){const s=Math.round(t/60);return s===0?"on baseline":`${s>0?"+":"-"}${Math.abs(s)}m`}function R(t){return`${Math.round(t*100)}%`}function T(t,s){return t?new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",timeZone:s}).format(new Date(t)):"n/a"}function O(t,s){return new Intl.DateTimeFormat(void 0,{weekday:"long",day:"numeric",month:"long",timeZone:s}).format(new Date(t))}function q(t,s,a){return`${T(t,a)} - ${T(s,a)}`}function Re(t){const[s,a]=t.split("-").map(Number);return new Intl.DateTimeFormat(void 0,{month:"long",year:"numeric"}).format(new Date(s,(a??1)-1,1))}function U(t){const s=new Date(t),a=(t.getDay()+6)%7;return s.setDate(t.getDate()-a),s}function Me(t){const s=U(t);return s.setDate(s.getDate()+6),s}function _e(t){const s=t.getFullYear(),a=`${t.getMonth()+1}`.padStart(2,"0"),r=`${t.getDate()}`.padStart(2,"0");return`${s}-${a}-${r}`}function B(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 De(t,s){if(!t)return[];const[a,r]=t.split("-").map(Number),n=new Date(a,(r??1)-1,1),x=new Date(a,r??1,0),d=U(n),h=Me(x),l=new Map(s.map(c=>[c.dateKey,c])),i=[];for(const c=new Date(d);c<=h;c.setDate(c.getDate()+1)){const j=_e(c);i.push({dateKey:j,dayNumber:c.getDate(),outsideMonth:c.getMonth()!==n.getMonth(),sleep:l.get(j)??null})}return i}function Ie(t){return t>0?"text-emerald-200":t<0?"text-rose-200":"text-white/70"}function G(t){return t==="recharged"||t==="recovered"?"bg-emerald-400/16 text-emerald-100":t==="steady"||t==="stable"?"bg-sky-400/16 text-sky-100":t==="fragile"||t==="strained"?"bg-amber-400/16 text-amber-100":t==="depleted"?"bg-rose-400/16 text-rose-100":"bg-white/10 text-white/76"}function Be(t){return t==="provider_raw"?"bg-emerald-400/16 text-emerald-100":t==="historical_raw"?"bg-amber-400/16 text-amber-100":"bg-white/10 text-white/70"}function qe(t){return t==="provider_raw"?"Provider raw data":t==="historical_raw"?"Historical raw data":"Raw data unavailable"}function Ce(t){return t.qualityKind==="provider_native"?"bg-emerald-400/16 text-emerald-100":"bg-amber-400/16 text-amber-100"}function $e(t,s){const a=t.stage;if(typeof a=="string"&&a.trim().length>0)return a;const r=t.sourceType;if(typeof r=="string"&&r.trim().length>0)return r;const n=t.stageBreakdown;if(Array.isArray(n)&&n.length>0){const x=n[0];if(x&&typeof x=="object"&&typeof x.stage=="string")return(x.stage||"asleep_unspecified").trim()}return s.includes("awake")?"awake":"asleep_unspecified"}function Ee(t){const s=t,a=(s==null?void 0:s.segments)??(s==null?void 0:s.rawSegments)??[],r=(s==null?void 0:s.auditLogs)??(s==null?void 0:s.rawLogs)??[],n=s!=null&&s.sourceRecords&&s.sourceRecords.length>0?s.sourceRecords:r.filter(d=>typeof d.startedAt=="string"&&typeof d.endedAt=="string").map(d=>({id:d.id,importRunId:d.importRunId,pairingSessionId:d.pairingSessionId,sleepSessionId:d.sleepSessionId,userId:d.userId,provider:d.source,providerRecordType:d.logType,providerRecordUid:d.externalUid??d.id,sourceDevice:"",sourceTimezone:d.sourceTimezone,localDateKey:d.localDateKey,startedAt:d.startedAt,endedAt:d.endedAt,rawStage:$e(d.payload,d.logType),rawValue:null,qualityKind:"historical_import",payload:d.payload,metadata:d.metadata,ingestedAt:d.createdAt})),x=(s==null?void 0:s.rawDataStatus)??(n.length>0?"historical_raw":"raw_unavailable");return{sourceRecords:n,segments:a,auditLogs:r,rawDataStatus:x}}function J({stages:t}){const s=t.reduce((a,r)=>a+r.seconds,0);return t.length===0||s===0?e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 bg-black/10 px-4 py-4 text-sm text-white/52",children:"No stage composition was stored for this night yet."}):e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"flex h-3 overflow-hidden rounded-full bg-white/[0.08]",children:t.map(a=>{const r=I(a.stage);return e.jsx("div",{className:"h-full",style:{width:`${Math.max(4,a.seconds/s*100)}%`,background:r.strong},title:`${r.label} · ${u(a.seconds)}`},a.stage)})}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2 xl:grid-cols-4",children:t.map(a=>{const r=I(a.stage),n="percentage"in a&&typeof a.percentage=="number"?a.percentage:s>0?a.seconds/s:0;return e.jsxs("div",{className:"rounded-[16px] border border-white/8 px-3 py-3",style:{background:r.soft},children:[e.jsx("div",{className:v("text-sm font-medium",r.text),children:r.label}),e.jsx("div",{className:"mt-1 text-lg text-white",children:u(a.seconds)}),e.jsx("div",{className:"text-xs text-white/54",children:R(n)})]},a.stage)})})]})}function H({blocks:t,selectedBlockId:s,onSelect:a}){return e.jsxs("div",{className:"relative h-12 overflow-hidden rounded-[18px] border border-white/8 bg-black/20",children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 bg-[linear-gradient(90deg,rgba(255,255,255,0.06)_1px,transparent_1px)] bg-[length:25%_100%]"}),t.map(r=>{const n=I(r.stage),x=s===r.id;return e.jsx("button",{type:"button",onClick:()=>a(r.id),className:v("absolute inset-y-[5px] rounded-[12px] border transition",x?"border-white/60 shadow-[0_0_0_1px_rgba(255,255,255,0.18)]":"border-white/10"),style:{left:`${r.offsetRatio*100}%`,width:`${Math.max(r.widthRatio*100,1.8)}%`,background:n.strong},title:`${r.label} · ${u(r.durationSeconds)} · ${r.startedAt} - ${r.endedAt}`,children:r.widthRatio>.13?e.jsx("span",{className:"truncate px-2 text-[10px] font-medium text-slate-950/85",children:r.label}):null},r.id)})]})}function Ke({timeline:t,timeZone:s}){var l,i;const a=t.blocks.filter(c=>c.lane==="in_bed"),r=t.blocks.filter(c=>c.lane==="sleep"),n=((l=r[0])==null?void 0:l.id)??((i=a[0])==null?void 0:i.id)??null,[x,d]=g.useState(n);g.useEffect(()=>{d(n)},[n,t.startedAt,t.endedAt,t.totalSeconds]);const h=t.blocks.find(c=>c.id===x)??null;return t.hasRawSegments?e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"grid gap-3",children:[a.length>0?e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"In bed window"}),e.jsx(H,{blocks:a,selectedBlockId:x,onSelect:d})]}):null,e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:t.hasSleepStageData?"Sleep phases":"Recorded sleep coverage"}),e.jsx(H,{blocks:r.length>0?r:a,selectedBlockId:x,onSelect:d})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-white/48",children:[e.jsx("span",{children:T(t.startedAt,s)}),e.jsx("span",{children:u(t.totalSeconds)}),e.jsx("span",{children:T(t.endedAt,s)})]}),h?e.jsx("div",{className:"rounded-[18px] 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:v("text-sm font-medium",I(h.stage).text),children:h.label}),e.jsxs("div",{className:"mt-1 text-sm text-white/58",children:[T(h.startedAt,s)," -"," ",T(h.endedAt,s)]})]}),e.jsx(p,{tone:"meta",children:u(h.durationSeconds)})]})}):null]}):e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 bg-black/10 px-4 py-5 text-sm text-white/56",children:"Phase timing is unavailable for this night. Forge still keeps the canonical overnight summary, but the companion did not store segment-level timing."})}function Fe({latestNight:t}){return t?e.jsx(S,{className:"overflow-hidden border-white/8 bg-[linear-gradient(135deg,rgba(7,17,40,0.96),rgba(16,24,54,0.94))] p-0",children:e.jsxs("div",{className:"relative overflow-hidden px-6 py-6 sm:px-7 sm:py-7",children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(96,165,250,0.22),transparent_36%),radial-gradient(circle_at_bottom_left,rgba(45,212,191,0.14),transparent_34%)]"}),e.jsxs("div",{className:"relative grid gap-6 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(p,{className:v("border-white/0",G(t.recoveryState)),children:t.qualitativeState}),e.jsx(p,{tone:"meta",children:t.sourceTimezone}),t.hasReflection?e.jsx(p,{tone:"meta",children:"Has reflection"}):null,t.hasRawSegments?e.jsxs(p,{tone:"meta",children:[t.rawSegmentCount," raw segments"]}):null]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Last night"}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-end gap-x-4 gap-y-2",children:[e.jsx("div",{className:"text-[clamp(2.5rem,6vw,5rem)] font-medium leading-none text-white",children:u(t.asleepSeconds)}),e.jsxs("div",{className:"pb-2 text-sm text-white/58",children:["asleep across ",q(t.startedAt,t.endedAt,t.sourceTimezone)]})]}),e.jsx("div",{className:"mt-3 text-sm text-white/64",children:O(t.endedAt,t.sourceTimezone)}),t.qualitySummary?e.jsx("div",{className:"mt-4 max-w-2xl text-sm leading-6 text-white/72",children:t.qualitySummary}):e.jsx("div",{className:"mt-4 max-w-2xl text-sm leading-6 text-white/56",children:"Canonical overnight summary computed from synced sleep segments, with raw evidence still available underneath."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/20 px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"In bed"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:u(t.timeInBedSeconds)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/20 px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Score"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:t.score??"n/a"})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/20 px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Regularity"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:t.regularity??"n/a"})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/20 px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Efficiency"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:R(t.efficiency)})]})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-black/20 px-5 py-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Baseline"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Compared with recent nights"})]}),e.jsx(se,{className:"size-5 text-[var(--primary)]"})]}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-white/60",children:"7-night average"}),e.jsx("span",{className:"text-sm text-white",children:u(t.weeklyAverageSleepSeconds)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-white/60",children:"Versus baseline"}),e.jsx("span",{className:v("text-sm",Ie(t.deltaFromWeeklyAverageSeconds)),children:Te(t.deltaFromWeeklyAverageSeconds)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-white/60",children:"Bedtime drift"}),e.jsxs("span",{className:"text-sm text-white",children:[t.bedtimeDriftMinutes??0,"m"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-white/60",children:"Wake drift"}),e.jsxs("span",{className:"text-sm text-white",children:[t.wakeDriftMinutes??0,"m"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-white/60",children:"Restorative share"}),e.jsx("span",{className:"text-sm text-white",children:R(t.restorativeShare)})]})]})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-black/20 px-5 py-5",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Stage composition"}),e.jsx("div",{className:"mt-4",children:e.jsx(J,{stages:t.stageBreakdown})})]})]})]})]})}):e.jsxs(S,{className:"overflow-hidden p-6",children:[e.jsx("div",{className:"text-sm uppercase tracking-[0.18em] text-white/42",children:"Sleep"}),e.jsx("div",{className:"mt-4 text-2xl text-white",children:"No overnight sleep yet"}),e.jsx("div",{className:"mt-3 max-w-2xl text-sm leading-6 text-white/58",children:"The sleep page will switch to a night-first summary once the companion syncs a canonical overnight session."})]})}function F({title:t,value:s,description:a}){return e.jsxs(S,{className:"h-full border-white/8 bg-white/[0.03]",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:t}),e.jsx("div",{className:"mt-3 text-3xl text-white",children:s}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/56",children:a})]})}function ze({days:t,selectedSleepId:s,onSelect:a}){const r=g.useMemo(()=>Array.from(new Set(t.map(l=>l.dateKey.slice(0,7)))).sort((l,i)=>l.localeCompare(i)),[t]),[n,x]=g.useState(r[r.length-1]??"");g.useEffect(()=>{if(r.length===0){x("");return}r.includes(n)||x(r[r.length-1]??"")},[n,r]);const d=r.indexOf(n),h=g.useMemo(()=>De(n,t),[t,n]);return n?e.jsx(S,{className:"overflow-hidden border-white/8 bg-[linear-gradient(180deg,rgba(10,17,33,0.98),rgba(12,20,40,0.96))] p-0",children:e.jsxs("div",{className:"grid gap-5 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:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Sleep calendar"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:Re(n)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(C,{type:"button",variant:"secondary",className:"h-9 rounded-full",disabled:d<=0,onClick:()=>x(r[Math.max(0,d-1)]??n),children:"Previous"}),e.jsx(C,{type:"button",variant:"secondary",className:"h-9 rounded-full",disabled:d===-1||d>=r.length-1,onClick:()=>x(r[Math.min(r.length-1,d+1)]??n),children:"Next"})]})]}),e.jsx("div",{className:"grid grid-cols-7 gap-2 text-center text-[11px] uppercase tracking-[0.16em] text-white/38",children:Ae.map(l=>e.jsx("div",{children:l},l))}),e.jsx("div",{className:"grid grid-cols-7 gap-2",children:h.map(l=>{const i=l.sleep,c=(i==null?void 0:i.sleepId)===s,j=i&&typeof i.score=="number"?i.score>=80?"rgba(45,212,191,0.22)":i.score>=65?"rgba(96,165,250,0.22)":"rgba(251,191,36,0.18)":"rgba(255,255,255,0.04)";return e.jsxs("button",{type:"button",disabled:!i,"aria-pressed":c,"aria-label":`Select sleep for ${l.dateKey}`,onClick:()=>{i&&(x(i.dateKey.slice(0,7)),a(i.sleepId,i.dateKey.slice(0,7)))},className:v("min-h-[90px] rounded-[18px] border px-2 py-2 text-left transition",i?"border-white/10 hover:border-white/22 hover:bg-white/[0.05]":"border-white/6 bg-white/[0.02]",c&&"border-[var(--primary)] bg-[var(--primary)]/12",l.outsideMonth&&!i&&"opacity-35"),style:i?{background:`linear-gradient(180deg, ${j}, rgba(255,255,255,0.03))`}:void 0,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("span",{className:v("text-sm",l.outsideMonth?"text-white/40":"text-white/82"),children:l.dayNumber}),i!=null&&i.hasReflection?e.jsx("span",{className:"size-2 rounded-full bg-emerald-300"}):null]}),i?e.jsxs("div",{className:"mt-4 grid gap-1",children:[e.jsxs("div",{className:"text-lg text-white",children:[i.sleepHours.toFixed(1),"h"]}),e.jsxs("div",{className:"text-xs text-white/52",children:[i.score??"n/a"," score"]}),e.jsx("div",{className:"text-xs text-white/40",children:i.hasRawSegments?"phases available":"summary only"})]}):null]},l.dateKey)})})]})}):e.jsx(S,{className:"border-white/8 bg-white/[0.03] px-5 py-8 text-sm leading-6 text-white/56",children:"No canonical nights are available for the calendar yet."})}function z({active:t,children:s,onClick:a}){return e.jsx("button",{type:"button",onClick:a,className:v("rounded-full border px-4 py-2 text-sm transition",t?"border-[var(--primary)] bg-[var(--primary)]/12 text-white":"border-white/8 bg-white/[0.03] text-white/60 hover:text-white"),children:s})}function Le({session:t,draft:s,rawDetail:a,rawDetailLoading:r,pending:n,tab:x,linkOptions:d,onTabChange:h,onDraftChange:l,onSave:i}){const[c,j]=g.useState(null),y=g.useMemo(()=>Ee(a),[a]),$=typeof t.derived.efficiency=="number"?t.derived.efficiency:t.timeInBedSeconds>0?t.asleepSeconds/t.timeInBedSeconds:0,E=typeof t.derived.restorativeShare=="number"?t.derived.restorativeShare:0,M=typeof t.derived.recoveryState=="string"?t.derived.recoveryState:null;return e.jsx(S,{className:"overflow-hidden border-white/8 bg-[linear-gradient(180deg,rgba(10,17,33,0.98),rgba(13,20,38,0.96))] p-0",children:e.jsxs("div",{className:"grid gap-5 px-5 py-5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(p,{className:v("border-white/0",G(M)),children:M?M.replaceAll("_"," "):"Canonical night"}),e.jsxs(p,{tone:"meta",children:[t.rawSegmentCount," raw segments"]}),e.jsx(p,{tone:"meta",children:t.sourceTimezone})]}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Selected night"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:O(t.endedAt,t.sourceTimezone)}),e.jsx("div",{className:"mt-2 text-sm text-white/56",children:q(t.startedAt,t.endedAt,t.sourceTimezone)})]}),e.jsxs("div",{className:"grid gap-2 text-right",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Summary"}),e.jsx("div",{className:"text-3xl text-white",children:u(t.asleepSeconds)}),e.jsx("div",{className:"text-sm text-white/54",children:"asleep"})]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"In bed"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:u(t.timeInBedSeconds)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Awake"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:u(t.awakeSeconds)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Efficiency"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:R($)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Restorative"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:R(E)})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(z,{active:x==="summary",onClick:()=>h("summary"),children:"Summary"}),e.jsx(z,{active:x==="reflection",onClick:()=>h("reflection"),children:"Reflection"}),e.jsx(z,{active:x==="raw",onClick:()=>h("raw"),children:"Show raw data"})]}),x==="summary"?e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-black/18 px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Phase timeline"}),e.jsx("div",{className:"mt-4",children:r?e.jsx("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-6 text-sm text-white/56",children:"Loading phase timing from raw sleep segments…"}):e.jsx(Ke,{timeline:(a==null?void 0:a.phaseTimeline)??{startedAt:t.startedAt,endedAt:t.endedAt,totalSeconds:Math.max(0,Math.round((new Date(t.endedAt).getTime()-new Date(t.startedAt).getTime())/1e3)),hasRawSegments:!1,hasSleepStageData:!1,blocks:[]},timeZone:t.sourceTimezone})})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-black/18 px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Stage composition"}),e.jsx("div",{className:"mt-4",children:e.jsx(J,{stages:t.stageBreakdown})})]})]}):null,x==="reflection"?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:"Quality summary"}),e.jsx(Q,{value:s.qualitySummary,onChange:o=>l({qualitySummary:o.target.value}),placeholder:"Recovered after a late evening, but sleep onset drifted."})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Night notes"}),e.jsx(pe,{className:"min-h-[200px]",value:s.notes,onChange:o=>l({notes:o.target.value}),placeholder:"What shaped this night, and what should we remember about it?"})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Tags"}),e.jsx(Q,{value:s.tagsText,onChange:o=>l({tagsText:o.target.value}),placeholder:"travel, stress, good-routine, late-caffeine"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Linked context"}),e.jsx(ue,{options:d,selectedValues:s.linkValues,onChange:o=>l({linkValues:o}),placeholder:"Search goals, tasks, habits, beliefs, reports, or patterns…"})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(C,{type:"button",pending:n,pendingLabel:"Saving",onClick:i,children:[e.jsx(ae,{className:"size-4"}),"Save reflection"]})})]}):null,x==="raw"?e.jsxs("div",{className:"grid gap-5",children:[e.jsx("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4 text-sm leading-6 text-white/56",children:"Forge shows the canonical overnight session by default. This view reveals the evidence stack underneath it: raw provider or historical imported records first, then Forge-normalized sleep segments."}),r?e.jsx("div",{className:"text-sm text-white/56",children:"Loading raw sleep evidence…"}):null,r?null:e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(p,{className:v("border-white/0",Be(y.rawDataStatus)),children:qe(y.rawDataStatus)}),y.rawDataStatus==="historical_raw"?e.jsx(p,{tone:"meta",children:"Partial evidence"}):null]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Raw data"}),y.sourceRecords.length?y.sourceRecords.map(o=>e.jsxs("div",{className:"rounded-[16px] border border-white/8 bg-black/18 px-4 py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(p,{className:v("border-white/0",Ce(o)),children:o.qualityKind==="provider_native"?"Provider raw":"Historical raw"}),e.jsx(p,{tone:"meta",className:"capitalize",children:o.rawStage.replaceAll("_"," ")}),e.jsx("span",{className:"text-sm text-white/64",children:q(o.startedAt,o.endedAt,o.sourceTimezone)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-white/42",children:o.providerRecordType.replaceAll("_"," ")}),e.jsx(C,{type:"button",variant:"secondary",className:"h-8 rounded-full px-3",onClick:()=>j(_=>_===o.id?null:o.id),children:c===o.id?"Hide JSON":"See JSON"})]})]}),e.jsx("div",{className:"mt-3 text-sm text-white/50",children:u(Math.max(0,Math.round((new Date(o.endedAt).getTime()-new Date(o.startedAt).getTime())/1e3)))}),c===o.id?e.jsx("pre",{className:"mt-3 overflow-x-auto rounded-[14px] border border-white/8 bg-slate-950/70 p-3 text-xs leading-6 text-white/72",children:JSON.stringify({payload:o.payload,metadata:o.metadata},null,2)}):null]},o.id)):e.jsx("div",{className:"rounded-[16px] border border-dashed border-white/10 bg-black/10 px-4 py-4 text-sm text-white/52",children:"No raw data was stored for this night."})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Sleep segments"}),y.segments.length?y.segments.map(o=>e.jsx("div",{className:"rounded-[16px] border border-white/8 bg-black/18 px-4 py-3",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(p,{tone:"meta",className:"capitalize",children:o.stage.replaceAll("_"," ")}),e.jsx(p,{tone:"meta",children:o.qualityKind==="provider_native"?"provider-backed":"historical"}),e.jsx("span",{className:"text-sm text-white/64",children:q(o.startedAt,o.endedAt,o.sourceTimezone)})]}),e.jsx("span",{className:"text-sm text-white/50",children:u(Math.max(0,Math.round((new Date(o.endedAt).getTime()-new Date(o.startedAt).getTime())/1e3)))})]})},o.id)):e.jsx("div",{className:"rounded-[16px] border border-dashed border-white/10 bg-black/10 px-4 py-4 text-sm text-white/52",children:"No normalized sleep segments were stored for this night."})]})]})]}):null]})})}function Xe(){var V;const t=ne(),s=re(),[a,r]=g.useState({}),[n,x]=g.useState(null),[d,h]=g.useState("summary"),l=Array.isArray(t==null?void 0:t.selectedUserIds)?t.selectedUserIds:[],i=t==null?void 0:t.snapshot,c=A({queryKey:["forge-sleep",...l],queryFn:async()=>(await ge(l)).sleep}),j=A({queryKey:["forge-sleep-raw",n],enabled:!!n,queryFn:async()=>we(n)}),y=A({queryKey:["forge-sleep-values",...l],queryFn:async()=>(await be(l)).values}),$=A({queryKey:["forge-sleep-patterns",...l],queryFn:async()=>(await ve(l)).patterns}),E=A({queryKey:["forge-sleep-behaviors",...l],queryFn:async()=>(await fe(l)).behaviors}),M=A({queryKey:["forge-sleep-beliefs",...l],queryFn:async()=>(await je(l)).beliefs}),o=A({queryKey:["forge-sleep-reports",...l],queryFn:async()=>(await ye(l)).reports});g.useEffect(()=>{c.data&&r(Object.fromEntries(c.data.sessions.map(m=>[m.id,B(m)])))},[c.data]),g.useEffect(()=>{var N,f,k;if(!((N=c.data)!=null&&N.sessions.length)){x(null);return}c.data.sessions.some(K=>K.id===n)||x(((f=c.data.latestNight)==null?void 0:f.sleepId)??((k=c.data.sessions[0])==null?void 0:k.id)??null)},[n,c.data]),g.useEffect(()=>{h("summary")},[n]);const _=ie({mutationFn:async m=>de(m.sleepId,{qualitySummary:m.qualitySummary,notes:m.notes,tags:m.tagsText.split(",").map(N=>N.trim()).filter(Boolean),links:Se(m.linkValues)}),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-sleep"]}),await s.invalidateQueries({queryKey:["forge-sleep-raw"]})}});if(c.isLoading)return e.jsx(le,{eyebrow:"Sleep",title:"Loading sleep surface",description:"Reading canonical nights, calendar summaries, and sleep phase detail.",columns:2,blocks:6});if(c.isError||!c.data)return e.jsx(ce,{eyebrow:"Sleep",error:c.error??new Error("Sleep data unavailable"),onRetry:()=>void c.refetch()});const w=c.data,D=w.sessions,L=new Map(D.map(m=>[m.id,m])),b=(n?L.get(n):null)??(w.latestNight?L.get(w.latestNight.sleepId):null)??D[0]??null,P=b?a[b.id]??B(b):null,Y=ke({goals:(i==null?void 0:i.dashboard.goals)??[],projects:(i==null?void 0:i.dashboard.projects)??[],tasks:(i==null?void 0:i.dashboard.tasks)??[],habits:(i==null?void 0:i.dashboard.habits)??[],values:y.data??[],patterns:$.data??[],behaviors:E.data??[],beliefs:M.data??[],reports:o.data??[]});function X(m,N){r(f=>{const k=D.find(ee=>ee.id===m),K=f[m]??(k?B(k):{qualitySummary:"",notes:"",tagsText:"",linkValues:[]});return{...f,[m]:{...K,...N}}})}async function Z(m){const N=D.find(k=>k.id===m);if(!N)return;const f=a[m]??B(N);await _.mutateAsync({sleepId:m,qualitySummary:f.qualitySummary,notes:f.notes,tagsText:f.tagsText,linkValues:f.linkValues})}return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ne,{eyebrow:"Health",title:"Sleep",description:"Canonical overnight sessions first, with last-night recovery, a clickable night calendar, and raw segment evidence only when you ask for it.",badge:`${D.length} nights`}),e.jsx(oe,{}),e.jsx(xe,{children:e.jsx(Fe,{latestNight:w.latestNight})}),e.jsx(me,{children:e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.95fr)_minmax(0,1.05fr)]",children:[e.jsx(F,{title:"Weekly average",value:u(w.summary.averageSleepSeconds),description:"Average overnight sleep duration across the recent week, used as the baseline for the latest-night comparison."}),e.jsx(F,{title:"Regularity",value:`${w.summary.averageRegularityScore}`,description:`Average bedtime drift ${w.summary.averageBedtimeConsistencyMinutes}m and wake drift ${w.summary.averageWakeConsistencyMinutes}m.`}),e.jsx(F,{title:"Restorative share",value:R(w.summary.averageRestorativeShare),description:`Deep + REM share across recent nights, with ${w.summary.reflectiveNightCount} nights already carrying context.`}),e.jsxs(S,{className:"border-white/8 bg-white/[0.03]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Recent stage mix"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:"Average nightly phases"})]}),e.jsx(te,{className:"size-5 text-[var(--primary)]"})]}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:w.stageAverages.length>0?w.stageAverages.slice(0,5).map(m=>e.jsxs(p,{tone:"meta",children:[I(m.stage).label," ",u(m.averageSeconds)]},m.stage)):e.jsx("div",{className:"text-sm text-white/52",children:"Stage averages will appear once nights include phase data."})})]})]})}),e.jsx(he,{children:e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,25rem)_minmax(0,1fr)]",children:[e.jsx(ze,{days:w.calendarDays,selectedSleepId:(b==null?void 0:b.id)??null,onSelect:m=>x(m)}),b&&P?e.jsx(Le,{session:b,draft:P,rawDetail:j.data??null,rawDetailLoading:j.isLoading,pending:_.isPending&&((V=_.variables)==null?void 0:V.sleepId)===b.id,tab:d,linkOptions:Y,onTabChange:h,onDraftChange:m=>X(b.id,m),onSave:()=>void Z(b.id)}):e.jsx(S,{className:"border-white/8 bg-white/[0.03] px-6 py-8 text-sm leading-6 text-white/58",children:"Pick a night from the calendar to inspect its phase timing, stage summary, and reflection context."})]})})]})}export{Xe as SleepPage};
1
+ import{r as g,j as e,aV as te,cq as se,bX as ae}from"./vendor-DHkYh85p.js";import{j as re,i as A,k as ie}from"./state-B-4sS1xO.js";import{u as ne,eC as de,S as le,E as ce,ck as oe,eD as xe,eE as me,C as S,c as p,eF as he,Z as v,B as C,I as Q,T as pe,m as ue,bL as ge,eG as we,bw as be,bx as ve,by as fe,bz as je,bC as ye}from"./index-CF4J4R9L.js";import{P as Ne}from"./page-hero-DRy5b2MU.js";import{p as Se,b as ke}from"./health-link-options-Cpx8w7uM.js";import"./board-BkDRaMp6.js";import"./ui-C13Nbgas.js";import"./motion-BeD44FeG.js";import"./forms-BFlTgZ3W.js";import"./graph-D6JLqDbD.js";const Ae=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],W={awake:{label:"Awake",strong:"rgba(251, 191, 36, 0.95)",soft:"rgba(251, 191, 36, 0.16)",text:"text-amber-200"},core:{label:"Core",strong:"rgba(165, 180, 252, 0.96)",soft:"rgba(165, 180, 252, 0.18)",text:"text-indigo-100"},deep:{label:"Deep",strong:"rgba(45, 212, 191, 0.96)",soft:"rgba(45, 212, 191, 0.18)",text:"text-teal-100"},rem:{label:"REM",strong:"rgba(96, 165, 250, 0.96)",soft:"rgba(96, 165, 250, 0.18)",text:"text-sky-100"},in_bed:{label:"In bed",strong:"rgba(255, 255, 255, 0.4)",soft:"rgba(255, 255, 255, 0.1)",text:"text-white/72"},asleep_unspecified:{label:"Asleep",strong:"rgba(196, 181, 253, 0.96)",soft:"rgba(196, 181, 253, 0.16)",text:"text-violet-100"}};function I(t){return W[t]??W.asleep_unspecified}function u(t){if(t<=0)return"0m";const s=Math.floor(t/3600),a=Math.round(t%3600/60);return s===0?`${a}m`:a===0?`${s}h`:`${s}h ${a}m`}function Te(t){const s=Math.round(t/60);return s===0?"on baseline":`${s>0?"+":"-"}${Math.abs(s)}m`}function R(t){return`${Math.round(t*100)}%`}function T(t,s){return t?new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",timeZone:s}).format(new Date(t)):"n/a"}function O(t,s){return new Intl.DateTimeFormat(void 0,{weekday:"long",day:"numeric",month:"long",timeZone:s}).format(new Date(t))}function q(t,s,a){return`${T(t,a)} - ${T(s,a)}`}function Re(t){const[s,a]=t.split("-").map(Number);return new Intl.DateTimeFormat(void 0,{month:"long",year:"numeric"}).format(new Date(s,(a??1)-1,1))}function U(t){const s=new Date(t),a=(t.getDay()+6)%7;return s.setDate(t.getDate()-a),s}function Me(t){const s=U(t);return s.setDate(s.getDate()+6),s}function _e(t){const s=t.getFullYear(),a=`${t.getMonth()+1}`.padStart(2,"0"),r=`${t.getDate()}`.padStart(2,"0");return`${s}-${a}-${r}`}function B(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 De(t,s){if(!t)return[];const[a,r]=t.split("-").map(Number),n=new Date(a,(r??1)-1,1),x=new Date(a,r??1,0),d=U(n),h=Me(x),l=new Map(s.map(c=>[c.dateKey,c])),i=[];for(const c=new Date(d);c<=h;c.setDate(c.getDate()+1)){const j=_e(c);i.push({dateKey:j,dayNumber:c.getDate(),outsideMonth:c.getMonth()!==n.getMonth(),sleep:l.get(j)??null})}return i}function Ie(t){return t>0?"text-emerald-200":t<0?"text-rose-200":"text-white/70"}function G(t){return t==="recharged"||t==="recovered"?"bg-emerald-400/16 text-emerald-100":t==="steady"||t==="stable"?"bg-sky-400/16 text-sky-100":t==="fragile"||t==="strained"?"bg-amber-400/16 text-amber-100":t==="depleted"?"bg-rose-400/16 text-rose-100":"bg-white/10 text-white/76"}function Be(t){return t==="provider_raw"?"bg-emerald-400/16 text-emerald-100":t==="historical_raw"?"bg-amber-400/16 text-amber-100":"bg-white/10 text-white/70"}function qe(t){return t==="provider_raw"?"Provider raw data":t==="historical_raw"?"Historical raw data":"Raw data unavailable"}function Ce(t){return t.qualityKind==="provider_native"?"bg-emerald-400/16 text-emerald-100":"bg-amber-400/16 text-amber-100"}function $e(t,s){const a=t.stage;if(typeof a=="string"&&a.trim().length>0)return a;const r=t.sourceType;if(typeof r=="string"&&r.trim().length>0)return r;const n=t.stageBreakdown;if(Array.isArray(n)&&n.length>0){const x=n[0];if(x&&typeof x=="object"&&typeof x.stage=="string")return(x.stage||"asleep_unspecified").trim()}return s.includes("awake")?"awake":"asleep_unspecified"}function Ee(t){const s=t,a=(s==null?void 0:s.segments)??(s==null?void 0:s.rawSegments)??[],r=(s==null?void 0:s.auditLogs)??(s==null?void 0:s.rawLogs)??[],n=s!=null&&s.sourceRecords&&s.sourceRecords.length>0?s.sourceRecords:r.filter(d=>typeof d.startedAt=="string"&&typeof d.endedAt=="string").map(d=>({id:d.id,importRunId:d.importRunId,pairingSessionId:d.pairingSessionId,sleepSessionId:d.sleepSessionId,userId:d.userId,provider:d.source,providerRecordType:d.logType,providerRecordUid:d.externalUid??d.id,sourceDevice:"",sourceTimezone:d.sourceTimezone,localDateKey:d.localDateKey,startedAt:d.startedAt,endedAt:d.endedAt,rawStage:$e(d.payload,d.logType),rawValue:null,qualityKind:"historical_import",payload:d.payload,metadata:d.metadata,ingestedAt:d.createdAt})),x=(s==null?void 0:s.rawDataStatus)??(n.length>0?"historical_raw":"raw_unavailable");return{sourceRecords:n,segments:a,auditLogs:r,rawDataStatus:x}}function J({stages:t}){const s=t.reduce((a,r)=>a+r.seconds,0);return t.length===0||s===0?e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 bg-black/10 px-4 py-4 text-sm text-white/52",children:"No stage composition was stored for this night yet."}):e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"flex h-3 overflow-hidden rounded-full bg-white/[0.08]",children:t.map(a=>{const r=I(a.stage);return e.jsx("div",{className:"h-full",style:{width:`${Math.max(4,a.seconds/s*100)}%`,background:r.strong},title:`${r.label} · ${u(a.seconds)}`},a.stage)})}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2 xl:grid-cols-4",children:t.map(a=>{const r=I(a.stage),n="percentage"in a&&typeof a.percentage=="number"?a.percentage:s>0?a.seconds/s:0;return e.jsxs("div",{className:"rounded-[16px] border border-white/8 px-3 py-3",style:{background:r.soft},children:[e.jsx("div",{className:v("text-sm font-medium",r.text),children:r.label}),e.jsx("div",{className:"mt-1 text-lg text-white",children:u(a.seconds)}),e.jsx("div",{className:"text-xs text-white/54",children:R(n)})]},a.stage)})})]})}function H({blocks:t,selectedBlockId:s,onSelect:a}){return e.jsxs("div",{className:"relative h-12 overflow-hidden rounded-[18px] border border-white/8 bg-black/20",children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 bg-[linear-gradient(90deg,rgba(255,255,255,0.06)_1px,transparent_1px)] bg-[length:25%_100%]"}),t.map(r=>{const n=I(r.stage),x=s===r.id;return e.jsx("button",{type:"button",onClick:()=>a(r.id),className:v("absolute inset-y-[5px] rounded-[12px] border transition",x?"border-white/60 shadow-[0_0_0_1px_rgba(255,255,255,0.18)]":"border-white/10"),style:{left:`${r.offsetRatio*100}%`,width:`${Math.max(r.widthRatio*100,1.8)}%`,background:n.strong},title:`${r.label} · ${u(r.durationSeconds)} · ${r.startedAt} - ${r.endedAt}`,children:r.widthRatio>.13?e.jsx("span",{className:"truncate px-2 text-[10px] font-medium text-slate-950/85",children:r.label}):null},r.id)})]})}function Ke({timeline:t,timeZone:s}){var l,i;const a=t.blocks.filter(c=>c.lane==="in_bed"),r=t.blocks.filter(c=>c.lane==="sleep"),n=((l=r[0])==null?void 0:l.id)??((i=a[0])==null?void 0:i.id)??null,[x,d]=g.useState(n);g.useEffect(()=>{d(n)},[n,t.startedAt,t.endedAt,t.totalSeconds]);const h=t.blocks.find(c=>c.id===x)??null;return t.hasRawSegments?e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"grid gap-3",children:[a.length>0?e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"In bed window"}),e.jsx(H,{blocks:a,selectedBlockId:x,onSelect:d})]}):null,e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:t.hasSleepStageData?"Sleep phases":"Recorded sleep coverage"}),e.jsx(H,{blocks:r.length>0?r:a,selectedBlockId:x,onSelect:d})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-white/48",children:[e.jsx("span",{children:T(t.startedAt,s)}),e.jsx("span",{children:u(t.totalSeconds)}),e.jsx("span",{children:T(t.endedAt,s)})]}),h?e.jsx("div",{className:"rounded-[18px] 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:v("text-sm font-medium",I(h.stage).text),children:h.label}),e.jsxs("div",{className:"mt-1 text-sm text-white/58",children:[T(h.startedAt,s)," -"," ",T(h.endedAt,s)]})]}),e.jsx(p,{tone:"meta",children:u(h.durationSeconds)})]})}):null]}):e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 bg-black/10 px-4 py-5 text-sm text-white/56",children:"Phase timing is unavailable for this night. Forge still keeps the canonical overnight summary, but the companion did not store segment-level timing."})}function Fe({latestNight:t}){return t?e.jsx(S,{className:"overflow-hidden border-white/8 bg-[linear-gradient(135deg,rgba(7,17,40,0.96),rgba(16,24,54,0.94))] p-0",children:e.jsxs("div",{className:"relative overflow-hidden px-6 py-6 sm:px-7 sm:py-7",children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(96,165,250,0.22),transparent_36%),radial-gradient(circle_at_bottom_left,rgba(45,212,191,0.14),transparent_34%)]"}),e.jsxs("div",{className:"relative grid gap-6 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(p,{className:v("border-white/0",G(t.recoveryState)),children:t.qualitativeState}),e.jsx(p,{tone:"meta",children:t.sourceTimezone}),t.hasReflection?e.jsx(p,{tone:"meta",children:"Has reflection"}):null,t.hasRawSegments?e.jsxs(p,{tone:"meta",children:[t.rawSegmentCount," raw segments"]}):null]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.2em] text-white/42",children:"Last night"}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-end gap-x-4 gap-y-2",children:[e.jsx("div",{className:"text-[clamp(2.5rem,6vw,5rem)] font-medium leading-none text-white",children:u(t.asleepSeconds)}),e.jsxs("div",{className:"pb-2 text-sm text-white/58",children:["asleep across ",q(t.startedAt,t.endedAt,t.sourceTimezone)]})]}),e.jsx("div",{className:"mt-3 text-sm text-white/64",children:O(t.endedAt,t.sourceTimezone)}),t.qualitySummary?e.jsx("div",{className:"mt-4 max-w-2xl text-sm leading-6 text-white/72",children:t.qualitySummary}):e.jsx("div",{className:"mt-4 max-w-2xl text-sm leading-6 text-white/56",children:"Canonical overnight summary computed from synced sleep segments, with raw evidence still available underneath."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/20 px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"In bed"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:u(t.timeInBedSeconds)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/20 px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Score"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:t.score??"n/a"})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/20 px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Regularity"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:t.regularity??"n/a"})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-black/20 px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Efficiency"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:R(t.efficiency)})]})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-black/20 px-5 py-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Baseline"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Compared with recent nights"})]}),e.jsx(se,{className:"size-5 text-[var(--primary)]"})]}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-white/60",children:"7-night average"}),e.jsx("span",{className:"text-sm text-white",children:u(t.weeklyAverageSleepSeconds)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-white/60",children:"Versus baseline"}),e.jsx("span",{className:v("text-sm",Ie(t.deltaFromWeeklyAverageSeconds)),children:Te(t.deltaFromWeeklyAverageSeconds)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-white/60",children:"Bedtime drift"}),e.jsxs("span",{className:"text-sm text-white",children:[t.bedtimeDriftMinutes??0,"m"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-white/60",children:"Wake drift"}),e.jsxs("span",{className:"text-sm text-white",children:[t.wakeDriftMinutes??0,"m"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-white/60",children:"Restorative share"}),e.jsx("span",{className:"text-sm text-white",children:R(t.restorativeShare)})]})]})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-black/20 px-5 py-5",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Stage composition"}),e.jsx("div",{className:"mt-4",children:e.jsx(J,{stages:t.stageBreakdown})})]})]})]})]})}):e.jsxs(S,{className:"overflow-hidden p-6",children:[e.jsx("div",{className:"text-sm uppercase tracking-[0.18em] text-white/42",children:"Sleep"}),e.jsx("div",{className:"mt-4 text-2xl text-white",children:"No overnight sleep yet"}),e.jsx("div",{className:"mt-3 max-w-2xl text-sm leading-6 text-white/58",children:"The sleep page will switch to a night-first summary once the companion syncs a canonical overnight session."})]})}function F({title:t,value:s,description:a}){return e.jsxs(S,{className:"h-full border-white/8 bg-white/[0.03]",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:t}),e.jsx("div",{className:"mt-3 text-3xl text-white",children:s}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/56",children:a})]})}function ze({days:t,selectedSleepId:s,onSelect:a}){const r=g.useMemo(()=>Array.from(new Set(t.map(l=>l.dateKey.slice(0,7)))).sort((l,i)=>l.localeCompare(i)),[t]),[n,x]=g.useState(r[r.length-1]??"");g.useEffect(()=>{if(r.length===0){x("");return}r.includes(n)||x(r[r.length-1]??"")},[n,r]);const d=r.indexOf(n),h=g.useMemo(()=>De(n,t),[t,n]);return n?e.jsx(S,{className:"overflow-hidden border-white/8 bg-[linear-gradient(180deg,rgba(10,17,33,0.98),rgba(12,20,40,0.96))] p-0",children:e.jsxs("div",{className:"grid gap-5 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:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Sleep calendar"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:Re(n)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(C,{type:"button",variant:"secondary",className:"h-9 rounded-full",disabled:d<=0,onClick:()=>x(r[Math.max(0,d-1)]??n),children:"Previous"}),e.jsx(C,{type:"button",variant:"secondary",className:"h-9 rounded-full",disabled:d===-1||d>=r.length-1,onClick:()=>x(r[Math.min(r.length-1,d+1)]??n),children:"Next"})]})]}),e.jsx("div",{className:"grid grid-cols-7 gap-2 text-center text-[11px] uppercase tracking-[0.16em] text-white/38",children:Ae.map(l=>e.jsx("div",{children:l},l))}),e.jsx("div",{className:"grid grid-cols-7 gap-2",children:h.map(l=>{const i=l.sleep,c=(i==null?void 0:i.sleepId)===s,j=i&&typeof i.score=="number"?i.score>=80?"rgba(45,212,191,0.22)":i.score>=65?"rgba(96,165,250,0.22)":"rgba(251,191,36,0.18)":"rgba(255,255,255,0.04)";return e.jsxs("button",{type:"button",disabled:!i,"aria-pressed":c,"aria-label":`Select sleep for ${l.dateKey}`,onClick:()=>{i&&(x(i.dateKey.slice(0,7)),a(i.sleepId,i.dateKey.slice(0,7)))},className:v("min-h-[90px] rounded-[18px] border px-2 py-2 text-left transition",i?"border-white/10 hover:border-white/22 hover:bg-white/[0.05]":"border-white/6 bg-white/[0.02]",c&&"border-[var(--primary)] bg-[var(--primary)]/12",l.outsideMonth&&!i&&"opacity-35"),style:i?{background:`linear-gradient(180deg, ${j}, rgba(255,255,255,0.03))`}:void 0,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("span",{className:v("text-sm",l.outsideMonth?"text-white/40":"text-white/82"),children:l.dayNumber}),i!=null&&i.hasReflection?e.jsx("span",{className:"size-2 rounded-full bg-emerald-300"}):null]}),i?e.jsxs("div",{className:"mt-4 grid gap-1",children:[e.jsxs("div",{className:"text-lg text-white",children:[i.sleepHours.toFixed(1),"h"]}),e.jsxs("div",{className:"text-xs text-white/52",children:[i.score??"n/a"," score"]}),e.jsx("div",{className:"text-xs text-white/40",children:i.hasRawSegments?"phases available":"summary only"})]}):null]},l.dateKey)})})]})}):e.jsx(S,{className:"border-white/8 bg-white/[0.03] px-5 py-8 text-sm leading-6 text-white/56",children:"No canonical nights are available for the calendar yet."})}function z({active:t,children:s,onClick:a}){return e.jsx("button",{type:"button",onClick:a,className:v("rounded-full border px-4 py-2 text-sm transition",t?"border-[var(--primary)] bg-[var(--primary)]/12 text-white":"border-white/8 bg-white/[0.03] text-white/60 hover:text-white"),children:s})}function Le({session:t,draft:s,rawDetail:a,rawDetailLoading:r,pending:n,tab:x,linkOptions:d,onTabChange:h,onDraftChange:l,onSave:i}){const[c,j]=g.useState(null),y=g.useMemo(()=>Ee(a),[a]),$=typeof t.derived.efficiency=="number"?t.derived.efficiency:t.timeInBedSeconds>0?t.asleepSeconds/t.timeInBedSeconds:0,E=typeof t.derived.restorativeShare=="number"?t.derived.restorativeShare:0,M=typeof t.derived.recoveryState=="string"?t.derived.recoveryState:null;return e.jsx(S,{className:"overflow-hidden border-white/8 bg-[linear-gradient(180deg,rgba(10,17,33,0.98),rgba(13,20,38,0.96))] p-0",children:e.jsxs("div",{className:"grid gap-5 px-5 py-5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(p,{className:v("border-white/0",G(M)),children:M?M.replaceAll("_"," "):"Canonical night"}),e.jsxs(p,{tone:"meta",children:[t.rawSegmentCount," raw segments"]}),e.jsx(p,{tone:"meta",children:t.sourceTimezone})]}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Selected night"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:O(t.endedAt,t.sourceTimezone)}),e.jsx("div",{className:"mt-2 text-sm text-white/56",children:q(t.startedAt,t.endedAt,t.sourceTimezone)})]}),e.jsxs("div",{className:"grid gap-2 text-right",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Summary"}),e.jsx("div",{className:"text-3xl text-white",children:u(t.asleepSeconds)}),e.jsx("div",{className:"text-sm text-white/54",children:"asleep"})]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"In bed"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:u(t.timeInBedSeconds)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Awake"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:u(t.awakeSeconds)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Efficiency"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:R($)})]}),e.jsxs("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-white/40",children:"Restorative"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:R(E)})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(z,{active:x==="summary",onClick:()=>h("summary"),children:"Summary"}),e.jsx(z,{active:x==="reflection",onClick:()=>h("reflection"),children:"Reflection"}),e.jsx(z,{active:x==="raw",onClick:()=>h("raw"),children:"Show raw data"})]}),x==="summary"?e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-black/18 px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Phase timeline"}),e.jsx("div",{className:"mt-4",children:r?e.jsx("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-6 text-sm text-white/56",children:"Loading phase timing from raw sleep segments…"}):e.jsx(Ke,{timeline:(a==null?void 0:a.phaseTimeline)??{startedAt:t.startedAt,endedAt:t.endedAt,totalSeconds:Math.max(0,Math.round((new Date(t.endedAt).getTime()-new Date(t.startedAt).getTime())/1e3)),hasRawSegments:!1,hasSleepStageData:!1,blocks:[]},timeZone:t.sourceTimezone})})]}),e.jsxs("div",{className:"rounded-[22px] border border-white/8 bg-black/18 px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Stage composition"}),e.jsx("div",{className:"mt-4",children:e.jsx(J,{stages:t.stageBreakdown})})]})]}):null,x==="reflection"?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:"Quality summary"}),e.jsx(Q,{value:s.qualitySummary,onChange:o=>l({qualitySummary:o.target.value}),placeholder:"Recovered after a late evening, but sleep onset drifted."})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Night notes"}),e.jsx(pe,{className:"min-h-[200px]",value:s.notes,onChange:o=>l({notes:o.target.value}),placeholder:"What shaped this night, and what should we remember about it?"})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Tags"}),e.jsx(Q,{value:s.tagsText,onChange:o=>l({tagsText:o.target.value}),placeholder:"travel, stress, good-routine, late-caffeine"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Linked context"}),e.jsx(ue,{options:d,selectedValues:s.linkValues,onChange:o=>l({linkValues:o}),placeholder:"Search goals, tasks, habits, beliefs, reports, or patterns…"})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(C,{type:"button",pending:n,pendingLabel:"Saving",onClick:i,children:[e.jsx(ae,{className:"size-4"}),"Save reflection"]})})]}):null,x==="raw"?e.jsxs("div",{className:"grid gap-5",children:[e.jsx("div",{className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-4 text-sm leading-6 text-white/56",children:"Forge shows the canonical overnight session by default. This view reveals the evidence stack underneath it: raw provider or historical imported records first, then Forge-normalized sleep segments."}),r?e.jsx("div",{className:"text-sm text-white/56",children:"Loading raw sleep evidence…"}):null,r?null:e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(p,{className:v("border-white/0",Be(y.rawDataStatus)),children:qe(y.rawDataStatus)}),y.rawDataStatus==="historical_raw"?e.jsx(p,{tone:"meta",children:"Partial evidence"}):null]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Raw data"}),y.sourceRecords.length?y.sourceRecords.map(o=>e.jsxs("div",{className:"rounded-[16px] border border-white/8 bg-black/18 px-4 py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(p,{className:v("border-white/0",Ce(o)),children:o.qualityKind==="provider_native"?"Provider raw":"Historical raw"}),e.jsx(p,{tone:"meta",className:"capitalize",children:o.rawStage.replaceAll("_"," ")}),e.jsx("span",{className:"text-sm text-white/64",children:q(o.startedAt,o.endedAt,o.sourceTimezone)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-white/42",children:o.providerRecordType.replaceAll("_"," ")}),e.jsx(C,{type:"button",variant:"secondary",className:"h-8 rounded-full px-3",onClick:()=>j(_=>_===o.id?null:o.id),children:c===o.id?"Hide JSON":"See JSON"})]})]}),e.jsx("div",{className:"mt-3 text-sm text-white/50",children:u(Math.max(0,Math.round((new Date(o.endedAt).getTime()-new Date(o.startedAt).getTime())/1e3)))}),c===o.id?e.jsx("pre",{className:"mt-3 overflow-x-auto rounded-[14px] border border-white/8 bg-slate-950/70 p-3 text-xs leading-6 text-white/72",children:JSON.stringify({payload:o.payload,metadata:o.metadata},null,2)}):null]},o.id)):e.jsx("div",{className:"rounded-[16px] border border-dashed border-white/10 bg-black/10 px-4 py-4 text-sm text-white/52",children:"No raw data was stored for this night."})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Sleep segments"}),y.segments.length?y.segments.map(o=>e.jsx("div",{className:"rounded-[16px] border border-white/8 bg-black/18 px-4 py-3",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(p,{tone:"meta",className:"capitalize",children:o.stage.replaceAll("_"," ")}),e.jsx(p,{tone:"meta",children:o.qualityKind==="provider_native"?"provider-backed":"historical"}),e.jsx("span",{className:"text-sm text-white/64",children:q(o.startedAt,o.endedAt,o.sourceTimezone)})]}),e.jsx("span",{className:"text-sm text-white/50",children:u(Math.max(0,Math.round((new Date(o.endedAt).getTime()-new Date(o.startedAt).getTime())/1e3)))})]})},o.id)):e.jsx("div",{className:"rounded-[16px] border border-dashed border-white/10 bg-black/10 px-4 py-4 text-sm text-white/52",children:"No normalized sleep segments were stored for this night."})]})]})]}):null]})})}function Xe(){var V;const t=ne(),s=re(),[a,r]=g.useState({}),[n,x]=g.useState(null),[d,h]=g.useState("summary"),l=Array.isArray(t==null?void 0:t.selectedUserIds)?t.selectedUserIds:[],i=t==null?void 0:t.snapshot,c=A({queryKey:["forge-sleep",...l],queryFn:async()=>(await ge(l)).sleep}),j=A({queryKey:["forge-sleep-raw",n],enabled:!!n,queryFn:async()=>we(n)}),y=A({queryKey:["forge-sleep-values",...l],queryFn:async()=>(await be(l)).values}),$=A({queryKey:["forge-sleep-patterns",...l],queryFn:async()=>(await ve(l)).patterns}),E=A({queryKey:["forge-sleep-behaviors",...l],queryFn:async()=>(await fe(l)).behaviors}),M=A({queryKey:["forge-sleep-beliefs",...l],queryFn:async()=>(await je(l)).beliefs}),o=A({queryKey:["forge-sleep-reports",...l],queryFn:async()=>(await ye(l)).reports});g.useEffect(()=>{c.data&&r(Object.fromEntries(c.data.sessions.map(m=>[m.id,B(m)])))},[c.data]),g.useEffect(()=>{var N,f,k;if(!((N=c.data)!=null&&N.sessions.length)){x(null);return}c.data.sessions.some(K=>K.id===n)||x(((f=c.data.latestNight)==null?void 0:f.sleepId)??((k=c.data.sessions[0])==null?void 0:k.id)??null)},[n,c.data]),g.useEffect(()=>{h("summary")},[n]);const _=ie({mutationFn:async m=>de(m.sleepId,{qualitySummary:m.qualitySummary,notes:m.notes,tags:m.tagsText.split(",").map(N=>N.trim()).filter(Boolean),links:Se(m.linkValues)}),onSuccess:async()=>{await s.invalidateQueries({queryKey:["forge-sleep"]}),await s.invalidateQueries({queryKey:["forge-sleep-raw"]})}});if(c.isLoading)return e.jsx(le,{eyebrow:"Sleep",title:"Loading sleep surface",description:"Reading canonical nights, calendar summaries, and sleep phase detail.",columns:2,blocks:6});if(c.isError||!c.data)return e.jsx(ce,{eyebrow:"Sleep",error:c.error??new Error("Sleep data unavailable"),onRetry:()=>void c.refetch()});const w=c.data,D=w.sessions,L=new Map(D.map(m=>[m.id,m])),b=(n?L.get(n):null)??(w.latestNight?L.get(w.latestNight.sleepId):null)??D[0]??null,P=b?a[b.id]??B(b):null,Y=ke({goals:(i==null?void 0:i.dashboard.goals)??[],projects:(i==null?void 0:i.dashboard.projects)??[],tasks:(i==null?void 0:i.dashboard.tasks)??[],habits:(i==null?void 0:i.dashboard.habits)??[],values:y.data??[],patterns:$.data??[],behaviors:E.data??[],beliefs:M.data??[],reports:o.data??[]});function X(m,N){r(f=>{const k=D.find(ee=>ee.id===m),K=f[m]??(k?B(k):{qualitySummary:"",notes:"",tagsText:"",linkValues:[]});return{...f,[m]:{...K,...N}}})}async function Z(m){const N=D.find(k=>k.id===m);if(!N)return;const f=a[m]??B(N);await _.mutateAsync({sleepId:m,qualitySummary:f.qualitySummary,notes:f.notes,tagsText:f.tagsText,linkValues:f.linkValues})}return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(Ne,{eyebrow:"Health",title:"Sleep",description:"Canonical overnight sessions first, with last-night recovery, a clickable night calendar, and raw segment evidence only when you ask for it.",badge:`${D.length} nights`}),e.jsx(oe,{}),e.jsx(xe,{children:e.jsx(Fe,{latestNight:w.latestNight})}),e.jsx(me,{children:e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.95fr)_minmax(0,1.05fr)]",children:[e.jsx(F,{title:"Weekly average",value:u(w.summary.averageSleepSeconds),description:"Average overnight sleep duration across the recent week, used as the baseline for the latest-night comparison."}),e.jsx(F,{title:"Regularity",value:`${w.summary.averageRegularityScore}`,description:`Average bedtime drift ${w.summary.averageBedtimeConsistencyMinutes}m and wake drift ${w.summary.averageWakeConsistencyMinutes}m.`}),e.jsx(F,{title:"Restorative share",value:R(w.summary.averageRestorativeShare),description:`Deep + REM share across recent nights, with ${w.summary.reflectiveNightCount} nights already carrying context.`}),e.jsxs(S,{className:"border-white/8 bg-white/[0.03]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Recent stage mix"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:"Average nightly phases"})]}),e.jsx(te,{className:"size-5 text-[var(--primary)]"})]}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:w.stageAverages.length>0?w.stageAverages.slice(0,5).map(m=>e.jsxs(p,{tone:"meta",children:[I(m.stage).label," ",u(m.averageSeconds)]},m.stage)):e.jsx("div",{className:"text-sm text-white/52",children:"Stage averages will appear once nights include phase data."})})]})]})}),e.jsx(he,{children:e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,25rem)_minmax(0,1fr)]",children:[e.jsx(ze,{days:w.calendarDays,selectedSleepId:(b==null?void 0:b.id)??null,onSelect:m=>x(m)}),b&&P?e.jsx(Le,{session:b,draft:P,rawDetail:j.data??null,rawDetailLoading:j.isLoading,pending:_.isPending&&((V=_.variables)==null?void 0:V.sleepId)===b.id,tab:d,linkOptions:Y,onTabChange:h,onDraftChange:m=>X(b.id,m),onSave:()=>void Z(b.id)}):e.jsx(S,{className:"border-white/8 bg-white/[0.03] px-6 py-8 text-sm leading-6 text-white/58",children:"Pick a night from the calendar to inspect its phase timing, stage summary, and reflection context."})]})})]})}export{Xe as SleepPage};
@@ -1 +1 @@
1
- import{r as u,j as e,aC as Ve,bI as Ne,aV as Pe,b8 as ke,bK as qe,bX as Qe}from"./vendor-DHkYh85p.js";import{j as Ze,i as O,k as Ue}from"./state-B-4sS1xO.js";import{u as Ge,eH as Xe,S as Ye,E as Je,eI as et,C as g,eJ as Y,c as o,I as $,eK as tt,aS as at,T as st,m as it,B as ie,bM as rt,bw as nt,bx as lt,by as ct,bz as dt,bC as ot}from"./index-BHTUu_4M.js";import{F as ve}from"./faceted-token-search-CE1YauRd.js";import{P as xt}from"./page-hero-CQWo1Mm_.js";import{f as ht}from"./date-keys-Cj1G3TOn.js";import{p as mt,b as pt}from"./health-link-options-Cpx8w7uM.js";import{R as P,A as ut,C as J,X as q,Y as B,T as Q,a as ye,f as we,B as re,g as gt,e as jt,h as ft,b as ne,S as vt,i as yt}from"./charts-P7EVhIog.js";import"./board-BkDRaMp6.js";import"./ui-C13Nbgas.js";import"./motion-BeD44FeG.js";import"./forms-BFlTgZ3W.js";import"./graph-D6JLqDbD.js";const U={below_z1:"#94a3b8",zone_1:"#38bdf8",zone_2:"#22c55e",zone_3:"#eab308",zone_4:"#f97316",zone_5:"#ef4444"},I=["below_z1","zone_1","zone_2","zone_3","zone_4","zone_5"];function z(t){return t?t.replace(/^activity_/i,"").replaceAll("_"," ").replace(/\s+/g," ").replace(/\b\w/g,i=>i.toUpperCase()):"Unknown"}function W(t){return`${Math.round(t/60)}m`}function ce(t){return t?`${(t/1e3).toFixed(1)} km`:"n/a"}function G(t,i){const s=new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short"}),l=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"});return`${s.format(new Date(t))} · ${l.format(new Date(t))} - ${l.format(new Date(i))}`}function te(t){return ht(new Date(t))}function Z(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(i=>`${i.entityType}:${i.entityId}`):[]}}function Se(t){return t.trim().toLowerCase()}function j(t){var i;return((i=t.workoutTypeLabel)==null?void 0:i.trim())||z(t.workoutType)}function H(t){var i;return((i=t.activityFamilyLabel)==null?void 0:i.trim())||z(t.activityFamily)}function Ae(t){return z(t.sourceSystem??t.source)}function wt(t){return t==null?"n/a":typeof t=="boolean"?t?"Yes":"No":typeof t=="number"?Number.isInteger(t)?String(t):t.toFixed(1):t}function bt(t){const i=wt(t.value);return!t.unit||t.unit==="count"?i:`${i} ${t.unit}`}function Nt(t,i){return Se([t.workoutType,j(t),t.activityFamily,H(t),t.sourceSystem,Ae(t),t.sourceType,t.sourceDevice,t.reconciliationStatus,t.moodBefore,t.moodAfter,t.meaningText,t.plannedContext,t.socialContext,t.tags.join(" "),i.moodBefore,i.moodAfter,i.meaningText,i.plannedContext,i.socialContext,i.tagsText,G(t.startedAt,t.endedAt)].join(" "))}function kt(t){const i=new Map;for(const s of t)i.set(`workout:${s.workoutType}`,{id:`workout:${s.workoutType}`,label:j(s),description:"Workout type",searchText:`${j(s)} workout`,badge:e.jsx(o,{tone:"meta",children:j(s)})}),i.set(`source:${s.sourceType}`,{id:`source:${s.sourceType}`,label:s.sourceType.replaceAll("_"," "),description:"Source type",searchText:`${s.sourceType} source`,badge:e.jsx(o,{tone:"meta",className:"capitalize",children:s.sourceType.replaceAll("_"," ")})}),i.set(`status:${s.reconciliationStatus}`,{id:`status:${s.reconciliationStatus}`,label:s.reconciliationStatus.replaceAll("_"," "),description:"Reconciliation status",searchText:`${s.reconciliationStatus} status`,badge:e.jsx(o,{tone:"meta",className:"capitalize",children:s.reconciliationStatus.replaceAll("_"," ")})});return i.set("linked:yes",{id:"linked:yes",label:"Linked",description:"Already tied to Forge or Psyche context",badge:e.jsx(o,{tone:"meta",children:"Linked"})}),i.set("linked:no",{id:"linked:no",label:"Needs links",description:"No Forge or Psyche links yet",badge:e.jsx(o,{tone:"meta",children:"Needs links"})}),i.set("habit:yes",{id:"habit:yes",label:"Habit-generated",description:"Created from a habit completion",badge:e.jsx(o,{tone:"meta",children:"Habit-generated"})}),i.set("effort:rated",{id:"effort:rated",label:"Effort rated",description:"Already has a subjective effort score",badge:e.jsx(o,{tone:"meta",children:"Effort rated"})}),Array.from(i.values())}function St(t,i){return i.every(s=>s.startsWith("workout:")?t.workoutType===s.slice(8):s.startsWith("source:")?t.sourceType===s.slice(7):s.startsWith("status:")?t.reconciliationStatus===s.slice(7):s==="linked:yes"?t.links.length>0:s==="linked:no"?t.links.length===0:s==="habit:yes"?!!t.generatedFromHabitId:s==="effort:rated"?t.subjectiveEffort!==null:!0)}function ee(t,i,s){if(!t||t.length===0)return null;const l=[...t].filter(c=>c.dateKey<=i&&c[s]!=null).sort((c,f)=>f.dateKey.localeCompare(c.dateKey))[0];return(l==null?void 0:l[s])??null}function At(t){return[t.workoutType,t.workoutTypeLabel,t.activityFamily,t.activityFamilyLabel].filter(Boolean).join(" ").toLowerCase().includes("kickboxing")}function Ct(t){const i=new Map;for(const s of t){const l=`type:${s.workoutType}`;i.set(l,{id:l,label:j(s),description:H(s),searchText:`${j(s)} ${H(s)} ${s.workoutType}`,badge:e.jsx(o,{tone:"meta",children:j(s)})})}return[...i.values()].sort((s,l)=>s.label.localeCompare(l.label))}function Tt(t,i,s,l,c){const f=i.filter(x=>x.startsWith("type:")).map(x=>x.slice(5)),v=new Set(f),T=te(new Date().toISOString()),w=new Date(`${T}T12:00:00.000Z`);w.setUTCDate(w.getUTCDate()-90);const n=w.toISOString().slice(0,10);return t.filter(x=>{if(v.size>0&&!v.has(x.workoutType))return!1;const h=te(x.startedAt);return s==="recent_90"?h>=n:!(s==="custom"&&(l&&h<l||c&&h>c))}).sort((x,h)=>Date.parse(x.startedAt)-Date.parse(h.startedAt))}function le(t){var s;const i=Object.fromEntries(I.map(l=>[l,0]));for(const l of t)for(const c of((s=l.analytics)==null?void 0:s.zoneDurations)??[])I.includes(c.key)&&(i[c.key]+=c.seconds);return i}function be(t){const i=Object.values(t).reduce((s,l)=>s+l,0);return Object.fromEntries(I.map(s=>[s,i>0?Number((t[s]/i*100).toFixed(1)):0]))}function Mt(t,i,s){const l=typeof(s==null?void 0:s.dataKey)=="string"?s.dataKey:typeof i=="string"?i:"",c=typeof t=="number"?Number(t.toFixed(1)):String(t??"n/a");return l==="restingHeartRate"||i==="Resting HR"?[`${c} bpm`,"Resting HR"]:l==="vo2Max"||i==="VO2max"?[`${c} ml/kg/min`,"VO2max"]:[`${c}%`,z(l)]}function Rt(t,i){const s=t.map((n,x)=>{var y,M,D;const h=te(n.startedAt),N=t.slice(Math.max(0,x-2),x+1),b=le(N),C=be(b);return{id:n.id,dateKey:h,date:h.slice(5),session:j(n),durationMinutes:Math.round(n.durationSeconds/60),confidence:((y=n.analytics)==null?void 0:y.confidence)??"unavailable",restingHeartRate:((D=(M=n.analytics)==null?void 0:M.hrSummary)==null?void 0:D.restingHr)??ee(i,h,"restingHeartRate"),vo2Max:ee(i,h,"vo2Max"),...C}}),l=t.map((n,x)=>{var C,y,M;const h=te(n.startedAt),N=le(t.slice(0,x+1)),b=be(N);return{id:n.id,dateKey:h,date:h.slice(5),session:j(n),durationMinutes:Math.round(n.durationSeconds/60),confidence:((C=n.analytics)==null?void 0:C.confidence)??"unavailable",restingHeartRate:((M=(y=n.analytics)==null?void 0:y.hrSummary)==null?void 0:M.restingHr)??ee(i,h,"restingHeartRate"),vo2Max:ee(i,h,"vo2Max"),...b}}),c=le(t),f=Object.values(c).reduce((n,x)=>n+x,0),v=I.map(n=>{var h;const x=((h=t.flatMap(N=>{var b;return((b=N.analytics)==null?void 0:b.zoneDurations)??[]}).find(N=>N.key===n))==null?void 0:h.label)??z(n);return{key:n,zone:x,percentage:f>0?Number((c[n]/f*100).toFixed(1)):0,fill:U[n]??"#f8fafc"}}),T=t.filter(n=>{var x,h;return(((h=(x=n.analytics)==null?void 0:x.dataQuality)==null?void 0:h.heartRateSampleCount)??0)>0}).length,w=[...new Set(t.map(n=>j(n)))];return{sessions:t,lineData:s,expandingLineData:l,averageZoneData:v,rawHrCount:T,exerciseLabels:w}}function Et({session:t,draft:i,linkOptions:s,pending:l,step:c,onStepChange:f,onDraftChange:v,onSave:T}){var n,x,h,N,b,C,y,M,D;const w=[{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(Ne,{className:"size-4 text-[var(--primary)]"}),e.jsx("span",{children:j(t)})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:G(t.startedAt,t.endedAt)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(o,{children:W(t.durationSeconds)}),t.totalEnergyKcal?e.jsxs(o,{tone:"meta",children:[Math.round(t.totalEnergyKcal)," kcal"]}):null,t.distanceMeters?e.jsx(o,{tone:"meta",children:ce(t.distanceMeters)}):null,e.jsx(o,{tone:"meta",children:H(t)}),e.jsx(o,{tone:"meta",className:"capitalize",children:t.reconciliationStatus.replaceAll("_"," ")})]})]})}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-3",children:w.map((r,L)=>e.jsxs("button",{type:"button",onClick:()=>f(L),className:`rounded-[20px] border px-4 py-3 text-left transition ${c===L?"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 ",L+1]}),e.jsx("div",{className:"mt-2 text-sm font-medium",children:r.title})]},r.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:w[c].title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:w[c].description}),c===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:"Activity family"}),e.jsx("div",{className:"mt-2 text-lg text-white capitalize",children:H(t)})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Source system"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Ae(t)})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Source device"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:t.sourceDevice||"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:"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:"Avg HR"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:t.averageHeartRate?Math.round(t.averageHeartRate):"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($,{type:"number",min:1,max:10,value:i.subjectiveEffort,onChange:r=>v({subjectiveEffort:r.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($,{value:i.plannedContext,onChange:r=>v({plannedContext:r.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($,{value:i.socialContext,onChange:r=>v({socialContext:r.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($,{value:i.tagsText,onChange:r=>v({tagsText:r.target.value}),placeholder:"recovery, interval-block, stress-release"})]})]}):null,c===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($,{value:i.moodBefore,onChange:r=>v({moodBefore:r.target.value})})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Mood after"}),e.jsx($,{value:i.moodAfter,onChange:r=>v({moodAfter:r.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(st,{className:"min-h-[160px]",value:i.meaningText,onChange:r=>v({meaningText:r.target.value}),placeholder:"This session was planned as active recovery after a heavy work block and helped reset stress before sleep."})]})]}):null,c===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(it,{options:s,selectedValues:i.linkValues,onChange:r=>v({linkValues:r}),placeholder:"Search Forge and Psyche records…"})]}):null,e.jsxs("div",{className:"mt-5 grid gap-4 border-t border-white/8 pt-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Captured data"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Source-native workout metrics, events, and phases exposed through the adapter layer."})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:[(((n=t.details)==null?void 0:n.metrics)??[]).slice(0,12).map(r=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:r.label}),e.jsx("div",{className:"mt-2 text-lg text-white",children:bt(r)}),e.jsxs("div",{className:"mt-1 text-xs uppercase tracking-[0.14em] text-white/38",children:[z(r.category)," · ",z(r.statistic)]})]},`${r.category}:${r.key}:${r.statistic}`)),(((h=(x=t.details)==null?void 0:x.metrics)==null?void 0:h.length)??0)===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] p-4 text-sm text-white/50",children:"No provider metrics were captured for this session yet."}):null]}),(((b=(N=t.details)==null?void 0:N.events)==null?void 0:b.length)??0)>0?e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Workout events"}),e.jsx("div",{className:"grid gap-2",children:(C=t.details)==null?void 0:C.events.map(r=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("div",{className:"text-white",children:r.label}),e.jsx(o,{tone:"meta",children:W(r.durationSeconds)})]}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:G(r.startedAt,r.endedAt??r.startedAt)})]},`${r.type}:${r.startedAt}`))})]}):null,(((M=(y=t.details)==null?void 0:y.components)==null?void 0:M.length)??0)>0?e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Workout phases"}),e.jsx("div",{className:"grid gap-2",children:(D=t.details)==null?void 0:D.components.map(r=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("div",{className:"text-white",children:r.activity.canonicalLabel}),e.jsx(o,{tone:"meta",children:W(r.durationSeconds)})]}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:G(r.startedAt,r.endedAt??r.startedAt)})]},r.externalUid))})]}):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:c<w.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(ie,{type:"button",variant:"secondary",onClick:()=>f(Math.max(0,c-1)),disabled:c===0,children:"Back"}),c<w.length-1?e.jsxs(ie,{type:"button",onClick:()=>f(c+1),children:["Next",e.jsx(ke,{className:"size-4"})]}):null,e.jsxs(ie,{type:"button",pending:l,pendingLabel:"Saving",onClick:T,children:[e.jsx(Qe,{className:"size-4"}),"Save session"]})]})]})]})}function Pt(){var je,fe;const t=Ge(),i=Ze(),s=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],[l,c]=u.useState({}),[f,v]=u.useState(""),[T,w]=u.useState([]),[n,x]=u.useState([]),[h,N]=u.useState(""),[b,C]=u.useState("all"),[y,M]=u.useState("rolling_stack"),[D,r]=u.useState(""),[L,Ce]=u.useState(""),[de,Te]=u.useState(!1),[oe,ae]=u.useState(null),[Me,X]=u.useState(0),k=O({queryKey:["forge-fitness",...s],queryFn:async()=>(await rt(s)).fitness}),Re=O({queryKey:["forge-health-values",...s],queryFn:async()=>(await nt(s)).values}),Ee=O({queryKey:["forge-health-patterns",...s],queryFn:async()=>(await lt(s)).patterns}),ze=O({queryKey:["forge-health-behaviors",...s],queryFn:async()=>(await ct(s)).behaviors}),De=O({queryKey:["forge-health-beliefs",...s],queryFn:async()=>(await dt(s)).beliefs}),Fe=O({queryKey:["forge-health-reports",...s],queryFn:async()=>(await ot(s)).reports});u.useEffect(()=>{k.data&&c(Object.fromEntries(k.data.sessions.map(a=>[a.id,Z(a)])))},[k.data]),u.useEffect(()=>{if(de||!k.data)return;const d=(k.data.analysisSessions??k.data.sessions).find(At);d&&x([`type:${d.workoutType}`]),Te(!0)},[de,k.data]);const se=Ue({mutationFn:async a=>Xe(a.workoutId,{subjectiveEffort:a.subjectiveEffort.trim().length>0?Number(a.subjectiveEffort):null,moodBefore:a.moodBefore,moodAfter:a.moodAfter,meaningText:a.meaningText,plannedContext:a.plannedContext,socialContext:a.socialContext,tags:a.tagsText.split(",").map(d=>d.trim()).filter(Boolean),links:mt(a.linkValues)}),onSuccess:async()=>{await i.invalidateQueries({queryKey:["forge-fitness"]})}}),F=k.data,S=(F==null?void 0:F.sessions)??[],K=(F==null?void 0:F.analysisSessions)??S,$e=pt({goals:t.snapshot.dashboard.goals,projects:t.snapshot.dashboard.projects,tasks:t.snapshot.dashboard.tasks,habits:t.snapshot.dashboard.habits,values:Re.data??[],patterns:Ee.data??[],behaviors:ze.data??[],beliefs:De.data??[],reports:Fe.data??[]}),Le=u.useMemo(()=>kt(S),[S]),_e=u.useMemo(()=>Ct(K),[K]),V=u.useMemo(()=>{const a=Se(f);return[...S].sort((d,m)=>new Date(m.startedAt).getTime()-new Date(d.startedAt).getTime()).filter(d=>{const m=l[d.id]??Z(d);return(a.length===0||Nt(d,m).includes(a))&&St(d,T)})},[l,f,T,S]),xe=u.useMemo(()=>Tt(K,n,b,D,L),[b,L,K,D,n]),he=V.length===S.length&&f.trim().length===0&&T.length===0?`${S.length} workout sessions visible`:`${V.length} of ${S.length} workout sessions visible`,R=V.find(a=>a.id===oe)??S.find(a=>a.id===oe)??null,me=R?l[R.id]??Z(R):null;if(k.isLoading)return e.jsx(Ye,{eyebrow:"Sports",title:"Loading sports view",description:"Reading synced workouts and local reflection metadata.",columns:2,blocks:6});if(k.isError||!F)return e.jsx(Je,{eyebrow:"Sports",error:k.error??new Error("Sports data unavailable"),onRetry:()=>void k.refetch()});const{summary:p,weeklyTrend:pe,typeBreakdown:He}=F,ue=p.zoneMix??[],A=Rt(xe,F.vitalsTrend),ge=n.length===0?"All exercise types":A.exerciseLabels.length>0?A.exerciseLabels.join(", "):`${n.length} selected types`,Ke=ue.map(a=>({zone:a.label,minutes:Math.round(a.seconds/60),percentage:Math.round(a.percentage*100),fill:U[a.key]??"#f8fafc"})),Oe=pe.map(a=>{const d=Object.fromEntries((a.zoneDurations??[]).map(m=>[m.key,Math.round(m.seconds/60)]));return{date:a.dateKey.slice(5),duration:a.durationMinutes,load:a.trainingLoad??0,coverage:Math.round((a.heartRateCoverage??0)*100),...d}}),Be=K.map(a=>{var d,m,E,_;return{duration:Math.round(a.durationSeconds/60),intensity:Math.round((((m=(d=a.analytics)==null?void 0:d.load)==null?void 0:m.intensity)??0)*100),load:((_=(E=a.analytics)==null?void 0:E.load)==null?void 0:_.trimp)??0,type:j(a),name:j(a)}});function We(a,d){c(m=>{const E=m[a]??Z(S.find(_=>_.id===a));return{...m,[a]:{...E,...d}}})}async function Ie(a){const d=S.find(E=>E.id===a);if(!d)return;const m=l[a]??Z(d);await se.mutateAsync({workoutId:a,subjectiveEffort:m.subjectiveEffort,moodBefore:m.moodBefore,moodAfter:m.moodAfter,meaningText:m.meaningText,plannedContext:m.plannedContext,socialContext:m.socialContext,tagsText:m.tagsText,linkValues:m.linkValues}),ae(null),X(0)}return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(xt,{entityKind:"project",title:"Sports",description:"A session-first training surface for workout data, subjective meaning, and links back into Forge execution and Psyche.",badge:`${S.length} sessions`}),e.jsx(et,{children:e.jsxs("section",{className:"grid gap-4 lg:grid-cols-4",children:[e.jsxs(g,{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:W(p.weeklyVolumeSeconds)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Total training time in the recent week."})]}),e.jsxs(g,{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:p.exerciseMinutes}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Aggregate exercise minutes from synced sessions."})]}),e.jsxs(g,{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:p.energyBurnedKcal}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Recent weekly kcal."})]}),e.jsxs(g,{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:p.streakDays}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Distinct workout days in the recent week."})]}),e.jsxs(g,{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:[p.averageSessionMinutes,"m"]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Mean duration across recent sessions."})]}),e.jsxs(g,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Training load"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:p.totalTrainingLoad??"n/a"}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Forge TRIMP across recent sessions."})]}),e.jsxs(g,{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:p.linkedSessionCount}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Sessions already tied to Forge or Psyche entities."})]}),e.jsxs(g,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"HR coverage"}),e.jsxs("div",{className:"mt-3 font-display text-4xl text-white",children:[Math.round((p.averageHeartRateCoverage??0)*100),"%"]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Average raw HR sample coverage."})]})]})}),e.jsx(Y,{children:e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.1fr)_minmax(320px,0.9fr)]",children:[e.jsxs(g,{className:"min-h-[320px]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Load and volume trend"}),e.jsx("div",{className:"mt-4 h-[260px]",children:e.jsx(P,{width:"100%",height:"100%",children:e.jsxs(ut,{data:Oe,children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"sportsLoad",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"#f97316",stopOpacity:.36}),e.jsx("stop",{offset:"100%",stopColor:"#f97316",stopOpacity:.04})]})}),e.jsx(J,{stroke:"rgba(255,255,255,0.08)",vertical:!1}),e.jsx(q,{dataKey:"date",tick:{fill:"rgba(255,255,255,0.55)",fontSize:11}}),e.jsx(B,{tick:{fill:"rgba(255,255,255,0.55)",fontSize:11},width:34}),e.jsx(Q,{contentStyle:{background:"rgba(8,12,22,0.94)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,color:"white"}}),e.jsx(ye,{type:"monotone",dataKey:"load",stroke:"#f97316",fill:"url(#sportsLoad)",strokeWidth:2}),e.jsx(ye,{type:"monotone",dataKey:"duration",stroke:"#38bdf8",fill:"rgba(56,189,248,0.10)",strokeWidth:2})]})})})]}),e.jsxs(g,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Zone distribution"}),e.jsx("div",{className:"mt-4 grid gap-3",children:ue.map(a=>e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm",children:[e.jsx("span",{className:"text-white/72",children:a.label}),e.jsxs("span",{className:"text-white",children:[Math.round(a.percentage*100),"% · ",W(a.seconds)]})]}),e.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-white/[0.08]",children:e.jsx("div",{className:"h-full rounded-full",style:{width:`${Math.max(1,a.percentage*100)}%`,background:U[a.key]??"#f8fafc"}})})]},a.key))}),e.jsx("div",{className:"mt-5 h-[180px]",children:e.jsx(P,{width:"100%",height:"100%",children:e.jsxs(we,{data:Ke,children:[e.jsx(q,{dataKey:"zone",tick:{fill:"rgba(255,255,255,0.55)",fontSize:10}}),e.jsx(B,{tick:{fill:"rgba(255,255,255,0.55)",fontSize:10},width:34}),e.jsx(Q,{contentStyle:{background:"rgba(8,12,22,0.94)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,color:"white"}}),e.jsx(re,{dataKey:"minutes",fill:"#f97316",radius:[4,4,0,0]})]})})})]})]})}),e.jsx(Y,{children:e.jsxs("section",{className:"grid gap-4",children:[e.jsxs(g,{className:"grid gap-4 overflow-hidden",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:"HR zone analysis"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Filter all-time workout evidence by exercise type and date."})]}),e.jsxs(o,{tone:"meta",children:[xe.length," of ",K.length," sessions"]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1fr)_minmax(280px,0.8fr)]",children:[e.jsx(ve,{title:"Exercise types",description:"Select one, many, or none for all exercise types.",query:h,onQueryChange:N,options:_e,selectedOptionIds:n,onSelectedOptionIdsChange:x,resultSummary:ge,placeholder:"Search exercise types",emptyStateMessage:"No exercise type matches."}),e.jsxs("div",{className:"grid gap-3 rounded-[8px] border border-white/8 bg-white/[0.035] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Date range"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:[["all","All time"],["recent_90","90 days"],["custom","Custom"]].map(([a,d])=>e.jsx("button",{type:"button",className:`rounded-[8px] border px-3 py-2 text-sm transition ${b===a?"border-[var(--primary)] bg-[var(--primary)]/12 text-white":"border-white/8 bg-white/[0.04] text-white/62 hover:bg-white/[0.07] hover:text-white"}`,onClick:()=>C(a),children:d},a))}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Start"}),e.jsx($,{type:"date",value:D,onChange:a=>{r(a.target.value),C("custom")}})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"End"}),e.jsx($,{type:"date",value:L,onChange:a=>{Ce(a.target.value),C("custom")}})]})]})]})]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.85fr)_minmax(0,1.15fr)]",children:[e.jsxs(g,{className:"min-h-[330px] overflow-hidden",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:"Average zones"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Duration-weighted proportion of time in each HR zone."})]}),e.jsx(o,{tone:"meta",children:ge})]}),e.jsx("div",{className:"mt-4 h-[235px]",children:A.sessions.length>0?e.jsx(P,{width:"100%",height:"100%",children:e.jsxs(we,{data:A.averageZoneData,children:[e.jsx(J,{stroke:"rgba(255,255,255,0.08)",vertical:!1}),e.jsx(q,{dataKey:"zone",interval:0,tick:{fill:"rgba(255,255,255,0.55)",fontSize:10}}),e.jsx(B,{unit:"%",domain:[0,100],ticks:[0,25,50,75,100],tick:{fill:"rgba(255,255,255,0.55)",fontSize:10},width:38}),e.jsx(Q,{formatter:a=>[`${a}%`,"Average time"],contentStyle:{background:"rgba(8,12,22,0.94)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,color:"white"}}),e.jsx(re,{dataKey:"percentage",radius:[4,4,0,0],children:A.averageZoneData.map(a=>e.jsx(gt,{fill:a.fill},a.key))})]})}):e.jsx("div",{className:"grid h-full place-items-center rounded-[8px] bg-white/[0.035] p-6 text-center text-sm leading-6 text-white/54",children:"No selected sessions with zone analytics are available yet."})}),A.sessions.length>0?e.jsxs("div",{className:"mt-3 grid gap-2 text-sm text-white/58 sm:grid-cols-3",children:[e.jsxs("div",{children:[A.rawHrCount," sessions have raw HR timelines"]}),e.jsxs("div",{children:["Latest:"," ",((je=A.lineData.at(-1))==null?void 0:je.dateKey)??"n/a"]}),e.jsxs("div",{children:["VO2max points:"," ",A.lineData.filter(a=>a.vo2Max!=null).length]})]}):null]}),e.jsxs(g,{className:"min-h-[330px] overflow-hidden",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:y==="expanding_lines"?"Expanding zone lines":"Zone drift"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:y==="expanding_lines"?"Expanding all-session average with resting HR and VO2max overlay.":"Rolling duration-weighted zone mix with resting HR and VO2max overlay."})]}),e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:items-end",children:[e.jsx("div",{className:"grid grid-cols-2 gap-1 rounded-[8px] border border-white/8 bg-white/[0.035] p-1","aria-label":"Zone chart display",children:[["rolling_stack","Stacked"],["expanding_lines","Lines"]].map(([a,d])=>e.jsx("button",{type:"button",className:`min-h-9 rounded-[6px] px-3 py-1.5 text-xs font-medium transition ${y===a?"bg-[var(--primary)]/18 text-white":"text-white/58 hover:bg-white/[0.06] hover:text-white"}`,onClick:()=>M(a),children:d},a))}),e.jsx(o,{tone:"meta",children:"HRR zones"})]})]}),e.jsx("div",{className:"mt-4 h-[255px]",children:A.lineData.length>0?e.jsx(P,{width:"100%",height:"100%",children:e.jsxs(jt,{data:y==="expanding_lines"?A.expandingLineData:A.lineData,children:[e.jsx(J,{stroke:"rgba(255,255,255,0.08)",vertical:!1}),e.jsx(q,{dataKey:"date",tick:{fill:"rgba(255,255,255,0.55)",fontSize:10}}),e.jsx(B,{yAxisId:"zones",domain:[0,100],ticks:[0,25,50,75,100],unit:"%",tick:{fill:"rgba(255,255,255,0.55)",fontSize:10},width:38}),e.jsx(B,{yAxisId:"vitals",orientation:"right",tick:{fill:"rgba(255,255,255,0.55)",fontSize:10},width:42}),e.jsx(Q,{formatter:(a,d,m)=>Mt(a,d,m),contentStyle:{background:"rgba(8,12,22,0.94)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,color:"white"}}),e.jsx(ft,{wrapperStyle:{color:"rgba(255,255,255,0.7)",fontSize:11}}),y==="expanding_lines"?I.map(a=>e.jsx(ne,{yAxisId:"zones",type:"monotone",dataKey:a,name:z(a),stroke:U[a],strokeWidth:2,dot:{r:2.5},activeDot:{r:4},connectNulls:!0},a)):I.map(a=>e.jsx(re,{yAxisId:"zones",dataKey:a,stackId:"zones",fill:U[a],isAnimationActive:!1},a)),e.jsx(ne,{yAxisId:"vitals",type:"monotone",dataKey:"restingHeartRate",name:"Resting HR",stroke:"#e2e8f0",strokeWidth:2,dot:{r:3},connectNulls:!0}),e.jsx(ne,{yAxisId:"vitals",type:"monotone",dataKey:"vo2Max",name:"VO2max",stroke:"#a78bfa",strokeWidth:2,dot:{r:3},connectNulls:!0})]})}):e.jsx("div",{className:"grid h-full place-items-center rounded-[8px] bg-white/[0.035] p-6 text-center text-sm leading-6 text-white/54",children:"Select workouts with HR evidence to unlock the time-series plot."})})]})]})]})}),e.jsx(Y,{children:e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[minmax(0,1fr)_360px]",children:[e.jsxs(g,{className:"min-h-[300px]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Duration vs intensity"}),e.jsx("div",{className:"mt-4 h-[250px]",children:e.jsx(P,{width:"100%",height:"100%",children:e.jsxs(vt,{data:Be,children:[e.jsx(J,{stroke:"rgba(255,255,255,0.08)"}),e.jsx(q,{type:"number",dataKey:"duration",name:"minutes",tick:{fill:"rgba(255,255,255,0.55)",fontSize:11}}),e.jsx(B,{type:"number",dataKey:"intensity",name:"intensity",tick:{fill:"rgba(255,255,255,0.55)",fontSize:11},width:38}),e.jsx(Q,{cursor:{strokeDasharray:"3 3"},contentStyle:{background:"rgba(8,12,22,0.94)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,color:"white"}}),e.jsx(yt,{dataKey:"load",fill:"#f97316"})]})})})]}),e.jsxs(g,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Evidence quality"}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsxs("div",{className:"rounded-[8px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Raw HR coverage"}),e.jsxs("div",{className:"mt-2 text-2xl text-white",children:[Math.round((p.averageHeartRateCoverage??0)*100),"%"]})]}),e.jsxs("div",{className:"rounded-[8px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Route-backed workouts"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:p.routeWorkoutCount??0})]}),e.jsxs("div",{className:"rounded-[8px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Top sport"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:p.topWorkoutTypeLabel??p.topWorkoutType??"n/a"})]})]})]})]})}),e.jsx(Y,{children:e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[1.05fr_0.95fr]",children:[e.jsxs(g,{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:pe.map(a=>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:a.dateKey}),e.jsx("div",{className:"text-sm text-white",children:a.workoutTypeLabel??z(a.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,a.durationMinutes/120*100)}%`}})}),e.jsxs("div",{className:"text-sm text-white",children:[a.durationMinutes,"m"]})]}),e.jsxs("div",{className:"text-sm text-white/62",children:[a.energyKcal," kcal"]})]},a.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:ce(p.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:p.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:[p.importedSessionCount," / ",p.reconciledSessionCount]})]})]})]}),e.jsxs(g,{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:He.slice(0,6).map(a=>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:a.workoutTypeLabel??z(a.workoutType)}),e.jsxs("div",{className:"mt-1 text-sm text-white/58",children:[a.sessionCount," sessions · ",a.activityFamilyLabel??"Other"]})]}),e.jsxs("div",{className:"text-sm text-white/72",children:[a.totalMinutes,"m"]}),e.jsxs("div",{className:"text-sm text-white/72",children:[a.energyKcal," kcal"]})]},a.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:p.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:p.linkedSessionCount})]})]})]})]})}),e.jsx(tt,{children:e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,25rem)_minmax(0,1fr)]",children:[e.jsx(ve,{title:"Session browser",description:"Search past activities by workout type, source, reconciliation state, or whether they still need context.",query:f,onQueryChange:v,options:Le,selectedOptionIds:T,onSelectedOptionIdsChange:w,resultSummary:he,placeholder:"Search workouts, devices, notes, moods, or filter chips",emptyStateMessage:"Keep typing or pick a filter chip to narrow the activity history."}),e.jsxs(g,{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(o,{tone:"meta",children:he})]}),e.jsx("div",{className:"max-h-[34rem] overflow-y-auto rounded-[8px] border border-white/8 bg-white/[0.03] p-3",children:V.length===0?e.jsx("div",{className:"flex min-h-[18rem] 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:"grid gap-3",children:V.map(a=>{var m,E,_;const d=a.meaningText.trim().length>0||a.moodBefore.trim().length>0||a.moodAfter.trim().length>0||a.tags.length>0||a.links.length>0;return e.jsxs("div",{className:"grid w-full min-w-0 gap-3 rounded-[8px] border border-white/8 bg-white/[0.04] px-4 py-3 text-left transition hover:bg-white/[0.07]",children:[e.jsxs("div",{className:"grid min-w-0 gap-3 sm:flex sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(Ve,{to:`/sports/workouts/${a.id}`,className:"flex min-w-0 items-center gap-2 text-white transition hover:text-[var(--primary)]",children:[e.jsx(Ne,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"truncate text-base font-medium",children:j(a)})]}),e.jsxs("div",{className:"mt-2 flex min-w-0 items-center gap-2 text-sm text-white/56",children:[e.jsx(Pe,{className:"size-3.5 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate",children:G(a.startedAt,a.endedAt)})]}),e.jsxs("div",{className:"mt-2 text-sm text-white/46",children:[H(a)," · ",a.sourceDevice]})]}),e.jsxs("button",{type:"button","aria-label":`Edit ${j(a)} reflection`,className:"inline-flex w-fit max-w-full items-center gap-2 rounded-full bg-white/[0.05] px-3 py-1.5 text-xs text-white/70 transition hover:bg-white/[0.08] hover:text-white",onClick:()=>{ae(a.id),X(0)},children:[e.jsx("span",{className:"truncate",children:d?"Reflected":"Needs reflection"}),e.jsx(ke,{className:"size-3.5 shrink-0"})]})]}),e.jsxs("div",{className:"flex min-w-0 flex-wrap gap-2",children:[e.jsx(o,{children:W(a.durationSeconds)}),a.totalEnergyKcal?e.jsxs(o,{tone:"meta",children:[Math.round(a.totalEnergyKcal)," kcal"]}):null,a.distanceMeters?e.jsx(o,{tone:"meta",children:ce(a.distanceMeters)}):null,a.averageHeartRate?e.jsxs(o,{tone:"meta",children:[e.jsx(qe,{className:"mr-1 size-3.5"}),Math.round(a.averageHeartRate)," bpm"]}):null,e.jsx(o,{tone:"meta",children:H(a)}),e.jsx(o,{tone:"meta",className:"capitalize",children:a.sourceType.replaceAll("_"," ")}),e.jsx(o,{tone:"meta",className:"capitalize",children:a.reconciliationStatus.replaceAll("_"," ")}),(m=a.analytics)!=null&&m.confidence?e.jsxs(o,{tone:"meta",children:[a.analytics.confidence," zones"]}):null,(_=(E=a.analytics)==null?void 0:E.routeSummary)!=null&&_.hasRoute?e.jsx(o,{tone:"meta",children:"Route"}):null]})]},a.id)})})})]})]})}),R&&me?e.jsx(at,{open:!!R,onOpenChange:a=>{a||(ae(null),X(0))},eyebrow:"Sports session",title:j(R),description:"Add contextual meaning without crowding the main training surface.",children:e.jsx(Et,{session:R,draft:me,linkOptions:$e,pending:se.isPending&&((fe=se.variables)==null?void 0:fe.workoutId)===R.id,step:Me,onStepChange:X,onDraftChange:a=>We(R.id,a),onSave:()=>void Ie(R.id)})}):null]})}export{Pt as SportsPage,Mt as formatZoneTrendTooltipValue};
1
+ import{r as u,j as e,aC as Ve,bI as Ne,aV as Pe,b8 as ke,bK as qe,bX as Qe}from"./vendor-DHkYh85p.js";import{j as Ze,i as O,k as Ue}from"./state-B-4sS1xO.js";import{u as Ge,eH as Xe,S as Ye,E as Je,eI as et,C as g,eJ as Y,c as o,I as $,eK as tt,aS as at,T as st,m as it,B as ie,bM as rt,bw as nt,bx as lt,by as ct,bz as dt,bC as ot}from"./index-CF4J4R9L.js";import{F as ve}from"./faceted-token-search-BxRRcM3q.js";import{P as xt}from"./page-hero-DRy5b2MU.js";import{f as ht}from"./date-keys-Cj1G3TOn.js";import{p as mt,b as pt}from"./health-link-options-Cpx8w7uM.js";import{R as P,A as ut,C as J,X as q,Y as B,T as Q,a as ye,f as we,B as re,g as gt,e as jt,h as ft,b as ne,S as vt,i as yt}from"./charts-P7EVhIog.js";import"./board-BkDRaMp6.js";import"./ui-C13Nbgas.js";import"./motion-BeD44FeG.js";import"./forms-BFlTgZ3W.js";import"./graph-D6JLqDbD.js";const U={below_z1:"#94a3b8",zone_1:"#38bdf8",zone_2:"#22c55e",zone_3:"#eab308",zone_4:"#f97316",zone_5:"#ef4444"},I=["below_z1","zone_1","zone_2","zone_3","zone_4","zone_5"];function z(t){return t?t.replace(/^activity_/i,"").replaceAll("_"," ").replace(/\s+/g," ").replace(/\b\w/g,i=>i.toUpperCase()):"Unknown"}function W(t){return`${Math.round(t/60)}m`}function ce(t){return t?`${(t/1e3).toFixed(1)} km`:"n/a"}function G(t,i){const s=new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short"}),l=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"});return`${s.format(new Date(t))} · ${l.format(new Date(t))} - ${l.format(new Date(i))}`}function te(t){return ht(new Date(t))}function Z(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(i=>`${i.entityType}:${i.entityId}`):[]}}function Se(t){return t.trim().toLowerCase()}function j(t){var i;return((i=t.workoutTypeLabel)==null?void 0:i.trim())||z(t.workoutType)}function H(t){var i;return((i=t.activityFamilyLabel)==null?void 0:i.trim())||z(t.activityFamily)}function Ae(t){return z(t.sourceSystem??t.source)}function wt(t){return t==null?"n/a":typeof t=="boolean"?t?"Yes":"No":typeof t=="number"?Number.isInteger(t)?String(t):t.toFixed(1):t}function bt(t){const i=wt(t.value);return!t.unit||t.unit==="count"?i:`${i} ${t.unit}`}function Nt(t,i){return Se([t.workoutType,j(t),t.activityFamily,H(t),t.sourceSystem,Ae(t),t.sourceType,t.sourceDevice,t.reconciliationStatus,t.moodBefore,t.moodAfter,t.meaningText,t.plannedContext,t.socialContext,t.tags.join(" "),i.moodBefore,i.moodAfter,i.meaningText,i.plannedContext,i.socialContext,i.tagsText,G(t.startedAt,t.endedAt)].join(" "))}function kt(t){const i=new Map;for(const s of t)i.set(`workout:${s.workoutType}`,{id:`workout:${s.workoutType}`,label:j(s),description:"Workout type",searchText:`${j(s)} workout`,badge:e.jsx(o,{tone:"meta",children:j(s)})}),i.set(`source:${s.sourceType}`,{id:`source:${s.sourceType}`,label:s.sourceType.replaceAll("_"," "),description:"Source type",searchText:`${s.sourceType} source`,badge:e.jsx(o,{tone:"meta",className:"capitalize",children:s.sourceType.replaceAll("_"," ")})}),i.set(`status:${s.reconciliationStatus}`,{id:`status:${s.reconciliationStatus}`,label:s.reconciliationStatus.replaceAll("_"," "),description:"Reconciliation status",searchText:`${s.reconciliationStatus} status`,badge:e.jsx(o,{tone:"meta",className:"capitalize",children:s.reconciliationStatus.replaceAll("_"," ")})});return i.set("linked:yes",{id:"linked:yes",label:"Linked",description:"Already tied to Forge or Psyche context",badge:e.jsx(o,{tone:"meta",children:"Linked"})}),i.set("linked:no",{id:"linked:no",label:"Needs links",description:"No Forge or Psyche links yet",badge:e.jsx(o,{tone:"meta",children:"Needs links"})}),i.set("habit:yes",{id:"habit:yes",label:"Habit-generated",description:"Created from a habit completion",badge:e.jsx(o,{tone:"meta",children:"Habit-generated"})}),i.set("effort:rated",{id:"effort:rated",label:"Effort rated",description:"Already has a subjective effort score",badge:e.jsx(o,{tone:"meta",children:"Effort rated"})}),Array.from(i.values())}function St(t,i){return i.every(s=>s.startsWith("workout:")?t.workoutType===s.slice(8):s.startsWith("source:")?t.sourceType===s.slice(7):s.startsWith("status:")?t.reconciliationStatus===s.slice(7):s==="linked:yes"?t.links.length>0:s==="linked:no"?t.links.length===0:s==="habit:yes"?!!t.generatedFromHabitId:s==="effort:rated"?t.subjectiveEffort!==null:!0)}function ee(t,i,s){if(!t||t.length===0)return null;const l=[...t].filter(c=>c.dateKey<=i&&c[s]!=null).sort((c,f)=>f.dateKey.localeCompare(c.dateKey))[0];return(l==null?void 0:l[s])??null}function At(t){return[t.workoutType,t.workoutTypeLabel,t.activityFamily,t.activityFamilyLabel].filter(Boolean).join(" ").toLowerCase().includes("kickboxing")}function Ct(t){const i=new Map;for(const s of t){const l=`type:${s.workoutType}`;i.set(l,{id:l,label:j(s),description:H(s),searchText:`${j(s)} ${H(s)} ${s.workoutType}`,badge:e.jsx(o,{tone:"meta",children:j(s)})})}return[...i.values()].sort((s,l)=>s.label.localeCompare(l.label))}function Tt(t,i,s,l,c){const f=i.filter(x=>x.startsWith("type:")).map(x=>x.slice(5)),v=new Set(f),T=te(new Date().toISOString()),w=new Date(`${T}T12:00:00.000Z`);w.setUTCDate(w.getUTCDate()-90);const n=w.toISOString().slice(0,10);return t.filter(x=>{if(v.size>0&&!v.has(x.workoutType))return!1;const h=te(x.startedAt);return s==="recent_90"?h>=n:!(s==="custom"&&(l&&h<l||c&&h>c))}).sort((x,h)=>Date.parse(x.startedAt)-Date.parse(h.startedAt))}function le(t){var s;const i=Object.fromEntries(I.map(l=>[l,0]));for(const l of t)for(const c of((s=l.analytics)==null?void 0:s.zoneDurations)??[])I.includes(c.key)&&(i[c.key]+=c.seconds);return i}function be(t){const i=Object.values(t).reduce((s,l)=>s+l,0);return Object.fromEntries(I.map(s=>[s,i>0?Number((t[s]/i*100).toFixed(1)):0]))}function Mt(t,i,s){const l=typeof(s==null?void 0:s.dataKey)=="string"?s.dataKey:typeof i=="string"?i:"",c=typeof t=="number"?Number(t.toFixed(1)):String(t??"n/a");return l==="restingHeartRate"||i==="Resting HR"?[`${c} bpm`,"Resting HR"]:l==="vo2Max"||i==="VO2max"?[`${c} ml/kg/min`,"VO2max"]:[`${c}%`,z(l)]}function Rt(t,i){const s=t.map((n,x)=>{var y,M,D;const h=te(n.startedAt),N=t.slice(Math.max(0,x-2),x+1),b=le(N),C=be(b);return{id:n.id,dateKey:h,date:h.slice(5),session:j(n),durationMinutes:Math.round(n.durationSeconds/60),confidence:((y=n.analytics)==null?void 0:y.confidence)??"unavailable",restingHeartRate:((D=(M=n.analytics)==null?void 0:M.hrSummary)==null?void 0:D.restingHr)??ee(i,h,"restingHeartRate"),vo2Max:ee(i,h,"vo2Max"),...C}}),l=t.map((n,x)=>{var C,y,M;const h=te(n.startedAt),N=le(t.slice(0,x+1)),b=be(N);return{id:n.id,dateKey:h,date:h.slice(5),session:j(n),durationMinutes:Math.round(n.durationSeconds/60),confidence:((C=n.analytics)==null?void 0:C.confidence)??"unavailable",restingHeartRate:((M=(y=n.analytics)==null?void 0:y.hrSummary)==null?void 0:M.restingHr)??ee(i,h,"restingHeartRate"),vo2Max:ee(i,h,"vo2Max"),...b}}),c=le(t),f=Object.values(c).reduce((n,x)=>n+x,0),v=I.map(n=>{var h;const x=((h=t.flatMap(N=>{var b;return((b=N.analytics)==null?void 0:b.zoneDurations)??[]}).find(N=>N.key===n))==null?void 0:h.label)??z(n);return{key:n,zone:x,percentage:f>0?Number((c[n]/f*100).toFixed(1)):0,fill:U[n]??"#f8fafc"}}),T=t.filter(n=>{var x,h;return(((h=(x=n.analytics)==null?void 0:x.dataQuality)==null?void 0:h.heartRateSampleCount)??0)>0}).length,w=[...new Set(t.map(n=>j(n)))];return{sessions:t,lineData:s,expandingLineData:l,averageZoneData:v,rawHrCount:T,exerciseLabels:w}}function Et({session:t,draft:i,linkOptions:s,pending:l,step:c,onStepChange:f,onDraftChange:v,onSave:T}){var n,x,h,N,b,C,y,M,D;const w=[{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(Ne,{className:"size-4 text-[var(--primary)]"}),e.jsx("span",{children:j(t)})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:G(t.startedAt,t.endedAt)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(o,{children:W(t.durationSeconds)}),t.totalEnergyKcal?e.jsxs(o,{tone:"meta",children:[Math.round(t.totalEnergyKcal)," kcal"]}):null,t.distanceMeters?e.jsx(o,{tone:"meta",children:ce(t.distanceMeters)}):null,e.jsx(o,{tone:"meta",children:H(t)}),e.jsx(o,{tone:"meta",className:"capitalize",children:t.reconciliationStatus.replaceAll("_"," ")})]})]})}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-3",children:w.map((r,L)=>e.jsxs("button",{type:"button",onClick:()=>f(L),className:`rounded-[20px] border px-4 py-3 text-left transition ${c===L?"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 ",L+1]}),e.jsx("div",{className:"mt-2 text-sm font-medium",children:r.title})]},r.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:w[c].title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:w[c].description}),c===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:"Activity family"}),e.jsx("div",{className:"mt-2 text-lg text-white capitalize",children:H(t)})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Source system"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:Ae(t)})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Source device"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:t.sourceDevice||"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:"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:"Avg HR"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:t.averageHeartRate?Math.round(t.averageHeartRate):"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($,{type:"number",min:1,max:10,value:i.subjectiveEffort,onChange:r=>v({subjectiveEffort:r.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($,{value:i.plannedContext,onChange:r=>v({plannedContext:r.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($,{value:i.socialContext,onChange:r=>v({socialContext:r.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($,{value:i.tagsText,onChange:r=>v({tagsText:r.target.value}),placeholder:"recovery, interval-block, stress-release"})]})]}):null,c===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($,{value:i.moodBefore,onChange:r=>v({moodBefore:r.target.value})})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Mood after"}),e.jsx($,{value:i.moodAfter,onChange:r=>v({moodAfter:r.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(st,{className:"min-h-[160px]",value:i.meaningText,onChange:r=>v({meaningText:r.target.value}),placeholder:"This session was planned as active recovery after a heavy work block and helped reset stress before sleep."})]})]}):null,c===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(it,{options:s,selectedValues:i.linkValues,onChange:r=>v({linkValues:r}),placeholder:"Search Forge and Psyche records…"})]}):null,e.jsxs("div",{className:"mt-5 grid gap-4 border-t border-white/8 pt-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Captured data"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:"Source-native workout metrics, events, and phases exposed through the adapter layer."})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:[(((n=t.details)==null?void 0:n.metrics)??[]).slice(0,12).map(r=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:r.label}),e.jsx("div",{className:"mt-2 text-lg text-white",children:bt(r)}),e.jsxs("div",{className:"mt-1 text-xs uppercase tracking-[0.14em] text-white/38",children:[z(r.category)," · ",z(r.statistic)]})]},`${r.category}:${r.key}:${r.statistic}`)),(((h=(x=t.details)==null?void 0:x.metrics)==null?void 0:h.length)??0)===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] p-4 text-sm text-white/50",children:"No provider metrics were captured for this session yet."}):null]}),(((b=(N=t.details)==null?void 0:N.events)==null?void 0:b.length)??0)>0?e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Workout events"}),e.jsx("div",{className:"grid gap-2",children:(C=t.details)==null?void 0:C.events.map(r=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("div",{className:"text-white",children:r.label}),e.jsx(o,{tone:"meta",children:W(r.durationSeconds)})]}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:G(r.startedAt,r.endedAt??r.startedAt)})]},`${r.type}:${r.startedAt}`))})]}):null,(((M=(y=t.details)==null?void 0:y.components)==null?void 0:M.length)??0)>0?e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Workout phases"}),e.jsx("div",{className:"grid gap-2",children:(D=t.details)==null?void 0:D.components.map(r=>e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("div",{className:"text-white",children:r.activity.canonicalLabel}),e.jsx(o,{tone:"meta",children:W(r.durationSeconds)})]}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:G(r.startedAt,r.endedAt??r.startedAt)})]},r.externalUid))})]}):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:c<w.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(ie,{type:"button",variant:"secondary",onClick:()=>f(Math.max(0,c-1)),disabled:c===0,children:"Back"}),c<w.length-1?e.jsxs(ie,{type:"button",onClick:()=>f(c+1),children:["Next",e.jsx(ke,{className:"size-4"})]}):null,e.jsxs(ie,{type:"button",pending:l,pendingLabel:"Saving",onClick:T,children:[e.jsx(Qe,{className:"size-4"}),"Save session"]})]})]})]})}function Pt(){var je,fe;const t=Ge(),i=Ze(),s=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],[l,c]=u.useState({}),[f,v]=u.useState(""),[T,w]=u.useState([]),[n,x]=u.useState([]),[h,N]=u.useState(""),[b,C]=u.useState("all"),[y,M]=u.useState("rolling_stack"),[D,r]=u.useState(""),[L,Ce]=u.useState(""),[de,Te]=u.useState(!1),[oe,ae]=u.useState(null),[Me,X]=u.useState(0),k=O({queryKey:["forge-fitness",...s],queryFn:async()=>(await rt(s)).fitness}),Re=O({queryKey:["forge-health-values",...s],queryFn:async()=>(await nt(s)).values}),Ee=O({queryKey:["forge-health-patterns",...s],queryFn:async()=>(await lt(s)).patterns}),ze=O({queryKey:["forge-health-behaviors",...s],queryFn:async()=>(await ct(s)).behaviors}),De=O({queryKey:["forge-health-beliefs",...s],queryFn:async()=>(await dt(s)).beliefs}),Fe=O({queryKey:["forge-health-reports",...s],queryFn:async()=>(await ot(s)).reports});u.useEffect(()=>{k.data&&c(Object.fromEntries(k.data.sessions.map(a=>[a.id,Z(a)])))},[k.data]),u.useEffect(()=>{if(de||!k.data)return;const d=(k.data.analysisSessions??k.data.sessions).find(At);d&&x([`type:${d.workoutType}`]),Te(!0)},[de,k.data]);const se=Ue({mutationFn:async a=>Xe(a.workoutId,{subjectiveEffort:a.subjectiveEffort.trim().length>0?Number(a.subjectiveEffort):null,moodBefore:a.moodBefore,moodAfter:a.moodAfter,meaningText:a.meaningText,plannedContext:a.plannedContext,socialContext:a.socialContext,tags:a.tagsText.split(",").map(d=>d.trim()).filter(Boolean),links:mt(a.linkValues)}),onSuccess:async()=>{await i.invalidateQueries({queryKey:["forge-fitness"]})}}),F=k.data,S=(F==null?void 0:F.sessions)??[],K=(F==null?void 0:F.analysisSessions)??S,$e=pt({goals:t.snapshot.dashboard.goals,projects:t.snapshot.dashboard.projects,tasks:t.snapshot.dashboard.tasks,habits:t.snapshot.dashboard.habits,values:Re.data??[],patterns:Ee.data??[],behaviors:ze.data??[],beliefs:De.data??[],reports:Fe.data??[]}),Le=u.useMemo(()=>kt(S),[S]),_e=u.useMemo(()=>Ct(K),[K]),V=u.useMemo(()=>{const a=Se(f);return[...S].sort((d,m)=>new Date(m.startedAt).getTime()-new Date(d.startedAt).getTime()).filter(d=>{const m=l[d.id]??Z(d);return(a.length===0||Nt(d,m).includes(a))&&St(d,T)})},[l,f,T,S]),xe=u.useMemo(()=>Tt(K,n,b,D,L),[b,L,K,D,n]),he=V.length===S.length&&f.trim().length===0&&T.length===0?`${S.length} workout sessions visible`:`${V.length} of ${S.length} workout sessions visible`,R=V.find(a=>a.id===oe)??S.find(a=>a.id===oe)??null,me=R?l[R.id]??Z(R):null;if(k.isLoading)return e.jsx(Ye,{eyebrow:"Sports",title:"Loading sports view",description:"Reading synced workouts and local reflection metadata.",columns:2,blocks:6});if(k.isError||!F)return e.jsx(Je,{eyebrow:"Sports",error:k.error??new Error("Sports data unavailable"),onRetry:()=>void k.refetch()});const{summary:p,weeklyTrend:pe,typeBreakdown:He}=F,ue=p.zoneMix??[],A=Rt(xe,F.vitalsTrend),ge=n.length===0?"All exercise types":A.exerciseLabels.length>0?A.exerciseLabels.join(", "):`${n.length} selected types`,Ke=ue.map(a=>({zone:a.label,minutes:Math.round(a.seconds/60),percentage:Math.round(a.percentage*100),fill:U[a.key]??"#f8fafc"})),Oe=pe.map(a=>{const d=Object.fromEntries((a.zoneDurations??[]).map(m=>[m.key,Math.round(m.seconds/60)]));return{date:a.dateKey.slice(5),duration:a.durationMinutes,load:a.trainingLoad??0,coverage:Math.round((a.heartRateCoverage??0)*100),...d}}),Be=K.map(a=>{var d,m,E,_;return{duration:Math.round(a.durationSeconds/60),intensity:Math.round((((m=(d=a.analytics)==null?void 0:d.load)==null?void 0:m.intensity)??0)*100),load:((_=(E=a.analytics)==null?void 0:E.load)==null?void 0:_.trimp)??0,type:j(a),name:j(a)}});function We(a,d){c(m=>{const E=m[a]??Z(S.find(_=>_.id===a));return{...m,[a]:{...E,...d}}})}async function Ie(a){const d=S.find(E=>E.id===a);if(!d)return;const m=l[a]??Z(d);await se.mutateAsync({workoutId:a,subjectiveEffort:m.subjectiveEffort,moodBefore:m.moodBefore,moodAfter:m.moodAfter,meaningText:m.meaningText,plannedContext:m.plannedContext,socialContext:m.socialContext,tagsText:m.tagsText,linkValues:m.linkValues}),ae(null),X(0)}return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(xt,{entityKind:"project",title:"Sports",description:"A session-first training surface for workout data, subjective meaning, and links back into Forge execution and Psyche.",badge:`${S.length} sessions`}),e.jsx(et,{children:e.jsxs("section",{className:"grid gap-4 lg:grid-cols-4",children:[e.jsxs(g,{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:W(p.weeklyVolumeSeconds)}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Total training time in the recent week."})]}),e.jsxs(g,{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:p.exerciseMinutes}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Aggregate exercise minutes from synced sessions."})]}),e.jsxs(g,{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:p.energyBurnedKcal}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Recent weekly kcal."})]}),e.jsxs(g,{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:p.streakDays}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Distinct workout days in the recent week."})]}),e.jsxs(g,{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:[p.averageSessionMinutes,"m"]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Mean duration across recent sessions."})]}),e.jsxs(g,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Training load"}),e.jsx("div",{className:"mt-3 font-display text-4xl text-white",children:p.totalTrainingLoad??"n/a"}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Forge TRIMP across recent sessions."})]}),e.jsxs(g,{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:p.linkedSessionCount}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Sessions already tied to Forge or Psyche entities."})]}),e.jsxs(g,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"HR coverage"}),e.jsxs("div",{className:"mt-3 font-display text-4xl text-white",children:[Math.round((p.averageHeartRateCoverage??0)*100),"%"]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:"Average raw HR sample coverage."})]})]})}),e.jsx(Y,{children:e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.1fr)_minmax(320px,0.9fr)]",children:[e.jsxs(g,{className:"min-h-[320px]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Load and volume trend"}),e.jsx("div",{className:"mt-4 h-[260px]",children:e.jsx(P,{width:"100%",height:"100%",children:e.jsxs(ut,{data:Oe,children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"sportsLoad",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"#f97316",stopOpacity:.36}),e.jsx("stop",{offset:"100%",stopColor:"#f97316",stopOpacity:.04})]})}),e.jsx(J,{stroke:"rgba(255,255,255,0.08)",vertical:!1}),e.jsx(q,{dataKey:"date",tick:{fill:"rgba(255,255,255,0.55)",fontSize:11}}),e.jsx(B,{tick:{fill:"rgba(255,255,255,0.55)",fontSize:11},width:34}),e.jsx(Q,{contentStyle:{background:"rgba(8,12,22,0.94)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,color:"white"}}),e.jsx(ye,{type:"monotone",dataKey:"load",stroke:"#f97316",fill:"url(#sportsLoad)",strokeWidth:2}),e.jsx(ye,{type:"monotone",dataKey:"duration",stroke:"#38bdf8",fill:"rgba(56,189,248,0.10)",strokeWidth:2})]})})})]}),e.jsxs(g,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Zone distribution"}),e.jsx("div",{className:"mt-4 grid gap-3",children:ue.map(a=>e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm",children:[e.jsx("span",{className:"text-white/72",children:a.label}),e.jsxs("span",{className:"text-white",children:[Math.round(a.percentage*100),"% · ",W(a.seconds)]})]}),e.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-white/[0.08]",children:e.jsx("div",{className:"h-full rounded-full",style:{width:`${Math.max(1,a.percentage*100)}%`,background:U[a.key]??"#f8fafc"}})})]},a.key))}),e.jsx("div",{className:"mt-5 h-[180px]",children:e.jsx(P,{width:"100%",height:"100%",children:e.jsxs(we,{data:Ke,children:[e.jsx(q,{dataKey:"zone",tick:{fill:"rgba(255,255,255,0.55)",fontSize:10}}),e.jsx(B,{tick:{fill:"rgba(255,255,255,0.55)",fontSize:10},width:34}),e.jsx(Q,{contentStyle:{background:"rgba(8,12,22,0.94)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,color:"white"}}),e.jsx(re,{dataKey:"minutes",fill:"#f97316",radius:[4,4,0,0]})]})})})]})]})}),e.jsx(Y,{children:e.jsxs("section",{className:"grid gap-4",children:[e.jsxs(g,{className:"grid gap-4 overflow-hidden",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:"HR zone analysis"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Filter all-time workout evidence by exercise type and date."})]}),e.jsxs(o,{tone:"meta",children:[xe.length," of ",K.length," sessions"]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1fr)_minmax(280px,0.8fr)]",children:[e.jsx(ve,{title:"Exercise types",description:"Select one, many, or none for all exercise types.",query:h,onQueryChange:N,options:_e,selectedOptionIds:n,onSelectedOptionIdsChange:x,resultSummary:ge,placeholder:"Search exercise types",emptyStateMessage:"No exercise type matches."}),e.jsxs("div",{className:"grid gap-3 rounded-[8px] border border-white/8 bg-white/[0.035] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Date range"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:[["all","All time"],["recent_90","90 days"],["custom","Custom"]].map(([a,d])=>e.jsx("button",{type:"button",className:`rounded-[8px] border px-3 py-2 text-sm transition ${b===a?"border-[var(--primary)] bg-[var(--primary)]/12 text-white":"border-white/8 bg-white/[0.04] text-white/62 hover:bg-white/[0.07] hover:text-white"}`,onClick:()=>C(a),children:d},a))}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Start"}),e.jsx($,{type:"date",value:D,onChange:a=>{r(a.target.value),C("custom")}})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"End"}),e.jsx($,{type:"date",value:L,onChange:a=>{Ce(a.target.value),C("custom")}})]})]})]})]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.85fr)_minmax(0,1.15fr)]",children:[e.jsxs(g,{className:"min-h-[330px] overflow-hidden",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:"Average zones"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Duration-weighted proportion of time in each HR zone."})]}),e.jsx(o,{tone:"meta",children:ge})]}),e.jsx("div",{className:"mt-4 h-[235px]",children:A.sessions.length>0?e.jsx(P,{width:"100%",height:"100%",children:e.jsxs(we,{data:A.averageZoneData,children:[e.jsx(J,{stroke:"rgba(255,255,255,0.08)",vertical:!1}),e.jsx(q,{dataKey:"zone",interval:0,tick:{fill:"rgba(255,255,255,0.55)",fontSize:10}}),e.jsx(B,{unit:"%",domain:[0,100],ticks:[0,25,50,75,100],tick:{fill:"rgba(255,255,255,0.55)",fontSize:10},width:38}),e.jsx(Q,{formatter:a=>[`${a}%`,"Average time"],contentStyle:{background:"rgba(8,12,22,0.94)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,color:"white"}}),e.jsx(re,{dataKey:"percentage",radius:[4,4,0,0],children:A.averageZoneData.map(a=>e.jsx(gt,{fill:a.fill},a.key))})]})}):e.jsx("div",{className:"grid h-full place-items-center rounded-[8px] bg-white/[0.035] p-6 text-center text-sm leading-6 text-white/54",children:"No selected sessions with zone analytics are available yet."})}),A.sessions.length>0?e.jsxs("div",{className:"mt-3 grid gap-2 text-sm text-white/58 sm:grid-cols-3",children:[e.jsxs("div",{children:[A.rawHrCount," sessions have raw HR timelines"]}),e.jsxs("div",{children:["Latest:"," ",((je=A.lineData.at(-1))==null?void 0:je.dateKey)??"n/a"]}),e.jsxs("div",{children:["VO2max points:"," ",A.lineData.filter(a=>a.vo2Max!=null).length]})]}):null]}),e.jsxs(g,{className:"min-h-[330px] overflow-hidden",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:y==="expanding_lines"?"Expanding zone lines":"Zone drift"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:y==="expanding_lines"?"Expanding all-session average with resting HR and VO2max overlay.":"Rolling duration-weighted zone mix with resting HR and VO2max overlay."})]}),e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:items-end",children:[e.jsx("div",{className:"grid grid-cols-2 gap-1 rounded-[8px] border border-white/8 bg-white/[0.035] p-1","aria-label":"Zone chart display",children:[["rolling_stack","Stacked"],["expanding_lines","Lines"]].map(([a,d])=>e.jsx("button",{type:"button",className:`min-h-9 rounded-[6px] px-3 py-1.5 text-xs font-medium transition ${y===a?"bg-[var(--primary)]/18 text-white":"text-white/58 hover:bg-white/[0.06] hover:text-white"}`,onClick:()=>M(a),children:d},a))}),e.jsx(o,{tone:"meta",children:"HRR zones"})]})]}),e.jsx("div",{className:"mt-4 h-[255px]",children:A.lineData.length>0?e.jsx(P,{width:"100%",height:"100%",children:e.jsxs(jt,{data:y==="expanding_lines"?A.expandingLineData:A.lineData,children:[e.jsx(J,{stroke:"rgba(255,255,255,0.08)",vertical:!1}),e.jsx(q,{dataKey:"date",tick:{fill:"rgba(255,255,255,0.55)",fontSize:10}}),e.jsx(B,{yAxisId:"zones",domain:[0,100],ticks:[0,25,50,75,100],unit:"%",tick:{fill:"rgba(255,255,255,0.55)",fontSize:10},width:38}),e.jsx(B,{yAxisId:"vitals",orientation:"right",tick:{fill:"rgba(255,255,255,0.55)",fontSize:10},width:42}),e.jsx(Q,{formatter:(a,d,m)=>Mt(a,d,m),contentStyle:{background:"rgba(8,12,22,0.94)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,color:"white"}}),e.jsx(ft,{wrapperStyle:{color:"rgba(255,255,255,0.7)",fontSize:11}}),y==="expanding_lines"?I.map(a=>e.jsx(ne,{yAxisId:"zones",type:"monotone",dataKey:a,name:z(a),stroke:U[a],strokeWidth:2,dot:{r:2.5},activeDot:{r:4},connectNulls:!0},a)):I.map(a=>e.jsx(re,{yAxisId:"zones",dataKey:a,stackId:"zones",fill:U[a],isAnimationActive:!1},a)),e.jsx(ne,{yAxisId:"vitals",type:"monotone",dataKey:"restingHeartRate",name:"Resting HR",stroke:"#e2e8f0",strokeWidth:2,dot:{r:3},connectNulls:!0}),e.jsx(ne,{yAxisId:"vitals",type:"monotone",dataKey:"vo2Max",name:"VO2max",stroke:"#a78bfa",strokeWidth:2,dot:{r:3},connectNulls:!0})]})}):e.jsx("div",{className:"grid h-full place-items-center rounded-[8px] bg-white/[0.035] p-6 text-center text-sm leading-6 text-white/54",children:"Select workouts with HR evidence to unlock the time-series plot."})})]})]})]})}),e.jsx(Y,{children:e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[minmax(0,1fr)_360px]",children:[e.jsxs(g,{className:"min-h-[300px]",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Duration vs intensity"}),e.jsx("div",{className:"mt-4 h-[250px]",children:e.jsx(P,{width:"100%",height:"100%",children:e.jsxs(vt,{data:Be,children:[e.jsx(J,{stroke:"rgba(255,255,255,0.08)"}),e.jsx(q,{type:"number",dataKey:"duration",name:"minutes",tick:{fill:"rgba(255,255,255,0.55)",fontSize:11}}),e.jsx(B,{type:"number",dataKey:"intensity",name:"intensity",tick:{fill:"rgba(255,255,255,0.55)",fontSize:11},width:38}),e.jsx(Q,{cursor:{strokeDasharray:"3 3"},contentStyle:{background:"rgba(8,12,22,0.94)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,color:"white"}}),e.jsx(yt,{dataKey:"load",fill:"#f97316"})]})})})]}),e.jsxs(g,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Evidence quality"}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsxs("div",{className:"rounded-[8px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Raw HR coverage"}),e.jsxs("div",{className:"mt-2 text-2xl text-white",children:[Math.round((p.averageHeartRateCoverage??0)*100),"%"]})]}),e.jsxs("div",{className:"rounded-[8px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Route-backed workouts"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:p.routeWorkoutCount??0})]}),e.jsxs("div",{className:"rounded-[8px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-sm text-white/58",children:"Top sport"}),e.jsx("div",{className:"mt-2 text-lg text-white",children:p.topWorkoutTypeLabel??p.topWorkoutType??"n/a"})]})]})]})]})}),e.jsx(Y,{children:e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[1.05fr_0.95fr]",children:[e.jsxs(g,{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:pe.map(a=>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:a.dateKey}),e.jsx("div",{className:"text-sm text-white",children:a.workoutTypeLabel??z(a.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,a.durationMinutes/120*100)}%`}})}),e.jsxs("div",{className:"text-sm text-white",children:[a.durationMinutes,"m"]})]}),e.jsxs("div",{className:"text-sm text-white/62",children:[a.energyKcal," kcal"]})]},a.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:ce(p.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:p.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:[p.importedSessionCount," / ",p.reconciledSessionCount]})]})]})]}),e.jsxs(g,{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:He.slice(0,6).map(a=>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:a.workoutTypeLabel??z(a.workoutType)}),e.jsxs("div",{className:"mt-1 text-sm text-white/58",children:[a.sessionCount," sessions · ",a.activityFamilyLabel??"Other"]})]}),e.jsxs("div",{className:"text-sm text-white/72",children:[a.totalMinutes,"m"]}),e.jsxs("div",{className:"text-sm text-white/72",children:[a.energyKcal," kcal"]})]},a.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:p.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:p.linkedSessionCount})]})]})]})]})}),e.jsx(tt,{children:e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,25rem)_minmax(0,1fr)]",children:[e.jsx(ve,{title:"Session browser",description:"Search past activities by workout type, source, reconciliation state, or whether they still need context.",query:f,onQueryChange:v,options:Le,selectedOptionIds:T,onSelectedOptionIdsChange:w,resultSummary:he,placeholder:"Search workouts, devices, notes, moods, or filter chips",emptyStateMessage:"Keep typing or pick a filter chip to narrow the activity history."}),e.jsxs(g,{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(o,{tone:"meta",children:he})]}),e.jsx("div",{className:"max-h-[34rem] overflow-y-auto rounded-[8px] border border-white/8 bg-white/[0.03] p-3",children:V.length===0?e.jsx("div",{className:"flex min-h-[18rem] 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:"grid gap-3",children:V.map(a=>{var m,E,_;const d=a.meaningText.trim().length>0||a.moodBefore.trim().length>0||a.moodAfter.trim().length>0||a.tags.length>0||a.links.length>0;return e.jsxs("div",{className:"grid w-full min-w-0 gap-3 rounded-[8px] border border-white/8 bg-white/[0.04] px-4 py-3 text-left transition hover:bg-white/[0.07]",children:[e.jsxs("div",{className:"grid min-w-0 gap-3 sm:flex sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(Ve,{to:`/sports/workouts/${a.id}`,className:"flex min-w-0 items-center gap-2 text-white transition hover:text-[var(--primary)]",children:[e.jsx(Ne,{className:"size-4 shrink-0 text-[var(--primary)]"}),e.jsx("span",{className:"truncate text-base font-medium",children:j(a)})]}),e.jsxs("div",{className:"mt-2 flex min-w-0 items-center gap-2 text-sm text-white/56",children:[e.jsx(Pe,{className:"size-3.5 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate",children:G(a.startedAt,a.endedAt)})]}),e.jsxs("div",{className:"mt-2 text-sm text-white/46",children:[H(a)," · ",a.sourceDevice]})]}),e.jsxs("button",{type:"button","aria-label":`Edit ${j(a)} reflection`,className:"inline-flex w-fit max-w-full items-center gap-2 rounded-full bg-white/[0.05] px-3 py-1.5 text-xs text-white/70 transition hover:bg-white/[0.08] hover:text-white",onClick:()=>{ae(a.id),X(0)},children:[e.jsx("span",{className:"truncate",children:d?"Reflected":"Needs reflection"}),e.jsx(ke,{className:"size-3.5 shrink-0"})]})]}),e.jsxs("div",{className:"flex min-w-0 flex-wrap gap-2",children:[e.jsx(o,{children:W(a.durationSeconds)}),a.totalEnergyKcal?e.jsxs(o,{tone:"meta",children:[Math.round(a.totalEnergyKcal)," kcal"]}):null,a.distanceMeters?e.jsx(o,{tone:"meta",children:ce(a.distanceMeters)}):null,a.averageHeartRate?e.jsxs(o,{tone:"meta",children:[e.jsx(qe,{className:"mr-1 size-3.5"}),Math.round(a.averageHeartRate)," bpm"]}):null,e.jsx(o,{tone:"meta",children:H(a)}),e.jsx(o,{tone:"meta",className:"capitalize",children:a.sourceType.replaceAll("_"," ")}),e.jsx(o,{tone:"meta",className:"capitalize",children:a.reconciliationStatus.replaceAll("_"," ")}),(m=a.analytics)!=null&&m.confidence?e.jsxs(o,{tone:"meta",children:[a.analytics.confidence," zones"]}):null,(_=(E=a.analytics)==null?void 0:E.routeSummary)!=null&&_.hasRoute?e.jsx(o,{tone:"meta",children:"Route"}):null]})]},a.id)})})})]})]})}),R&&me?e.jsx(at,{open:!!R,onOpenChange:a=>{a||(ae(null),X(0))},eyebrow:"Sports session",title:j(R),description:"Add contextual meaning without crowding the main training surface.",children:e.jsx(Et,{session:R,draft:me,linkOptions:$e,pending:se.isPending&&((fe=se.variables)==null?void 0:fe.workoutId)===R.id,step:Me,onStepChange:X,onDraftChange:a=>We(R.id,a),onSave:()=>void Ie(R.id)})}):null]})}export{Pt as SportsPage,Mt as formatZoneTrendTooltipValue};
@@ -1 +1 @@
1
- import{b5 as U,c2 as z,r,j as e,b4 as A,b3 as O,ce as Q,c7 as $}from"./vendor-DHkYh85p.js";import{j as F,k as I}from"./state-B-4sS1xO.js";import{b as G,S as R}from"./strategy-dialog-BvzomTaF.js";import{P as H}from"./page-hero-CQWo1Mm_.js";import{u as K,s as _,c0 as J,c1 as V,c2 as W,B as d,C as M,I as X,a as Y,U as Z,c as x}from"./index-BHTUu_4M.js";import"./board-BkDRaMp6.js";import"./ui-C13Nbgas.js";import"./motion-BeD44FeG.js";import"./forms-BFlTgZ3W.js";import"./graph-D6JLqDbD.js";function ee(a){return a.trim().toLowerCase()}function xe(){const a=K(),u=U(),B=F(),[j,w]=z(),[E,c]=r.useState(!1),[T,o]=r.useState(null),[m,D]=r.useState(""),L=_(a.selectedUserIds);r.useEffect(()=>{j.get("create")==="1"&&(o(null),c(!0),w(s=>{const t=new URLSearchParams(s);return t.delete("create"),t},{replace:!0}))},[j,w]);const v=async()=>{await B.invalidateQueries({queryKey:["strategy-detail"]}),await a.refresh()},N=I({mutationFn:async({input:s,strategyId:t})=>t?(await J(t,s)).strategy:(await V(s)).strategy,onSuccess:async()=>{await v()}}),p=I({mutationFn:async s=>W(s),onSuccess:async()=>{await v()}}),b=r.useMemo(()=>new Map(a.snapshot.goals.map(s=>[s.id,s])),[a.snapshot.goals]),h=r.useMemo(()=>new Map(a.snapshot.dashboard.projects.map(s=>[s.id,s])),[a.snapshot.dashboard.projects]),f=r.useMemo(()=>new Map(a.snapshot.tasks.map(s=>[s.id,s])),[a.snapshot.tasks]),S=r.useMemo(()=>{const s=ee(m);return s?a.snapshot.strategies.filter(t=>{var k,y,C;const g=t.targetGoalIds.map(l=>{var n;return((n=b.get(l))==null?void 0:n.title)??""}).join(" "),i=t.targetProjectIds.map(l=>{var n;return((n=h.get(l))==null?void 0:n.title)??""}).join(" "),q=t.graph.nodes.map(l=>{var n,P;return l.entityType==="project"?((n=h.get(l.entityId))==null?void 0:n.title)??"":((P=f.get(l.entityId))==null?void 0:P.title)??""}).join(" ");return[t.title,t.overview,t.endStateDescription,t.status,((k=t.user)==null?void 0:k.displayName)??"",((y=t.user)==null?void 0:y.handle)??"",((C=t.user)==null?void 0:C.kind)??"",g,i,q].join(" ").toLowerCase().includes(s)}):a.snapshot.strategies},[b,h,m,a.snapshot.strategies,f]);return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(H,{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:`${a.snapshot.strategies.length} strategies`,actions:e.jsxs(d,{onClick:()=>{o(null),c(!0)},children:[e.jsx(A,{className:"size-4"}),"New strategy"]})}),e.jsxs(M,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(O,{className:"size-4 text-white/38"}),e.jsx(X,{value:m,onChange:s=>D(s.target.value),placeholder:"Search strategy title, target, graph node, human, or bot"})]}),e.jsx("div",{className:"text-sm text-white/56",children:"Search includes owners, target goals/projects, and graph nodes so cross-user plans stay discoverable."})]}),S.length===0?e.jsx(Y,{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(d,{onClick:()=>{o(null),c(!0)},children:"Create strategy"})}):e.jsx("div",{className:"grid gap-4",children:S.map(s=>{const t=s.graph.nodes.filter(i=>s.metrics.activeNodeIds.includes(i.id)),g=G(s.metrics);return e.jsxs(M,{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:()=>u(`/strategies/${s.id}`),children:[e.jsx("div",{className:"font-display text-2xl text-white",children:s.title}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:s.overview||s.endStateDescription})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Z,{user:s.user}),e.jsx(x,{className:s.isLocked?"bg-amber-500/12 text-amber-200":"bg-emerald-500/12 text-emerald-200",children:s.isLocked?"Contract locked":"Editable draft"}),e.jsx(x,{className:"bg-white/[0.08] text-white/78",children:s.status}),e.jsxs(x,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[s.metrics.alignmentScore,"% aligned"]})]})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Graph progress"}),e.jsxs("div",{className:"mt-2 text-xl text-white",children:[s.metrics.startedNodeCount,"/",s.metrics.totalNodeCount]}),e.jsxs("div",{className:"text-xs leading-5 text-white/46",children:[s.metrics.completedNodeCount," completed"]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Ready branches"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:s.metrics.readyNodeCount}),e.jsx("div",{className:"text-xs leading-5 text-white/46",children:"Nodes whose prerequisites are already satisfied."})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"End targets"}),e.jsxs("div",{className:"mt-2 text-xl text-white",children:[s.metrics.completedTargetCount,"/",s.metrics.totalTargetCount||0]}),e.jsxs("div",{className:"text-xs leading-5 text-white/46",children:[s.metrics.targetProgressScore,"% target progress"]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Sequencing"}),e.jsxs("div",{className:"mt-2 text-xl text-white",children:[s.metrics.sequencingScore,"%"]})]})]}),e.jsxs("div",{className:"grid gap-3 xl:grid-cols-[minmax(0,1.2fr)_minmax(16rem,0.8fr)]",children:[e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Active next nodes"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:t.length===0?e.jsx("div",{className:"text-sm text-white/52",children:"No currently open branch."}):t.map(i=>e.jsx(x,{className:"bg-white/[0.08] text-white/80",children:i.title},i.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:g.map(i=>e.jsxs("div",{children:[i.label," ",i.value,"%"]},i.id))})]})]})}),e.jsxs("div",{className:"flex flex-wrap items-end justify-end gap-2",children:[s.isLocked?null:e.jsxs(d,{variant:"secondary",onClick:()=>{o(s),c(!0)},children:[e.jsx(Q,{className:"size-4"}),"Edit"]}),e.jsxs(d,{variant:"secondary",pending:p.isPending&&p.variables===s.id,pendingLabel:"Deleting strategy",onClick:()=>{window.confirm(`Delete strategy "${s.title}"?`)&&p.mutateAsync(s.id)},children:[e.jsx($,{className:"size-4"}),"Delete"]}),e.jsx(d,{onClick:()=>u(`/strategies/${s.id}`),children:"Open strategy"})]})]})]},s.id)})}),e.jsx(R,{open:E,pending:N.isPending,editingStrategy:T,goals:a.snapshot.dashboard.goals,projects:a.snapshot.dashboard.projects,tasks:a.snapshot.tasks,habits:a.snapshot.habits,strategies:a.snapshot.strategies,users:a.snapshot.users,defaultUserId:L,onOpenChange:c,onSubmit:async(s,t)=>{await N.mutateAsync({input:s,strategyId:t})}})]})}export{xe as StrategiesPage};
1
+ import{b5 as U,c2 as z,r,j as e,b4 as A,b3 as O,ce as Q,c7 as $}from"./vendor-DHkYh85p.js";import{j as F,k as I}from"./state-B-4sS1xO.js";import{b as G,S as R}from"./strategy-dialog-D3AuUlVz.js";import{P as H}from"./page-hero-DRy5b2MU.js";import{u as K,s as _,c0 as J,c1 as V,c2 as W,B as d,C as M,I as X,a as Y,U as Z,c as x}from"./index-CF4J4R9L.js";import"./board-BkDRaMp6.js";import"./ui-C13Nbgas.js";import"./motion-BeD44FeG.js";import"./forms-BFlTgZ3W.js";import"./graph-D6JLqDbD.js";function ee(a){return a.trim().toLowerCase()}function xe(){const a=K(),u=U(),B=F(),[j,w]=z(),[E,c]=r.useState(!1),[T,o]=r.useState(null),[m,D]=r.useState(""),L=_(a.selectedUserIds);r.useEffect(()=>{j.get("create")==="1"&&(o(null),c(!0),w(s=>{const t=new URLSearchParams(s);return t.delete("create"),t},{replace:!0}))},[j,w]);const v=async()=>{await B.invalidateQueries({queryKey:["strategy-detail"]}),await a.refresh()},N=I({mutationFn:async({input:s,strategyId:t})=>t?(await J(t,s)).strategy:(await V(s)).strategy,onSuccess:async()=>{await v()}}),p=I({mutationFn:async s=>W(s),onSuccess:async()=>{await v()}}),b=r.useMemo(()=>new Map(a.snapshot.goals.map(s=>[s.id,s])),[a.snapshot.goals]),h=r.useMemo(()=>new Map(a.snapshot.dashboard.projects.map(s=>[s.id,s])),[a.snapshot.dashboard.projects]),f=r.useMemo(()=>new Map(a.snapshot.tasks.map(s=>[s.id,s])),[a.snapshot.tasks]),S=r.useMemo(()=>{const s=ee(m);return s?a.snapshot.strategies.filter(t=>{var k,y,C;const g=t.targetGoalIds.map(l=>{var n;return((n=b.get(l))==null?void 0:n.title)??""}).join(" "),i=t.targetProjectIds.map(l=>{var n;return((n=h.get(l))==null?void 0:n.title)??""}).join(" "),q=t.graph.nodes.map(l=>{var n,P;return l.entityType==="project"?((n=h.get(l.entityId))==null?void 0:n.title)??"":((P=f.get(l.entityId))==null?void 0:P.title)??""}).join(" ");return[t.title,t.overview,t.endStateDescription,t.status,((k=t.user)==null?void 0:k.displayName)??"",((y=t.user)==null?void 0:y.handle)??"",((C=t.user)==null?void 0:C.kind)??"",g,i,q].join(" ").toLowerCase().includes(s)}):a.snapshot.strategies},[b,h,m,a.snapshot.strategies,f]);return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(H,{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:`${a.snapshot.strategies.length} strategies`,actions:e.jsxs(d,{onClick:()=>{o(null),c(!0)},children:[e.jsx(A,{className:"size-4"}),"New strategy"]})}),e.jsxs(M,{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(O,{className:"size-4 text-white/38"}),e.jsx(X,{value:m,onChange:s=>D(s.target.value),placeholder:"Search strategy title, target, graph node, human, or bot"})]}),e.jsx("div",{className:"text-sm text-white/56",children:"Search includes owners, target goals/projects, and graph nodes so cross-user plans stay discoverable."})]}),S.length===0?e.jsx(Y,{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(d,{onClick:()=>{o(null),c(!0)},children:"Create strategy"})}):e.jsx("div",{className:"grid gap-4",children:S.map(s=>{const t=s.graph.nodes.filter(i=>s.metrics.activeNodeIds.includes(i.id)),g=G(s.metrics);return e.jsxs(M,{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:()=>u(`/strategies/${s.id}`),children:[e.jsx("div",{className:"font-display text-2xl text-white",children:s.title}),e.jsx("div",{className:"mt-2 max-w-3xl text-sm leading-6 text-white/58",children:s.overview||s.endStateDescription})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Z,{user:s.user}),e.jsx(x,{className:s.isLocked?"bg-amber-500/12 text-amber-200":"bg-emerald-500/12 text-emerald-200",children:s.isLocked?"Contract locked":"Editable draft"}),e.jsx(x,{className:"bg-white/[0.08] text-white/78",children:s.status}),e.jsxs(x,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[s.metrics.alignmentScore,"% aligned"]})]})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Graph progress"}),e.jsxs("div",{className:"mt-2 text-xl text-white",children:[s.metrics.startedNodeCount,"/",s.metrics.totalNodeCount]}),e.jsxs("div",{className:"text-xs leading-5 text-white/46",children:[s.metrics.completedNodeCount," completed"]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Ready branches"}),e.jsx("div",{className:"mt-2 text-xl text-white",children:s.metrics.readyNodeCount}),e.jsx("div",{className:"text-xs leading-5 text-white/46",children:"Nodes whose prerequisites are already satisfied."})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"End targets"}),e.jsxs("div",{className:"mt-2 text-xl text-white",children:[s.metrics.completedTargetCount,"/",s.metrics.totalTargetCount||0]}),e.jsxs("div",{className:"text-xs leading-5 text-white/46",children:[s.metrics.targetProgressScore,"% target progress"]})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/40",children:"Sequencing"}),e.jsxs("div",{className:"mt-2 text-xl text-white",children:[s.metrics.sequencingScore,"%"]})]})]}),e.jsxs("div",{className:"grid gap-3 xl:grid-cols-[minmax(0,1.2fr)_minmax(16rem,0.8fr)]",children:[e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4",children:e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Active next nodes"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:t.length===0?e.jsx("div",{className:"text-sm text-white/52",children:"No currently open branch."}):t.map(i=>e.jsx(x,{className:"bg-white/[0.08] text-white/80",children:i.title},i.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:g.map(i=>e.jsxs("div",{children:[i.label," ",i.value,"%"]},i.id))})]})]})}),e.jsxs("div",{className:"flex flex-wrap items-end justify-end gap-2",children:[s.isLocked?null:e.jsxs(d,{variant:"secondary",onClick:()=>{o(s),c(!0)},children:[e.jsx(Q,{className:"size-4"}),"Edit"]}),e.jsxs(d,{variant:"secondary",pending:p.isPending&&p.variables===s.id,pendingLabel:"Deleting strategy",onClick:()=>{window.confirm(`Delete strategy "${s.title}"?`)&&p.mutateAsync(s.id)},children:[e.jsx($,{className:"size-4"}),"Delete"]}),e.jsx(d,{onClick:()=>u(`/strategies/${s.id}`),children:"Open strategy"})]})]})]},s.id)})}),e.jsx(R,{open:E,pending:N.isPending,editingStrategy:T,goals:a.snapshot.dashboard.goals,projects:a.snapshot.dashboard.projects,tasks:a.snapshot.tasks,habits:a.snapshot.habits,strategies:a.snapshot.strategies,users:a.snapshot.users,defaultUserId:L,onOpenChange:c,onSubmit:async(s,t)=>{await N.mutateAsync({input:s,strategyId:t})}})]})}export{xe as StrategiesPage};
@@ -1 +1 @@
1
- import{r as h,j as e,cA as W,cx as K,cF as V,cC as J,aC as A,cc as X,b5 as Y}from"./vendor-DHkYh85p.js";import{j as Z,i as ee,k as D}from"./state-B-4sS1xO.js";import{O as te}from"./open-in-graph-button-Cg5VrKsC.js";import{P as se}from"./preference-entity-handoff-button-D4WAs9pC.js";import{a as ae,i as ie,b as re,S as ne}from"./strategy-dialog-BvzomTaF.js";import{i as le,C as de,B as oe,M as ce}from"./graph-D6JLqDbD.js";import{c as m,U as M,u as xe,s as pe,c0 as z,c2 as me,L as ge,E as G,B as L,C as k,W as he,bq as ue,c3 as be}from"./index-BHTUu_4M.js";import{P as fe}from"./page-hero-CQWo1Mm_.js";import"./board-BkDRaMp6.js";import"./ui-C13Nbgas.js";import"./motion-BeD44FeG.js";import"./forms-BFlTgZ3W.js";function Q(a){const r=new Map;for(const i of a.nodes)r.set(i.id,[]);for(const i of a.edges)r.set(i.to,[...r.get(i.to)??[],i.from]);const l=new Map,o=i=>{const c=l.get(i);if(c!==void 0)return c;const y=r.get(i)??[],u=y.length===0?0:Math.max(...y.map(n=>o(n)))+1;return l.set(i,u),u};for(const i of a.nodes)o(i.id);return l}function je(a){const r=Q(a),l=new Map;for(const o of a.nodes){const i=r.get(o.id)??0;l.set(i,[...l.get(i)??[],o.id])}return Array.from(l.entries()).sort((o,i)=>o[0]-i[0]).map(([o,i])=>({level:o,nodeIds:i}))}function ye(a,r){const l=Q(a.graph),o=new Map;for(const i of a.graph.nodes){const c=l.get(i.id)??0;o.set(c,[...o.get(c)??[],i.id])}return a.graph.nodes.map(i=>{const c=l.get(i.id)??0,y=(o.get(c)??[]).indexOf(i.id),u=a.metrics.activeNodeIds.includes(i.id),n=a.metrics.blockedNodeIds.includes(i.id),p=a.metrics.outOfOrderNodeIds.includes(i.id),f=!u&&!n&&!p,t=(r==null?void 0:r.get(i.id))??null;let g="border-white/10 bg-[rgba(8,14,26,0.92)]";return u?g="border-emerald-400/30 bg-emerald-500/[0.08]":n?g="border-rose-400/28 bg-rose-500/[0.08]":p?g="border-amber-400/28 bg-amber-500/[0.08]":a.metrics.completedNodeCount>0&&(g="border-sky-400/20 bg-sky-500/[0.05]"),{id:i.id,position:{x:72+c*308,y:56+y*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)] ${g}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(m,{className:"bg-white/[0.08] text-white/74",children:i.entityType}),u?e.jsx(m,{className:"bg-emerald-500/12 text-emerald-200",children:"Active"}):null,n?e.jsx(m,{className:"bg-rose-500/12 text-rose-200",children:"Blocked"}):null,p?e.jsx(m,{className:"bg-amber-500/12 text-amber-200",children:"Out of order"}):null,f&&!n&&!p?e.jsx(m,{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:i.title}),i.branchLabel?e.jsx("div",{className:"mt-2 text-xs uppercase tracking-[0.16em] text-white/45",children:i.branchLabel}):null,i.notes?e.jsx("div",{className:"mt-2 text-sm leading-5 text-white/56",children:i.notes}):null,t?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:t.color}}),e.jsx("span",{children:t.label})]}):null]})},style:{background:"transparent",border:"none",padding:0}}})}function we(a){return a.graph.edges.map(r=>{const l=a.metrics.activeNodeIds.includes(r.to),o=a.metrics.blockedNodeIds.includes(r.to),i=a.metrics.outOfOrderNodeIds.includes(r.to);let c="rgba(255,255,255,0.3)";return l?c="#4ade80":o?c="#fb7185":i&&(c="#f59e0b"),{id:`${r.from}->${r.to}`,source:r.from,target:r.to,label:r.label||void 0,animated:l,markerEnd:{type:ce.ArrowClosed,color:c},style:{stroke:c,strokeWidth:l?2.4:1.5},labelStyle:{fill:"rgba(255,255,255,0.56)",fontSize:11,fontWeight:600}}})}function ve({strategy:a,ownerByNodeId:r,heightClassName:l="h-[540px]"}){const o=h.useMemo(()=>ye(a,r),[r,a]),i=h.useMemo(()=>we(a),[a]);return e.jsx("div",{className:`${l} 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(le,{fitView:!0,nodes:o,edges:i,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!1,attributionPosition:"bottom-left",children:[e.jsx(de,{showInteractive:!1}),e.jsx(oe,{gap:28,size:1,color:"rgba(255,255,255,0.06)"})]})})}function Ne(a,r){const l=a.metrics.activeNodeIds.includes(r),o=a.metrics.blockedNodeIds.includes(r),i=a.metrics.outOfOrderNodeIds.includes(r);return o?{label:"Blocked",className:"bg-rose-500/12 text-rose-200"}:i?{label:"Out of order",className:"bg-amber-500/12 text-amber-200"}:l?{label:"Ready now",className:"bg-emerald-500/12 text-emerald-200"}:{label:"In plan",className:"bg-sky-500/12 text-sky-200"}}function ke({strategy:a,projectsById:r,tasksById:l,className:o}){const i=h.useMemo(()=>je(a.graph),[a.graph]),c=h.useMemo(()=>{const n=new Map;for(const p of a.graph.nodes)n.set(p.id,[]);for(const p of a.graph.edges)n.set(p.to,[...n.get(p.to)??[],p.from]);return n},[a.graph]),[y,u]=h.useState([]);return e.jsxs("div",{className:o??"grid gap-3",children:[i.map(n=>{const p=y.includes(n.level),f=n.level===0?"Launch phase":`Phase ${n.level+1}`,t=n.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:()=>u(g=>p?g.filter(d=>d!==n.level):[...g,n.level]),children:[e.jsx("span",{className:"rounded-full bg-white/[0.06] p-2 text-white/72",children:p?e.jsx(W,{className:"size-4"}):e.jsx(K,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:f}),e.jsx("div",{className:"mt-1 text-sm text-white/60",children:t?"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(m,{className:"bg-white/[0.08] text-white/76",children:[n.nodeIds.length," node",n.nodeIds.length===1?"":"s"]}),e.jsx(m,{className:"bg-white/[0.08] text-white/76",children:t?e.jsxs(e.Fragment,{children:[e.jsx(V,{className:"mr-1 size-3.5"}),"Parallel"]}):e.jsxs(e.Fragment,{children:[e.jsx(J,{className:"mr-1 size-3.5"}),"Sequential"]})})]})]}),p?null:e.jsx("div",{className:"grid gap-3 border-t border-white/8 px-4 py-4 lg:grid-cols-2",children:n.nodeIds.map(g=>{var O,N,P;const d=a.graph.nodes.find(b=>b.id===g);if(!d)return null;const v=d.entityType==="project"?r.get(d.entityId):l.get(d.entityId),T=d.entityType==="project"?`/projects/${d.entityId}`:`/tasks/${d.entityId}`,I=d.entityType==="project"?(O=r.get(d.entityId))==null?void 0:O.user:(N=l.get(d.entityId))==null?void 0:N.user,j=((P=c.get(d.id))==null?void 0:P.map(b=>{var $;return(($=a.graph.nodes.find(B=>B.id===b))==null?void 0:$.title)??b}))??[],w=Ne(a,d.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(m,{className:"bg-white/[0.08] text-white/76",children:d.entityType}),e.jsx(m,{className:w.className,children:w.label})]}),e.jsx(A,{to:T,className:"mt-3 block text-lg font-medium text-white transition hover:text-[var(--primary)]",children:d.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:d.notes||("description"in(v??{})?v==null?void 0:v.description:"")||"No extra step note attached yet."})]}),e.jsx(M,{user:I,compact:!0})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[d.branchLabel?e.jsx(m,{className:"bg-[rgba(192,193,255,0.12)] text-white/82",children:d.branchLabel}):null,j.length===0?e.jsx(m,{className:"bg-emerald-500/10 text-emerald-200",children:"Start node"}):j.map(b=>e.jsxs(m,{className:"bg-white/[0.08] text-white/70",children:["Depends on ",b]},`${d.id}:${b}`))]})]},d.id)})})]},n.level)}),i.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 Ee(){var B;const a=xe(),{strategyId:r}=X(),l=Y(),o=Z(),[i,c]=h.useState(!1),[y,u]=h.useState(),n=pe(a.selectedUserIds),p=a.snapshot.strategies.find(s=>s.id===r)??null,f=ee({queryKey:["strategy-detail",r],queryFn:async()=>(await be(r)).strategy,enabled:!!(r&&!p)}),t=p??f.data??null,g=async()=>{await Promise.all([o.invalidateQueries({queryKey:["strategy-detail",r]}),a.refresh()])},d=D({mutationFn:async({input:s,currentStrategyId:x})=>(await z(x,s)).strategy,onSuccess:g}),v=D({mutationFn:async s=>me(s),onSuccess:async()=>{await g(),l("/strategies")}}),T=D({mutationFn:async s=>(await z(r,{isLocked:s,lockedByUserId:s?n??(t==null?void 0:t.userId)??"user_operator":null})).strategy,onSuccess:g}),I=h.useMemo(()=>new Map(a.snapshot.goals.map(s=>[s.id,s])),[a.snapshot.goals]),j=h.useMemo(()=>new Map(a.snapshot.dashboard.projects.map(s=>[s.id,s])),[a.snapshot.dashboard.projects]),w=h.useMemo(()=>new Map(a.snapshot.tasks.map(s=>[s.id,s])),[a.snapshot.tasks]),O=h.useMemo(()=>t?new Map(t.graph.nodes.map(s=>{var S,C;const x=s.entityType==="project"?(S=j.get(s.entityId))==null?void 0:S.user:(C=w.get(s.entityId))==null?void 0:C.user;return[s.id,x?{label:`${x.displayName} (${x.kind})`,color:x.accentColor}:null]})):new Map,[j,t,w]),N=t??{title:"",overview:"",endStateDescription:"",targetGoalIds:[],targetProjectIds:[],graph:{nodes:[],edges:[]}},P=h.useMemo(()=>ae(N),[N]),b=h.useMemo(()=>ie(N),[N]),$=h.useMemo(()=>re((t==null?void 0:t.metrics)??{planCoverageScore:0,sequencingScore:0,scopeDisciplineScore:0,qualityScore:0,targetProgressScore:0,startedNodeCount:0,totalNodeCount:1,offPlanEntityCount:0,offPlanActiveEntityCount:0,blockedNodeIds:[],outOfOrderNodeIds:[]}),[t==null?void 0:t.metrics]);return f.isLoading&&!t?e.jsx(ge,{eyebrow:"Strategy",title:"Loading strategy",description:"Resolving the directed plan, targets, and current alignment."}):f.isError?e.jsx(G,{eyebrow:"Strategy",error:f.error,onRetry:()=>void f.refetch()}):t?e.jsxs("div",{className:"grid gap-5",children:[e.jsx(fe,{title:t.title,titleText:t.title,description:t.overview||t.endStateDescription,badge:`${t.metrics.alignmentScore}% aligned`,actions:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(se,{userId:n,domain:"strategies",entityType:"strategy",entityId:t.id,label:t.title,description:t.overview||t.endStateDescription}),e.jsx(te,{entityType:"strategy",entityId:t.id}),t.isLocked?null:e.jsx(L,{variant:"secondary",onClick:()=>{u(void 0),c(!0)},children:"Edit strategy"}),e.jsx(L,{variant:"secondary",disabled:!t.isLocked&&!b,pending:T.isPending,pendingLabel:t.isLocked?"Unlocking contract":"Locking contract",onClick:()=>{T.mutateAsync(!t.isLocked)},children:t.isLocked?"Unlock contract":"Lock as contract"}),e.jsx(L,{variant:"secondary",pending:v.isPending,pendingLabel:"Deleting strategy",onClick:()=>{window.confirm(`Delete strategy "${t.title}"?`)&&v.mutateAsync(t.id)},children:"Delete"})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(M,{user:t.user}),e.jsx(m,{className:t.isLocked?"bg-amber-500/12 text-amber-200":"bg-emerald-500/12 text-emerald-200",children:t.isLocked?"Contract locked":"Editable draft"}),e.jsx(m,{className:"bg-white/[0.08] text-white/76",children:t.status}),e.jsxs(m,{className:"bg-white/[0.08] text-white/76",children:[t.graph.nodes.length," nodes"]}),e.jsxs(m,{className:"bg-white/[0.08] text-white/76",children:[t.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(k,{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:t.endStateDescription||"No end-state description yet."})]}),e.jsxs(k,{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."})]}),t.isLocked?null:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(L,{variant:"secondary",onClick:()=>{u("sequence"),c(!0)},children:"Refine sequence"}),e.jsx(L,{onClick:()=>{u("sequence"),c(!0)},children:"Add parallel work"})]})]}),e.jsx(ve,{strategy:t,ownerByNodeId:O}),e.jsx(ke,{strategy:t,projectsById:j,tasksById:w})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(k,{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:t.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."}),t.isLocked?e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-sm text-white/60",children:[e.jsxs("span",{children:["Locked by"," ",((B=t.lockedByUser)==null?void 0:B.displayName)??"Unknown user"]}),t.lockedAt?e.jsxs("span",{children:["· ",new Date(t.lockedAt).toLocaleString()]}):null]}):null,t.isLocked?null:e.jsx("div",{className:"mt-4 grid gap-2",children:P.map(s=>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:s.label}),e.jsx(m,{className:s.satisfied?"bg-emerald-500/12 text-emerald-200":"bg-amber-500/12 text-amber-200",children:s.satisfied?"Ready":"Missing"})]},s.id))})]}),!t.isLocked&&!b?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,t.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(k,{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:[t.metrics.alignmentScore,"%"]}),e.jsxs("div",{className:"mt-3 text-xs leading-5 text-white/48",children:[t.metrics.startedNodeCount,"/",t.metrics.totalNodeCount," planned nodes started,"," ",t.metrics.completedNodeCount," completed,"," ",t.metrics.readyNodeCount," ready now."]})]}),$.map(s=>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:s.label}),e.jsxs("div",{className:"text-sm font-medium text-white",children:[s.value,"%"]})]}),e.jsx(he,{value:s.value,className:"mt-3"}),e.jsx("div",{className:"mt-3 text-xs leading-5 text-white/48",children:s.detail})]},s.id))]}),e.jsxs(k,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"End targets"}),t.targetGoalIds.map(s=>{const x=I.get(s);return x?e.jsx(A,{to:`/goals/${x.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: ",x.title]}),e.jsx(M,{user:x.user,compact:!0})]})},x.id):null}),t.targetProjectIds.map(s=>{const x=j.get(s);return x?e.jsx(A,{to:`/projects/${x.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: ",x.title]}),e.jsx(M,{user:x.user,compact:!0})]})},x.id):null}),t.targetGoalIds.length===0&&t.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(k,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Linked entities"}),t.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."}):t.linkedEntities.map(s=>{var C,E,q,_,F,R,U;const x=ue(s.entityType,s.entityId),S=s.entityType==="goal"?(C=I.get(s.entityId))==null?void 0:C.title:s.entityType==="project"?(E=j.get(s.entityId))==null?void 0:E.title:s.entityType==="task"?(q=w.get(s.entityId))==null?void 0:q.title:`${s.entityType}:${s.entityId}`;return x?e.jsx(A,{to:x,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:S}),e.jsx(M,{user:s.entityType==="goal"?(_=I.get(s.entityId))==null?void 0:_.user:s.entityType==="project"?(F=j.get(s.entityId))==null?void 0:F.user:s.entityType==="task"?(R=w.get(s.entityId))==null?void 0:R.user:s.entityType==="strategy"?(U=a.snapshot.strategies.find(H=>H.id===s.entityId))==null?void 0:U.user:null,compact:!0})]})},`${s.entityType}:${s.entityId}`):e.jsx("div",{className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/52",children:S},`${s.entityType}:${s.entityId}`)})]})]})]}),e.jsx(ne,{open:i,pending:d.isPending,editingStrategy:t,goals:a.snapshot.dashboard.goals,projects:a.snapshot.dashboard.projects,tasks:a.snapshot.tasks,habits:a.snapshot.habits,strategies:a.snapshot.strategies,users:a.snapshot.users,defaultUserId:n,initialStepId:y,onOpenChange:s=>{c(s),s||u(void 0)},onSubmit:async s=>{await d.mutateAsync({input:s,currentStrategyId:t.id})}})]}):e.jsx(G,{eyebrow:"Strategy",error:new Error("Strategy not found."),onRetry:()=>l("/strategies")})}export{Ee as StrategyDetailPage};
1
+ import{r as h,j as e,cA as W,cx as K,cF as V,cC as J,aC as A,cc as X,b5 as Y}from"./vendor-DHkYh85p.js";import{j as Z,i as ee,k as D}from"./state-B-4sS1xO.js";import{O as te}from"./open-in-graph-button-IXe9SGth.js";import{P as se}from"./preference-entity-handoff-button-5PzUn42S.js";import{a as ae,i as ie,b as re,S as ne}from"./strategy-dialog-D3AuUlVz.js";import{i as le,C as de,B as oe,M as ce}from"./graph-D6JLqDbD.js";import{c as m,U as M,u as xe,s as pe,c0 as z,c2 as me,L as ge,E as G,B as L,C as k,W as he,bq as ue,c3 as be}from"./index-CF4J4R9L.js";import{P as fe}from"./page-hero-DRy5b2MU.js";import"./board-BkDRaMp6.js";import"./ui-C13Nbgas.js";import"./motion-BeD44FeG.js";import"./forms-BFlTgZ3W.js";function Q(a){const r=new Map;for(const i of a.nodes)r.set(i.id,[]);for(const i of a.edges)r.set(i.to,[...r.get(i.to)??[],i.from]);const l=new Map,o=i=>{const c=l.get(i);if(c!==void 0)return c;const y=r.get(i)??[],u=y.length===0?0:Math.max(...y.map(n=>o(n)))+1;return l.set(i,u),u};for(const i of a.nodes)o(i.id);return l}function je(a){const r=Q(a),l=new Map;for(const o of a.nodes){const i=r.get(o.id)??0;l.set(i,[...l.get(i)??[],o.id])}return Array.from(l.entries()).sort((o,i)=>o[0]-i[0]).map(([o,i])=>({level:o,nodeIds:i}))}function ye(a,r){const l=Q(a.graph),o=new Map;for(const i of a.graph.nodes){const c=l.get(i.id)??0;o.set(c,[...o.get(c)??[],i.id])}return a.graph.nodes.map(i=>{const c=l.get(i.id)??0,y=(o.get(c)??[]).indexOf(i.id),u=a.metrics.activeNodeIds.includes(i.id),n=a.metrics.blockedNodeIds.includes(i.id),p=a.metrics.outOfOrderNodeIds.includes(i.id),f=!u&&!n&&!p,t=(r==null?void 0:r.get(i.id))??null;let g="border-white/10 bg-[rgba(8,14,26,0.92)]";return u?g="border-emerald-400/30 bg-emerald-500/[0.08]":n?g="border-rose-400/28 bg-rose-500/[0.08]":p?g="border-amber-400/28 bg-amber-500/[0.08]":a.metrics.completedNodeCount>0&&(g="border-sky-400/20 bg-sky-500/[0.05]"),{id:i.id,position:{x:72+c*308,y:56+y*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)] ${g}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(m,{className:"bg-white/[0.08] text-white/74",children:i.entityType}),u?e.jsx(m,{className:"bg-emerald-500/12 text-emerald-200",children:"Active"}):null,n?e.jsx(m,{className:"bg-rose-500/12 text-rose-200",children:"Blocked"}):null,p?e.jsx(m,{className:"bg-amber-500/12 text-amber-200",children:"Out of order"}):null,f&&!n&&!p?e.jsx(m,{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:i.title}),i.branchLabel?e.jsx("div",{className:"mt-2 text-xs uppercase tracking-[0.16em] text-white/45",children:i.branchLabel}):null,i.notes?e.jsx("div",{className:"mt-2 text-sm leading-5 text-white/56",children:i.notes}):null,t?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:t.color}}),e.jsx("span",{children:t.label})]}):null]})},style:{background:"transparent",border:"none",padding:0}}})}function we(a){return a.graph.edges.map(r=>{const l=a.metrics.activeNodeIds.includes(r.to),o=a.metrics.blockedNodeIds.includes(r.to),i=a.metrics.outOfOrderNodeIds.includes(r.to);let c="rgba(255,255,255,0.3)";return l?c="#4ade80":o?c="#fb7185":i&&(c="#f59e0b"),{id:`${r.from}->${r.to}`,source:r.from,target:r.to,label:r.label||void 0,animated:l,markerEnd:{type:ce.ArrowClosed,color:c},style:{stroke:c,strokeWidth:l?2.4:1.5},labelStyle:{fill:"rgba(255,255,255,0.56)",fontSize:11,fontWeight:600}}})}function ve({strategy:a,ownerByNodeId:r,heightClassName:l="h-[540px]"}){const o=h.useMemo(()=>ye(a,r),[r,a]),i=h.useMemo(()=>we(a),[a]);return e.jsx("div",{className:`${l} 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(le,{fitView:!0,nodes:o,edges:i,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!1,attributionPosition:"bottom-left",children:[e.jsx(de,{showInteractive:!1}),e.jsx(oe,{gap:28,size:1,color:"rgba(255,255,255,0.06)"})]})})}function Ne(a,r){const l=a.metrics.activeNodeIds.includes(r),o=a.metrics.blockedNodeIds.includes(r),i=a.metrics.outOfOrderNodeIds.includes(r);return o?{label:"Blocked",className:"bg-rose-500/12 text-rose-200"}:i?{label:"Out of order",className:"bg-amber-500/12 text-amber-200"}:l?{label:"Ready now",className:"bg-emerald-500/12 text-emerald-200"}:{label:"In plan",className:"bg-sky-500/12 text-sky-200"}}function ke({strategy:a,projectsById:r,tasksById:l,className:o}){const i=h.useMemo(()=>je(a.graph),[a.graph]),c=h.useMemo(()=>{const n=new Map;for(const p of a.graph.nodes)n.set(p.id,[]);for(const p of a.graph.edges)n.set(p.to,[...n.get(p.to)??[],p.from]);return n},[a.graph]),[y,u]=h.useState([]);return e.jsxs("div",{className:o??"grid gap-3",children:[i.map(n=>{const p=y.includes(n.level),f=n.level===0?"Launch phase":`Phase ${n.level+1}`,t=n.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:()=>u(g=>p?g.filter(d=>d!==n.level):[...g,n.level]),children:[e.jsx("span",{className:"rounded-full bg-white/[0.06] p-2 text-white/72",children:p?e.jsx(W,{className:"size-4"}):e.jsx(K,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/42",children:f}),e.jsx("div",{className:"mt-1 text-sm text-white/60",children:t?"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(m,{className:"bg-white/[0.08] text-white/76",children:[n.nodeIds.length," node",n.nodeIds.length===1?"":"s"]}),e.jsx(m,{className:"bg-white/[0.08] text-white/76",children:t?e.jsxs(e.Fragment,{children:[e.jsx(V,{className:"mr-1 size-3.5"}),"Parallel"]}):e.jsxs(e.Fragment,{children:[e.jsx(J,{className:"mr-1 size-3.5"}),"Sequential"]})})]})]}),p?null:e.jsx("div",{className:"grid gap-3 border-t border-white/8 px-4 py-4 lg:grid-cols-2",children:n.nodeIds.map(g=>{var O,N,P;const d=a.graph.nodes.find(b=>b.id===g);if(!d)return null;const v=d.entityType==="project"?r.get(d.entityId):l.get(d.entityId),T=d.entityType==="project"?`/projects/${d.entityId}`:`/tasks/${d.entityId}`,I=d.entityType==="project"?(O=r.get(d.entityId))==null?void 0:O.user:(N=l.get(d.entityId))==null?void 0:N.user,j=((P=c.get(d.id))==null?void 0:P.map(b=>{var $;return(($=a.graph.nodes.find(B=>B.id===b))==null?void 0:$.title)??b}))??[],w=Ne(a,d.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(m,{className:"bg-white/[0.08] text-white/76",children:d.entityType}),e.jsx(m,{className:w.className,children:w.label})]}),e.jsx(A,{to:T,className:"mt-3 block text-lg font-medium text-white transition hover:text-[var(--primary)]",children:d.title}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/54",children:d.notes||("description"in(v??{})?v==null?void 0:v.description:"")||"No extra step note attached yet."})]}),e.jsx(M,{user:I,compact:!0})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[d.branchLabel?e.jsx(m,{className:"bg-[rgba(192,193,255,0.12)] text-white/82",children:d.branchLabel}):null,j.length===0?e.jsx(m,{className:"bg-emerald-500/10 text-emerald-200",children:"Start node"}):j.map(b=>e.jsxs(m,{className:"bg-white/[0.08] text-white/70",children:["Depends on ",b]},`${d.id}:${b}`))]})]},d.id)})})]},n.level)}),i.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 Ee(){var B;const a=xe(),{strategyId:r}=X(),l=Y(),o=Z(),[i,c]=h.useState(!1),[y,u]=h.useState(),n=pe(a.selectedUserIds),p=a.snapshot.strategies.find(s=>s.id===r)??null,f=ee({queryKey:["strategy-detail",r],queryFn:async()=>(await be(r)).strategy,enabled:!!(r&&!p)}),t=p??f.data??null,g=async()=>{await Promise.all([o.invalidateQueries({queryKey:["strategy-detail",r]}),a.refresh()])},d=D({mutationFn:async({input:s,currentStrategyId:x})=>(await z(x,s)).strategy,onSuccess:g}),v=D({mutationFn:async s=>me(s),onSuccess:async()=>{await g(),l("/strategies")}}),T=D({mutationFn:async s=>(await z(r,{isLocked:s,lockedByUserId:s?n??(t==null?void 0:t.userId)??"user_operator":null})).strategy,onSuccess:g}),I=h.useMemo(()=>new Map(a.snapshot.goals.map(s=>[s.id,s])),[a.snapshot.goals]),j=h.useMemo(()=>new Map(a.snapshot.dashboard.projects.map(s=>[s.id,s])),[a.snapshot.dashboard.projects]),w=h.useMemo(()=>new Map(a.snapshot.tasks.map(s=>[s.id,s])),[a.snapshot.tasks]),O=h.useMemo(()=>t?new Map(t.graph.nodes.map(s=>{var S,C;const x=s.entityType==="project"?(S=j.get(s.entityId))==null?void 0:S.user:(C=w.get(s.entityId))==null?void 0:C.user;return[s.id,x?{label:`${x.displayName} (${x.kind})`,color:x.accentColor}:null]})):new Map,[j,t,w]),N=t??{title:"",overview:"",endStateDescription:"",targetGoalIds:[],targetProjectIds:[],graph:{nodes:[],edges:[]}},P=h.useMemo(()=>ae(N),[N]),b=h.useMemo(()=>ie(N),[N]),$=h.useMemo(()=>re((t==null?void 0:t.metrics)??{planCoverageScore:0,sequencingScore:0,scopeDisciplineScore:0,qualityScore:0,targetProgressScore:0,startedNodeCount:0,totalNodeCount:1,offPlanEntityCount:0,offPlanActiveEntityCount:0,blockedNodeIds:[],outOfOrderNodeIds:[]}),[t==null?void 0:t.metrics]);return f.isLoading&&!t?e.jsx(ge,{eyebrow:"Strategy",title:"Loading strategy",description:"Resolving the directed plan, targets, and current alignment."}):f.isError?e.jsx(G,{eyebrow:"Strategy",error:f.error,onRetry:()=>void f.refetch()}):t?e.jsxs("div",{className:"grid gap-5",children:[e.jsx(fe,{title:t.title,titleText:t.title,description:t.overview||t.endStateDescription,badge:`${t.metrics.alignmentScore}% aligned`,actions:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(se,{userId:n,domain:"strategies",entityType:"strategy",entityId:t.id,label:t.title,description:t.overview||t.endStateDescription}),e.jsx(te,{entityType:"strategy",entityId:t.id}),t.isLocked?null:e.jsx(L,{variant:"secondary",onClick:()=>{u(void 0),c(!0)},children:"Edit strategy"}),e.jsx(L,{variant:"secondary",disabled:!t.isLocked&&!b,pending:T.isPending,pendingLabel:t.isLocked?"Unlocking contract":"Locking contract",onClick:()=>{T.mutateAsync(!t.isLocked)},children:t.isLocked?"Unlock contract":"Lock as contract"}),e.jsx(L,{variant:"secondary",pending:v.isPending,pendingLabel:"Deleting strategy",onClick:()=>{window.confirm(`Delete strategy "${t.title}"?`)&&v.mutateAsync(t.id)},children:"Delete"})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(M,{user:t.user}),e.jsx(m,{className:t.isLocked?"bg-amber-500/12 text-amber-200":"bg-emerald-500/12 text-emerald-200",children:t.isLocked?"Contract locked":"Editable draft"}),e.jsx(m,{className:"bg-white/[0.08] text-white/76",children:t.status}),e.jsxs(m,{className:"bg-white/[0.08] text-white/76",children:[t.graph.nodes.length," nodes"]}),e.jsxs(m,{className:"bg-white/[0.08] text-white/76",children:[t.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(k,{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:t.endStateDescription||"No end-state description yet."})]}),e.jsxs(k,{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."})]}),t.isLocked?null:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(L,{variant:"secondary",onClick:()=>{u("sequence"),c(!0)},children:"Refine sequence"}),e.jsx(L,{onClick:()=>{u("sequence"),c(!0)},children:"Add parallel work"})]})]}),e.jsx(ve,{strategy:t,ownerByNodeId:O}),e.jsx(ke,{strategy:t,projectsById:j,tasksById:w})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(k,{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:t.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."}),t.isLocked?e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-sm text-white/60",children:[e.jsxs("span",{children:["Locked by"," ",((B=t.lockedByUser)==null?void 0:B.displayName)??"Unknown user"]}),t.lockedAt?e.jsxs("span",{children:["· ",new Date(t.lockedAt).toLocaleString()]}):null]}):null,t.isLocked?null:e.jsx("div",{className:"mt-4 grid gap-2",children:P.map(s=>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:s.label}),e.jsx(m,{className:s.satisfied?"bg-emerald-500/12 text-emerald-200":"bg-amber-500/12 text-amber-200",children:s.satisfied?"Ready":"Missing"})]},s.id))})]}),!t.isLocked&&!b?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,t.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(k,{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:[t.metrics.alignmentScore,"%"]}),e.jsxs("div",{className:"mt-3 text-xs leading-5 text-white/48",children:[t.metrics.startedNodeCount,"/",t.metrics.totalNodeCount," planned nodes started,"," ",t.metrics.completedNodeCount," completed,"," ",t.metrics.readyNodeCount," ready now."]})]}),$.map(s=>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:s.label}),e.jsxs("div",{className:"text-sm font-medium text-white",children:[s.value,"%"]})]}),e.jsx(he,{value:s.value,className:"mt-3"}),e.jsx("div",{className:"mt-3 text-xs leading-5 text-white/48",children:s.detail})]},s.id))]}),e.jsxs(k,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"End targets"}),t.targetGoalIds.map(s=>{const x=I.get(s);return x?e.jsx(A,{to:`/goals/${x.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: ",x.title]}),e.jsx(M,{user:x.user,compact:!0})]})},x.id):null}),t.targetProjectIds.map(s=>{const x=j.get(s);return x?e.jsx(A,{to:`/projects/${x.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: ",x.title]}),e.jsx(M,{user:x.user,compact:!0})]})},x.id):null}),t.targetGoalIds.length===0&&t.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(k,{className:"grid gap-3",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:"Linked entities"}),t.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."}):t.linkedEntities.map(s=>{var C,E,q,_,F,R,U;const x=ue(s.entityType,s.entityId),S=s.entityType==="goal"?(C=I.get(s.entityId))==null?void 0:C.title:s.entityType==="project"?(E=j.get(s.entityId))==null?void 0:E.title:s.entityType==="task"?(q=w.get(s.entityId))==null?void 0:q.title:`${s.entityType}:${s.entityId}`;return x?e.jsx(A,{to:x,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:S}),e.jsx(M,{user:s.entityType==="goal"?(_=I.get(s.entityId))==null?void 0:_.user:s.entityType==="project"?(F=j.get(s.entityId))==null?void 0:F.user:s.entityType==="task"?(R=w.get(s.entityId))==null?void 0:R.user:s.entityType==="strategy"?(U=a.snapshot.strategies.find(H=>H.id===s.entityId))==null?void 0:U.user:null,compact:!0})]})},`${s.entityType}:${s.entityId}`):e.jsx("div",{className:"rounded-[16px] bg-white/[0.04] px-4 py-3 text-sm text-white/52",children:S},`${s.entityType}:${s.entityId}`)})]})]})]}),e.jsx(ne,{open:i,pending:d.isPending,editingStrategy:t,goals:a.snapshot.dashboard.goals,projects:a.snapshot.dashboard.projects,tasks:a.snapshot.tasks,habits:a.snapshot.habits,strategies:a.snapshot.strategies,users:a.snapshot.users,defaultUserId:n,initialStepId:y,onOpenChange:s=>{c(s),s||u(void 0)},onSubmit:async s=>{await d.mutateAsync({input:s,currentStrategyId:t.id})}})]}):e.jsx(G,{eyebrow:"Strategy",error:new Error("Strategy not found."),onRetry:()=>l("/strategies")})}export{Ee as StrategyDetailPage};