forge-openclaw-plugin 0.2.102 → 0.2.103

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 (174) hide show
  1. package/dist/assets/activity-page-Dv6X5ZCV.js +1 -0
  2. package/dist/assets/{ai-surface-workspace-xtB5RFQu.js → ai-surface-workspace-CutiG6uS.js} +1 -1
  3. package/dist/assets/{atlas-panel-B3dPHCmZ.js → atlas-panel-jgMRyaHn.js} +1 -1
  4. package/dist/assets/{board-DqHzdCPQ.js → board-dIX6etHh.js} +1 -1
  5. package/dist/assets/calendar-page-q7Nm5E2U.js +1 -0
  6. package/dist/assets/calendar-rules-DPFsfiRl.js +1 -0
  7. package/dist/assets/{calendar-week-toolbar-BZ_-X3Wb.js → calendar-week-toolbar-nVhgB-0s.js} +1 -1
  8. package/dist/assets/{charts-FcU0F3XV.js → charts-DFnEuIMB.js} +1 -1
  9. package/dist/assets/companion-sync-lab-page-CJ8UTij8.js +1 -0
  10. package/dist/assets/{daily-metrics-dashboard-BMyL0Qr4.js → daily-metrics-dashboard-CiJkkkd1.js} +1 -1
  11. package/dist/assets/entity-note-count-link-RzBB6ujx.js +1 -0
  12. package/dist/assets/{entity-notes-surface-CBylYDwy.js → entity-notes-surface-Djz50HvD.js} +1 -1
  13. package/dist/assets/execution-board-CtPhI-58.js +1 -0
  14. package/dist/assets/{faceted-token-search-D7xPWfOl.js → faceted-token-search-DEC6ANa9.js} +1 -1
  15. package/dist/assets/{flagship-signal-deck-BEFKOhvx.js → flagship-signal-deck-CtHC3mql.js} +1 -1
  16. package/dist/assets/floating-action-menu-CKQRhff9.js +1 -0
  17. package/dist/assets/{forms-CmLAyGqz.js → forms-hB0SqEh-.js} +1 -1
  18. package/dist/assets/goal-detail-page-CF5fNQeR.js +1 -0
  19. package/dist/assets/goals-page-fsY8NzGB.js +1 -0
  20. package/dist/assets/{graph-BTa79qum.js → graph-DDUZNRsO.js} +1 -1
  21. package/dist/assets/habits-page-COoGz4kj.js +1 -0
  22. package/dist/assets/index-BAXYM89v.css +1 -0
  23. package/dist/assets/index-EqQsXoat.js +19 -0
  24. package/dist/assets/{insight-flow-dialog-BtIQXXsS.js → insight-flow-dialog-DtX_5W7g.js} +1 -1
  25. package/dist/assets/insights-page-cBd74ObU.js +8 -0
  26. package/dist/assets/kanban-page-CYav9THw.js +1 -0
  27. package/dist/assets/knowledge-graph-page-D2A-W1jE.js +1 -0
  28. package/dist/assets/{life-force-page-BGDkKfbJ.js → life-force-page-CACGlNhq.js} +1 -1
  29. package/dist/assets/life-force-workspace-BJ4N1I78.js +1 -0
  30. package/dist/assets/{maps-CF1RagUX.js → maps-C-yOWiDN.js} +1 -1
  31. package/dist/assets/{metric-tile-4iMd_WnJ.js → metric-tile-CMadwnGz.js} +1 -1
  32. package/dist/assets/{motion-CfdU2F35.js → motion-Lt5B1XuE.js} +1 -1
  33. package/dist/assets/movement-page-D5VqFd2q.js +1 -0
  34. package/dist/assets/{note-markdown-CsGQhQXF.js → note-markdown-BzK2Qlgr.js} +1 -1
  35. package/dist/assets/{note-tags-input-DdZi93tj.js → note-tags-input-CZzqJMLc.js} +1 -1
  36. package/dist/assets/notes-page-D3Hsh90C.js +1 -0
  37. package/dist/assets/{open-in-graph-button-C0TGev7c.js → open-in-graph-button-BFPKfyK3.js} +1 -1
  38. package/dist/assets/{orbit-map-DVXkfQdd.js → orbit-map-CnyfSmOG.js} +1 -1
  39. package/dist/assets/{overview-page-BwMlFQKX.js → overview-page-CXdWrOV1.js} +1 -1
  40. package/dist/assets/{page-hero-oFHaAjtL.js → page-hero-ffKzgyW3.js} +1 -1
  41. package/dist/assets/pill-cluster-C2D0h3lx.js +1 -0
  42. package/dist/assets/{preference-entity-handoff-button-DOKV9bZc.js → preference-entity-handoff-button-Dj3V6VxL.js} +1 -1
  43. package/dist/assets/preferences-page-Jo8Gw386.js +1 -0
  44. package/dist/assets/project-collections-qSqp90HN.js +1 -0
  45. package/dist/assets/{project-detail-page-DogvVNEn.js → project-detail-page-BifhiLQX.js} +1 -1
  46. package/dist/assets/project-management-hierarchy-page-DZ_9klIc.js +1 -0
  47. package/dist/assets/project-management-section-nav-BImLCVvf.js +1 -0
  48. package/dist/assets/projects-page-ptcx6H38.js +1 -0
  49. package/dist/assets/{psyche-behaviors-page-BeVlXvbj.js → psyche-behaviors-page-BDwXyDta.js} +1 -1
  50. package/dist/assets/{psyche-flashcards-page-CqAWCO4E.js → psyche-flashcards-page-DL1BP1jX.js} +1 -1
  51. package/dist/assets/{psyche-goal-map-page-IyNnbk_W.js → psyche-goal-map-page-ovcpisx1.js} +1 -1
  52. package/dist/assets/{psyche-graph-IkUQRaDK.js → psyche-graph-EP5GL612.js} +1 -1
  53. package/dist/assets/{psyche-metrics-page-uai0a7Lx.js → psyche-metrics-page-Bcu813Rg.js} +1 -1
  54. package/dist/assets/{psyche-mode-guide-page-C7p-ABiF.js → psyche-mode-guide-page-C0g27Xpt.js} +1 -1
  55. package/dist/assets/{psyche-modes-page-CLQ5V3w0.js → psyche-modes-page-BjKjX5MR.js} +1 -1
  56. package/dist/assets/{psyche-page-NQBHkkpU.js → psyche-page-F4tF2W70.js} +1 -1
  57. package/dist/assets/{psyche-patterns-page-BkRiNpI_.js → psyche-patterns-page-B-14hukK.js} +1 -1
  58. package/dist/assets/{psyche-questionnaire-builder-page-Du-7HwPC.js → psyche-questionnaire-builder-page-BdXmoHvK.js} +1 -1
  59. package/dist/assets/{psyche-questionnaire-detail-page-C5-yf8MF.js → psyche-questionnaire-detail-page-Cu5uwlJu.js} +1 -1
  60. package/dist/assets/{psyche-questionnaire-run-detail-page-CoSH5O6R.js → psyche-questionnaire-run-detail-page-C3R4PClg.js} +1 -1
  61. package/dist/assets/{psyche-questionnaire-run-page-ChI7c1wy.js → psyche-questionnaire-run-page-Div3iDdt.js} +1 -1
  62. package/dist/assets/{psyche-questionnaires-page-xUcJJzbI.js → psyche-questionnaires-page-DpqAPQCp.js} +1 -1
  63. package/dist/assets/{psyche-report-detail-page-BPrZCFZS.js → psyche-report-detail-page-BvWVDKP3.js} +1 -1
  64. package/dist/assets/{psyche-reports-page-D2EXJmm6.js → psyche-reports-page-BrbWUlAq.js} +1 -1
  65. package/dist/assets/{psyche-schemas-RcZYaokx.js → psyche-schemas-Dxj554nU.js} +1 -1
  66. package/dist/assets/{psyche-schemas-beliefs-page-h0ooZ1lp.js → psyche-schemas-beliefs-page-DYKvAtSD.js} +1 -1
  67. package/dist/assets/{psyche-screen-time-page-_3-4LikV.js → psyche-screen-time-page-CAOKCyQw.js} +1 -1
  68. package/dist/assets/{psyche-self-observation-page-BdbCsgR5.js → psyche-self-observation-page-F0MVA0UH.js} +1 -1
  69. package/dist/assets/{psyche-values-page-DuUVki5e.js → psyche-values-page-DyvX-d0o.js} +1 -1
  70. package/dist/assets/{report-chain-fields-BBMz0sGI.js → report-chain-fields-CeC1cJFS.js} +1 -1
  71. package/dist/assets/rewards-page-C2loyODo.js +1 -0
  72. package/dist/assets/scheduling-rules-editor-D40AC2jR.js +1 -0
  73. package/dist/assets/{schema-badge-D93RcG36.js → schema-badge-FY7818qB.js} +1 -1
  74. package/dist/assets/{select-menu-Cdq7foRu.js → select-menu-DJsCG6rM.js} +1 -1
  75. package/dist/assets/settings-agents-page-BFkJ5AAD.js +6 -0
  76. package/dist/assets/settings-bin-page-D3-Ab-iA.js +1 -0
  77. package/dist/assets/settings-calendar-page-ly_mSTAD.js +5 -0
  78. package/dist/assets/settings-data-page-D7QOqNf-.js +1 -0
  79. package/dist/assets/settings-logs-page-Ca87HEUx.js +1 -0
  80. package/dist/assets/settings-mobile-page-D0jejZot.js +1 -0
  81. package/dist/assets/settings-models-page-DPDsZjSc.js +1 -0
  82. package/dist/assets/settings-page-1cArlSPM.js +1 -0
  83. package/dist/assets/settings-rewards-page-Db4BV1DC.js +1 -0
  84. package/dist/assets/{settings-section-nav-Dc4IeVBt.js → settings-section-nav-DP9o4peU.js} +1 -1
  85. package/dist/assets/settings-users-page-BHFyDSsd.js +1 -0
  86. package/dist/assets/settings-wiki-page-BNaiupBm.js +1 -0
  87. package/dist/assets/sleep-page-BmOPF0yD.js +1 -0
  88. package/dist/assets/sports-page-BldIiclr.js +1 -0
  89. package/dist/assets/{state-VYvD1QVP.js → state-vCcAT5Hq.js} +1 -1
  90. package/dist/assets/strategies-page-CaTN99qj.js +1 -0
  91. package/dist/assets/strategy-detail-page-DsgFTd-U.js +1 -0
  92. package/dist/assets/{strategy-dialog-DMyRKrWf.js → strategy-dialog-7X7peRzu.js} +1 -1
  93. package/dist/assets/{surface-Bfz_sLX6.js → surface-CJI17F3n.js} +1 -1
  94. package/dist/assets/{table-C0VTeqw0.js → table-BNqMG3_S.js} +1 -1
  95. package/dist/assets/task-detail-page-M1sIIPA8.js +1 -0
  96. package/dist/assets/timebox-planning-dialog-ByojN0AN.js +1 -0
  97. package/dist/assets/today-page-BjDijtn8.js +1 -0
  98. package/dist/assets/training-load-page-BPRmaWmF.js +1 -0
  99. package/dist/assets/{ui-CsEkP2V8.js → ui-C1iwpj2-.js} +1 -1
  100. package/dist/assets/{use-psyche-focus-target-qxT5Oy_z.js → use-psyche-focus-target-Ct-acS9G.js} +1 -1
  101. package/dist/assets/{vendor-kIz9EZnX.js → vendor-Dnkkx2co.js} +3 -3
  102. package/dist/assets/{vitals-page-Dz1Jt5H8.js → vitals-page-CE9zdGLF.js} +1 -1
  103. package/dist/assets/weekly-review-page-CzhTv90n.js +1 -0
  104. package/dist/assets/weight-loss-page-Bp_cIk78.js +5 -0
  105. package/dist/assets/wiki-article-markdown-Dok2uy2p.js +4 -0
  106. package/dist/assets/wiki-editor-page-BuW32Y3f.js +26 -0
  107. package/dist/assets/wiki-ingest-history-page-DZKSBNHV.js +1 -0
  108. package/dist/assets/wiki-ingest-modal-DyqBEZcC.js +1 -0
  109. package/dist/assets/wiki-page-DqxlbLKG.js +1 -0
  110. package/dist/assets/workbench-flow-page-C4nc9jUg.js +5 -0
  111. package/dist/assets/workbench-page-BnyR7SL0.js +1 -0
  112. package/dist/assets/{workout-detail-page-DD9IGN6l.js → workout-detail-page-DT-c5cHL.js} +2 -2
  113. package/dist/index.html +9 -9
  114. package/dist/server/server/src/app.js +22 -3
  115. package/dist/server/server/src/health-weight-loss.js +114 -39
  116. package/dist/server/server/src/repositories/model-settings.js +9 -3
  117. package/dist/server/src/components/workbench-boxes/shared/generic-node-view.js +13 -5
  118. package/dist/server/src/lib/api.js +10 -1
  119. package/openclaw.plugin.json +1 -1
  120. package/package.json +1 -1
  121. package/dist/assets/activity-page-CgF7K2ww.js +0 -1
  122. package/dist/assets/calendar-page-C1Wfd2Fy.js +0 -1
  123. package/dist/assets/calendar-rules-CaZXtlxt.js +0 -1
  124. package/dist/assets/companion-sync-lab-page-NgeK-O-P.js +0 -1
  125. package/dist/assets/entity-note-count-link-BrS1-O0o.js +0 -1
  126. package/dist/assets/execution-board-CpO2ch6v.js +0 -1
  127. package/dist/assets/floating-action-menu-zzC2r0Ob.js +0 -1
  128. package/dist/assets/goal-detail-page-JK_Nva8e.js +0 -1
  129. package/dist/assets/goals-page-yeoJ06Vw.js +0 -1
  130. package/dist/assets/habits-page-Dx5EhkJi.js +0 -1
  131. package/dist/assets/index-BHIKoiZ6.js +0 -19
  132. package/dist/assets/index-H8R-ABM3.css +0 -1
  133. package/dist/assets/insights-page-CujrosD_.js +0 -8
  134. package/dist/assets/kanban-page-Q9NuIz5w.js +0 -1
  135. package/dist/assets/knowledge-graph-page-DaJmlvvM.js +0 -1
  136. package/dist/assets/life-force-workspace-CLVexVnb.js +0 -1
  137. package/dist/assets/movement-page-ClaoTNuX.js +0 -1
  138. package/dist/assets/notes-page-DYI8s3NN.js +0 -1
  139. package/dist/assets/pill-cluster-7UZd_lHp.js +0 -1
  140. package/dist/assets/preferences-page-BrKEkmfD.js +0 -1
  141. package/dist/assets/project-collections-CZagCmeH.js +0 -1
  142. package/dist/assets/project-management-hierarchy-page-Dr7hW9PW.js +0 -1
  143. package/dist/assets/project-management-section-nav-BLdAgTge.js +0 -1
  144. package/dist/assets/projects-page-UKrby_5-.js +0 -1
  145. package/dist/assets/rewards-page-PZFPa6rR.js +0 -1
  146. package/dist/assets/scheduling-rules-editor-B9KNKsQz.js +0 -1
  147. package/dist/assets/settings-agents-page-DPx2F6wf.js +0 -6
  148. package/dist/assets/settings-bin-page-COwP3gjo.js +0 -1
  149. package/dist/assets/settings-calendar-page-C-ghE0YT.js +0 -5
  150. package/dist/assets/settings-data-page-CBubzKBw.js +0 -1
  151. package/dist/assets/settings-logs-page-uOuXMeBm.js +0 -1
  152. package/dist/assets/settings-mobile-page-C5rfj8_r.js +0 -1
  153. package/dist/assets/settings-models-page-DijmUWdU.js +0 -1
  154. package/dist/assets/settings-page-B4u5TR5g.js +0 -1
  155. package/dist/assets/settings-rewards-page-COiTwkMH.js +0 -1
  156. package/dist/assets/settings-users-page-DEGa5DNn.js +0 -1
  157. package/dist/assets/settings-wiki-page-Cvsiz5_e.js +0 -1
  158. package/dist/assets/sleep-page-BnSOwkEU.js +0 -1
  159. package/dist/assets/sports-page-l1RqXzA_.js +0 -1
  160. package/dist/assets/strategies-page-DEnPlpAs.js +0 -1
  161. package/dist/assets/strategy-detail-page-Ls8bxKeH.js +0 -1
  162. package/dist/assets/task-detail-page-CgrYgQLD.js +0 -1
  163. package/dist/assets/timebox-planning-dialog-Ww0NGLLo.js +0 -1
  164. package/dist/assets/today-page-CIuFHMi1.js +0 -1
  165. package/dist/assets/training-load-page-BIwc648i.js +0 -1
  166. package/dist/assets/weekly-review-page-BFpBe1kI.js +0 -1
  167. package/dist/assets/weight-loss-page-BgMoBpBt.js +0 -5
  168. package/dist/assets/wiki-article-markdown-gsPTXTg1.js +0 -4
  169. package/dist/assets/wiki-editor-page-BpAZHooY.js +0 -26
  170. package/dist/assets/wiki-ingest-history-page-C-ig8O22.js +0 -1
  171. package/dist/assets/wiki-ingest-modal-BK4eQgqs.js +0 -1
  172. package/dist/assets/wiki-page-CMTZ60Zt.js +0 -1
  173. package/dist/assets/workbench-flow-page-BIpWUcLJ.js +0 -5
  174. package/dist/assets/workbench-page-CtCjYSRe.js +0 -1
@@ -1 +0,0 @@
1
- import{r as y,j as e,aG as Ae}from"./vendor-kIz9EZnX.js";import{S as Pe}from"./scheduling-rules-editor-B9KNKsQz.js";import{aT as De,C as ge,B as U,K as ee,k as Q,F as w,c as m,h as Y,I as D,j as Ce,d as te,Q as Ie,cJ as Re,N as Ee}from"./index-BHIKoiZ6.js";import{i as fe}from"./state-VYvD1QVP.js";import{f as Me}from"./calendar-ui-Cy1XRwzV.js";function qe({open:s,onOpenChange:o,tasks:h,onSave:x}){const c=y.useMemo(()=>h.filter(p=>p.status!=="done"),[h]),[C,b]=y.useState("");y.useEffect(()=>{if(s){if(c.length===0){b("");return}b(p=>p&&c.some(g=>g.id===p)?p:c[0].id)}},[c,s]);const N=c.find(p=>p.id===C)??null;return e.jsx(De,{open:s,onOpenChange:o,eyebrow:"Calendar",title:"Adjust task scheduling rules",description:"Choose a task, then tell Forge which work blocks, calendar conditions, or keywords should allow or block that work.",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsx(ge,{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(18,28,38,0.98),rgba(11,17,28,0.98))]",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"rounded-[18px] bg-[var(--primary)]/14 p-3 text-[var(--primary)]",children:e.jsx(Ae,{className:"size-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:"Guided rule editing"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:"Use this when a task should only run in certain blocks such as Secondary Activity, or should stay blocked during clinic, rest, or other provider events."})]})]})}),c.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-white/58",children:"Task"}),e.jsx("select",{value:C,onChange:p=>b(p.target.value),className:"rounded-[22px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none",children:c.map(p=>e.jsx("option",{value:p.id,children:p.title},p.id))})]}),N?e.jsx(Pe,{title:"Task rules",subtitle:"These rules are saved directly on the task. They drive blocked-now checks and future timebox recommendations.",initialRules:N.schedulingRules,initialPlannedDurationSeconds:N.plannedDurationSeconds,allowPlannedDuration:!0,saveLabel:"Save task rules",onSave:async({schedulingRules:p,plannedDurationSeconds:g})=>{await x({taskId:N.id,schedulingRules:p,plannedDurationSeconds:g===void 0?N.plannedDurationSeconds:g??null}),o(!1)}}):null]}):e.jsxs(ge,{className:"rounded-[28px] border border-white/8 bg-white/[0.04]",children:[e.jsx("div",{className:"font-medium text-white",children:"No schedulable tasks yet"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-white/60",children:"Create or reopen a task first, then come back here to define work-block and calendar eligibility."}),e.jsx("div",{className:"mt-4",children:e.jsx(U,{variant:"secondary",onClick:()=>o(!1),children:"Close"})})]})]})})}function E(s){return s.slice(0,10)}function Fe(s){return new Date(`${s}T00:00:00`).toISOString()}function Ke(s){return new Date(`${s}T23:59:59.999`).toISOString()}function ae(s,o,h){return s<o?o:s>h?h:s}function we(s,o){const h=E(s),x=E(o),c=new Date(`${h}T12:00:00`);return c.setDate(c.getDate()+1),ae(E(c.toISOString()),h,x)}function ye(s){return String(s).padStart(2,"0")}function q(s){return`${ye(s.getHours())}:${ye(s.getMinutes())}`}function ve(s,o){if(!s||!o)return null;const h=new Date(`${s}T${o}:00`);return Number.isNaN(h.getTime())?null:h}function G(s,o,h){if(h){const b=new Date(h.startsAt),N=new Date(h.endsAt);return{startTime:q(b),endTime:q(N)}}const x=new Date(`${s}T09:00:00`),c=Math.max(1800,Math.min(o??3600,360*60)),C=new Date(x.getTime()+c*1e3);return{startTime:q(x),endTime:q(C)}}function je(s,o){return`${new Date(s).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})} - ${new Date(o).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`}function z(s,o){return`${Me(new Date(s))} · ${je(s,o)}`}function T({title:s,subtitle:o,emptyLabel:h,children:x}){const c=Array.isArray(x)?x:x?[x]:[];return e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:s}),e.jsx("div",{className:"mt-1 text-sm text-white/54",children:o})]}),e.jsx(m,{className:"bg-white/[0.08] text-white/74",children:c.length})]}),e.jsx("div",{className:"mt-3 grid gap-2",children:c.length>0?c:e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/8 bg-white/[0.03] px-3 py-3 text-sm text-white/46",children:h})})]})}function He({event:s}){return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:s.title}),e.jsx(m,{className:"bg-white/[0.08] text-white/70",children:s.availability})]}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:z(s.startAt,s.endAt)})]})}function Le({block:s}){return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:s.title}),e.jsx(m,{className:"bg-white/[0.08] text-white/70",children:s.blockingState})]}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:z(s.startAt,s.endAt)})]})}function $e({timebox:s}){const o=ee(s);return e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] px-3 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-white",children:s.title}),e.jsx(m,{className:"bg-white/[0.08] text-white/70",children:s.source})]}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:z(s.startsAt,s.endsAt)}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsx(m,{className:"bg-white/[0.08] text-white/72",children:te(o.rateApPerHour)}),e.jsx(m,{className:"bg-white/[0.08] text-white/72",children:Y(o.totalAp)})]})]})}function Ge({open:s,onOpenChange:o,tasks:h,from:x,to:c,onCreateTimebox:C,onUpdateTimebox:b,onDeleteTimebox:N,initialTaskId:p,lockedTaskId:g,editingTimebox:t,userIds:se}){var ce,ue,he,me,pe,xe;const M=!!t,v=y.useMemo(()=>{const a=g??(t==null?void 0:t.taskId)??null,d=h.filter(u=>u.status!=="done"||u.id===a);if(!a)return d;const r=d.find(u=>u.id===a);return r?[r]:[]},[t==null?void 0:t.taskId,g,h]),F=E(x),K=E(c),re=t?ae(E(t.startsAt),F,K):we(x,c),ne=g??(t==null?void 0:t.taskId)??p??((ce=v[0])==null?void 0:ce.id)??"",H=v.find(a=>a.id===ne)??v[0]??null,le=G(re,H==null?void 0:H.plannedDurationSeconds,t?{startsAt:t.startsAt,endsAt:t.endsAt}:null),[i,B]=y.useState({taskId:ne,preferredDate:re,plannerMode:t?"manual":"suggested",selectedTimeboxId:"",activityPresetKey:((ue=t==null?void 0:t.actionProfile)==null?void 0:ue.profileKey)??"task_inherited",customSustainRateApPerHour:((he=t==null?void 0:t.actionProfile)==null?void 0:he.sourceMethod)==="manual"?t.actionProfile.sustainRateApPerHour:null,manualStartTime:le.startTime,manualEndTime:le.endTime,manualTitle:(t==null?void 0:t.title)??(H==null?void 0:H.title)??"",overrideReason:(t==null?void 0:t.overrideReason)??""}),[be,j]=y.useState(null),[Ne,W]=y.useState(!1),[Se,ie]=y.useState(!1);y.useEffect(()=>{var R,$,_;if(!s)return;const a=g??p??((R=v[0])==null?void 0:R.id)??"",d=(t==null?void 0:t.taskId)??a,r=v.find(f=>f.id===d)??v[0]??null,u=t?ae(E(t.startsAt),F,K):we(x,c),n=G(u,r==null?void 0:r.plannedDurationSeconds,t?{startsAt:t.startsAt,endsAt:t.endsAt}:null);j(null),B({taskId:d,preferredDate:u,plannerMode:t?"manual":"suggested",selectedTimeboxId:"",activityPresetKey:(($=t==null?void 0:t.actionProfile)==null?void 0:$.profileKey)??"task_inherited",customSustainRateApPerHour:((_=t==null?void 0:t.actionProfile)==null?void 0:_.sourceMethod)==="manual"?t.actionProfile.sustainRateApPerHour:null,manualStartTime:n.startTime,manualEndTime:n.endTime,manualTitle:(t==null?void 0:t.title)??(r==null?void 0:r.title)??"",overrideReason:(t==null?void 0:t.overrideReason)??""})},[v,t,x,p,g,K,F,s,c]);const l=v.find(a=>a.id===i.taskId)??null,A=y.useMemo(()=>({from:Fe(i.preferredDate),to:Ke(i.preferredDate)}),[i.preferredDate]),P=fe({queryKey:["forge-calendar-suggestions-dialog",i.taskId,A.from,A.to],queryFn:()=>Re({taskId:i.taskId,from:A.from,to:A.to,limit:8}),enabled:s&&i.taskId.length>0}),J=fe({queryKey:["forge-calendar-timebox-dialog-day",A.from,A.to,...se??[]],queryFn:()=>Ee({from:A.from,to:A.to,userIds:se}),enabled:s});y.useEffect(()=>{var d;if(!s)return;const a=((d=P.data)==null?void 0:d.timeboxes)??[];if(!a.length){B(r=>r.selectedTimeboxId?{...r,selectedTimeboxId:""}:r);return}B(r=>r.selectedTimeboxId&&a.some(u=>u.id===r.selectedTimeboxId)?r:{...r,selectedTimeboxId:a[0].id})},[s,P.data]);const k=(me=J.data)==null?void 0:me.calendar,X=(k==null?void 0:k.events)??[],Z=(k==null?void 0:k.workBlockInstances)??[],V=(k==null?void 0:k.timeboxes)??[],L=(((pe=P.data)==null?void 0:pe.timeboxes)??[]).find(a=>a.id===i.selectedTimeboxId),S=ve(i.preferredDate,i.manualStartTime),I=ve(i.preferredDate,i.manualEndTime),O=S&&I?ee({startsAt:S.toISOString(),endsAt:I.toISOString(),actionProfile:i.customSustainRateApPerHour!==null||i.activityPresetKey!=="task_inherited"?{id:"manual-preview",profileKey:"manual-preview",title:i.manualTitle||(l==null?void 0:l.title)||"Manual timebox",entityType:"task_timebox",mode:"container",startupAp:0,totalCostAp:0,expectedDurationSeconds:null,sustainRateApPerHour:i.customSustainRateApPerHour??((xe=Q().find(a=>a.key===i.activityPresetKey))==null?void 0:xe.defaultRateApPerHour)??100/24,demandWeights:{activation:.1,focus:.3,vigor:.1,composure:.1,flow:.4},doubleCountPolicy:"container_only",sourceMethod:"manual",costBand:"light",recoveryEffect:0,metadata:{},createdAt:S.toISOString(),updatedAt:S.toISOString()}:null}):null,oe=M?"Review the task tied to this scheduled block":g?"Review the task you are planning":"Choose the task you want to place into the calendar",de=M?"The timebox stays linked to this task. Update the day, hours, title, or AP profile without leaving the planning flow.":g?"Forge will use this task's current duration target and scheduling rules while it looks for viable slots.":"Forge will use the task's current planned duration and scheduling rules when it searches for valid slots.",ke=y.useMemo(()=>[{id:"task",eyebrow:"Planning",title:oe,description:de,render:(a,d)=>e.jsxs("div",{className:"grid gap-4",children:[g?null:e.jsx(w,{label:"Task",children:e.jsx("select",{value:a.taskId,onChange:r=>(()=>{const u=v.find(R=>R.id===r.target.value),n=G(a.preferredDate,u==null?void 0:u.plannedDurationSeconds);d({taskId:r.target.value,selectedTimeboxId:"",activityPresetKey:"task_inherited",customSustainRateApPerHour:null,manualStartTime:n.startTime,manualEndTime:n.endTime,manualTitle:(u==null?void 0:u.title)??a.manualTitle})})(),className:"rounded-[22px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none",children:v.map(r=>e.jsx("option",{value:r.id,children:r.title},r.id))})}),l?e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(28,36,54,0.78),rgba(15,22,34,0.78))] p-5 shadow-[0_18px_40px_rgba(5,12,24,0.22)]",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/42",children:"Time Box"}),e.jsx("div",{className:"mt-2 font-display text-[1.4rem] leading-tight text-white",children:l.title})]}),e.jsx(m,{className:"bg-white/[0.08] text-white/74",children:l.status})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx(m,{className:"bg-white/[0.08] text-white/74",children:l.plannedDurationSeconds?`${Math.round(l.plannedDurationSeconds/60)} min target`:"No duration yet"}),e.jsx(m,{className:"bg-white/[0.08] text-white/74",children:l.schedulingRules?"Task-specific rules":"Uses project rules"}),e.jsxs(m,{className:"bg-white/[0.08] text-white/74",children:[l.points," xp"]}),l.plannedDurationSeconds?e.jsxs(m,{className:"bg-white/[0.08] text-white/74",children:[Y(l.plannedDurationSeconds/3600/24*100)," ","target load"]}):null]}),e.jsx("p",{className:"mt-4 text-sm leading-6 text-white/60",children:"Pick a day first, then either accept one of Forge's suggested slots or set the block manually."}),M&&t&&N?e.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-3 rounded-[20px] border border-rose-400/18 bg-rose-400/8 px-4 py-3",children:[e.jsx("div",{className:"text-sm leading-6 text-rose-100/84",children:"Remove this planned timebox if you no longer want it in the calendar."}),e.jsx(U,{type:"button",variant:"ghost",className:"text-rose-100 hover:bg-rose-500/12",pending:Se,pendingLabel:"Deleting",onClick:()=>void(async()=>{j(null),ie(!0);try{await N(t.id),o(!1)}catch(r){j(r instanceof Error?r.message:"Forge could not delete this timebox.")}finally{ie(!1)}})(),children:"Delete timebox"})]}):null]}):null]})},{id:"day",eyebrow:"Calendar",title:"Choose the day and review what is already there",description:"Forge reads the real day first so the timebox stays grounded in your provider events, work blocks, and already-planned work.",render:(a,d)=>e.jsx("div",{className:"grid gap-5",children:e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,16rem)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsx(w,{label:"Date",description:"Choose the day you want to protect for this task.",children:e.jsx(D,{type:"date",min:F,max:K,value:a.preferredDate,onChange:r=>{const u=G(r.target.value,l==null?void 0:l.plannedDurationSeconds,t?{startsAt:`${r.target.value}T${a.manualStartTime}:00`,endsAt:`${r.target.value}T${a.manualEndTime}:00`}:null);d({preferredDate:r.target.value,selectedTimeboxId:"",manualStartTime:u.startTime,manualEndTime:u.endTime})}})}),e.jsx(w,{label:"Planning style",description:"Take Forge's slot recommendation when it fits, or set the block yourself.",children:e.jsx(Ce,{value:a.plannerMode,onChange:r=>d({plannerMode:r}),options:[{value:"suggested",label:"Use suggestions",description:"Forge proposes slots that fit the task rules and the selected day."},{value:"manual",label:"Set it manually",description:"You choose the exact start and end time yourself."}]})})]}),e.jsxs("div",{className:"rounded-[28px] border border-white/8 bg-[linear-gradient(180deg,rgba(21,31,44,0.86),rgba(11,17,28,0.86))] p-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:"Selected day"}),e.jsx("div",{className:"mt-2 font-display text-[1.3rem] leading-tight text-white",children:a.preferredDate?new Date(`${a.preferredDate}T12:00:00`).toLocaleDateString([],{weekday:"long",month:"long",day:"numeric"}):"Choose a day"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(m,{className:"bg-white/[0.08] text-white/74",children:[X.length," events"]}),e.jsxs(m,{className:"bg-white/[0.08] text-white/74",children:[Z.length," work blocks"]}),e.jsxs(m,{className:"bg-white/[0.08] text-white/74",children:[V.length," timeboxes"]})]})]}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-white/58",children:"This is the context Forge will use while recommending a slot. You can still place the block manually if you want something more exact."}),J.isLoading?e.jsx("div",{className:"mt-4 rounded-[18px] border border-white/8 bg-white/[0.04] px-4 py-4 text-sm text-white/56",children:"Loading the selected day…"}):e.jsxs("div",{className:"mt-4 grid gap-4 xl:grid-cols-3",children:[e.jsx(T,{title:"Provider events",subtitle:"Busy or free events already on the day.",emptyLabel:"No mirrored events on this day.",children:X.slice(0,4).map(r=>e.jsx(He,{event:r},r.id))}),e.jsx(T,{title:"Work blocks",subtitle:"Recurring allowed or blocked containers.",emptyLabel:"No work blocks land on this day.",children:Z.slice(0,4).map(r=>e.jsx(Le,{block:r},r.id))}),e.jsx(T,{title:"Planned timeboxes",subtitle:"Existing owned work already placed there.",emptyLabel:"No other planned timeboxes yet.",children:V.slice(0,4).map(r=>e.jsx($e,{timebox:r},r.id))})]})]})]})})},{id:"slot",eyebrow:i.plannerMode==="suggested"?"Suggestion":"Manual",title:i.plannerMode==="suggested"?"Choose one of Forge's suggested slots":"Set the exact timebox yourself",description:i.plannerMode==="suggested"?"Forge proposes slots that fit the selected day, the task rules, and the current calendar picture.":"Use manual mode when the right block is obvious to you or when you want to place the timebox despite imperfect recommendations.",render:(a,d)=>{var u;if(a.plannerMode==="manual")return e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(w,{label:"Day",description:"Pick the day for the block. Forge defaults to a future day, but you can move it.",children:e.jsx(D,{type:"date",min:F,max:K,value:a.preferredDate,onChange:n=>d({preferredDate:n.target.value})})}),e.jsx(w,{label:"Start time",description:"Choose when the protected work block should begin.",children:e.jsx(D,{type:"time",step:300,value:a.manualStartTime,onChange:n=>d({manualStartTime:n.target.value})})}),e.jsx(w,{label:"End time",description:"Choose when the work block should end.",children:e.jsx(D,{type:"time",step:300,value:a.manualEndTime,onChange:n=>d({manualEndTime:n.target.value})})})]}),e.jsx(w,{label:"Title",description:"By default Forge uses the task title. Tighten it only if a shorter calendar label would help.",children:e.jsx(D,{value:a.manualTitle,onChange:n=>d({manualTitle:n.target.value}),placeholder:(l==null?void 0:l.title)??"Task timebox"})}),e.jsx(w,{label:"Override reason",description:"Optional. Add a short reason only if you are intentionally placing the block despite the normal rules or calendar shape.",children:e.jsx(D,{value:a.overrideReason,onChange:n=>d({overrideReason:n.target.value}),placeholder:"Protected writing block before clinic."})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(w,{label:"Activity profile",children:e.jsx("select",{value:a.activityPresetKey??"task_inherited",onChange:n=>d({activityPresetKey:n.target.value}),className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none",children:Q().map(n=>e.jsx("option",{value:n.key,children:n.label},n.key))})}),e.jsx(w,{label:"Custom AP per hour",children:e.jsx(D,{type:"number",min:0,step:.5,value:a.customSustainRateApPerHour??"",onChange:n=>d({customSustainRateApPerHour:n.target.value.trim()===""?null:Number(n.target.value)}),placeholder:"Leave empty to use the activity profile"})})]}),e.jsxs("div",{className:"rounded-[24px] border border-white/8 bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-white",children:a.manualTitle||(l==null?void 0:l.title)||"Manual timebox"}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:S&&I?`${S.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"})} · ${je(S.toISOString(),I.toISOString())}`:"Choose a start and end time."})]}),e.jsx(m,{className:"bg-white/[0.08] text-white/74",children:"manual"})]}),O?e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(m,{className:"bg-white/[0.08] text-white/72",children:te(O.rateApPerHour)}),e.jsx(m,{className:"bg-white/[0.08] text-white/72",children:Y(O.totalAp)})]}):null]})]});const r=((u=P.data)==null?void 0:u.timeboxes)??[];return P.isLoading?e.jsx("div",{className:"text-sm text-white/62",children:"Looking for valid slots on the selected day…"}):r.length?e.jsx("div",{className:"grid gap-3",children:r.map(n=>{var _;const R=a.selectedTimeboxId===n.id,$=ee({...n,actionProfile:a.customSustainRateApPerHour!==null||a.activityPresetKey!=="task_inherited"?{id:"suggested-preview",profileKey:"suggested-preview",title:n.title,entityType:"task_timebox",mode:"container",startupAp:0,totalCostAp:0,expectedDurationSeconds:null,sustainRateApPerHour:a.customSustainRateApPerHour??((_=Q().find(f=>f.key===a.activityPresetKey))==null?void 0:_.defaultRateApPerHour)??100/24,demandWeights:{activation:.1,focus:.3,vigor:.1,composure:.1,flow:.4},doubleCountPolicy:"container_only",sourceMethod:"manual",costBand:"light",recoveryEffect:0,metadata:{},createdAt:n.startsAt,updatedAt:n.startsAt}:null});return e.jsxs("button",{type:"button",onClick:()=>d({selectedTimeboxId:n.id}),className:`rounded-[24px] border px-4 py-4 text-left transition ${R?"border-[rgba(192,193,255,0.28)] bg-[rgba(192,193,255,0.14)] text-white shadow-[0_18px_36px_rgba(5,12,24,0.24)]":"border-white/8 bg-white/[0.04] text-white/72 hover:bg-white/[0.07]"}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium",children:n.title}),e.jsx(m,{className:"bg-white/[0.08] text-white/76",children:n.source})]}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:z(n.startsAt,n.endsAt)}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(m,{className:"bg-white/[0.08] text-white/74",children:te($.rateApPerHour)}),e.jsx(m,{className:"bg-white/[0.08] text-white/74",children:Y($.totalAp)})]}),R?e.jsxs("div",{className:"mt-4 grid gap-4 md:grid-cols-2",children:[e.jsx(w,{label:"Activity profile",children:e.jsx("select",{value:a.activityPresetKey??"task_inherited",onChange:f=>d({activityPresetKey:f.target.value}),className:"rounded-[18px] border border-white/8 bg-white/6 px-4 py-3 text-[15px] text-white outline-none",children:Q().map(f=>e.jsx("option",{value:f.key,children:f.label},f.key))})}),e.jsx(w,{label:"Custom AP per hour",children:e.jsx(D,{type:"number",min:0,step:.5,value:a.customSustainRateApPerHour??"",onChange:f=>d({customSustainRateApPerHour:f.target.value.trim()===""?null:Number(f.target.value)}),placeholder:"Leave empty to use the activity profile"})})]}):null]},n.id)})}):e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"rounded-[24px] border border-amber-400/20 bg-amber-400/10 px-4 py-4 text-sm leading-6 text-amber-100/86",children:"Forge could not find a valid slot on this day. Try another day, adjust the task rules, or switch to manual placement if you already know the right block."}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(U,{variant:"secondary",onClick:()=>void P.refetch(),children:"Refresh suggestions"}),e.jsx(U,{variant:"secondary",onClick:()=>d({plannerMode:"manual"}),children:"Switch to manual"})]})]})}}],[v,J.isLoading,Z,X,V,i.plannerMode,t,x,g,K,O,F,l,P.data,P.isLoading,de,oe,c]);return e.jsx(Ie,{open:s,onOpenChange:o,eyebrow:"Calendar",title:M?"Edit timebox":"Plan work",description:M?"Update the day, hour range, title, and AP profile for this scheduled block without leaving the task or calendar view.":"Review the day, let Forge recommend valid slots, and place a real timebox on the task without leaving the detail view.",value:i,onChange:B,draftPersistenceKey:t?`calendar.timebox.${t.id}`:`calendar.timebox.new.${(l==null?void 0:l.id)??"unscoped"}`,steps:ke,submitLabel:M?"Save timebox":"Schedule timebox",pending:Ne,pendingLabel:"Scheduling",error:be,contentClassName:"md:w-[min(70rem,calc(100vw-1.5rem))]",onSubmit:async()=>{if(!l){j("Choose a task before scheduling a timebox.");return}if(i.plannerMode==="manual"){if(!S||!I){j("Choose a valid manual start and end time.");return}if(I<=S){j("The manual timebox needs an end time after the start time.");return}j(null),W(!0);try{const a={title:i.manualTitle.trim()||l.title,startsAt:S.toISOString(),endsAt:I.toISOString(),overrideReason:i.overrideReason.trim()||null,activityPresetKey:i.activityPresetKey,customSustainRateApPerHour:i.customSustainRateApPerHour};t&&b?await b(t.id,a):await C({taskId:l.id,projectId:l.projectId,...a,source:"manual"}),o(!1)}catch(a){j(a instanceof Error?a.message:"Forge could not create the manual timebox.")}finally{W(!1)}return}if(!L){j("Pick one suggested slot before scheduling the timebox.");return}j(null),W(!0);try{const a={title:L.title,startsAt:L.startsAt,endsAt:L.endsAt,activityPresetKey:i.activityPresetKey,customSustainRateApPerHour:i.customSustainRateApPerHour};t&&b?await b(t.id,a):await C({taskId:l.id,projectId:l.projectId,...a,source:L.source}),o(!1)}catch(a){j(a instanceof Error?a.message:"Forge could not create the selected timebox.")}finally{W(!1)}}})}export{qe as T,Ge as a};
@@ -1 +0,0 @@
1
- import{j as e,aC as w,b8 as H,br as b,bO as P,b5 as B,r as C,aV as L,cA as _}from"./vendor-kIz9EZnX.js";import{i as X}from"./state-VYvD1QVP.js";import{A as O}from"./ai-surface-workspace-xtB5RFQu.js";import{P as W,aq as S,c as x,_ as F,b as k,V as R,B as U,Z as $,u as M,a as V,eR as z,eS as q,C as j,W as K,eT as Q,eU as G,eV as J,bG as Y,bH as Z,bI as ee,bJ as te,bK as se,N as ae}from"./index-BHIKoiZ6.js";import{E as A}from"./entity-note-count-link-BrS1-O0o.js";import{S as T}from"./surface-Bfz_sLX6.js";import{a as ie}from"./life-force-workspace-CLVexVnb.js";import{P as D}from"./page-hero-oFHaAjtL.js";import"./board-DqHzdCPQ.js";import"./motion-CfdU2F35.js";import"./ui-CsEkP2V8.js";import"./forms-CmLAyGqz.js";import"./graph-BTa79qum.js";import"./floating-action-menu-zzC2r0Ob.js";import"./charts-FcU0F3XV.js";function I(s,t){return t.find(c=>c.id===s.goalId)??null}function ne(s,t){return s.tagIds.map(c=>t.find(o=>o.id===c)).filter(Boolean)}function re(s,t){(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),t())}function le(s,t){switch(s.status){case"backlog":return{label:t.backlog,action:"start",icon:b};case"focus":return{label:t.focus,action:"start",icon:b};case"in_progress":return{label:t.in_progress,nextStatus:"done",action:"move",icon:P};case"blocked":return{label:t.blocked,action:"start",icon:b};default:return null}}function de({tasks:s,timeline:t,goals:c,tags:o,notesSummaryByEntity:v,selectedTaskId:f,onSelectTask:r,onMove:u,onStartTask:p}){const{t:l,formatDate:g}=W(),N={backlog:l("common.dailyRunway.actionBacklog"),focus:l("common.dailyRunway.actionFocus"),in_progress:l("common.dailyRunway.actionProgress"),blocked:l("common.dailyRunway.actionBlocked")};return e.jsxs("div",{className:"grid min-w-0 gap-4 2xl:grid-cols-[minmax(0,1.3fr)_minmax(17rem,0.9fr)]",children:[e.jsxs(T,{className:"min-w-0 rounded-[24px]",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",children:l("common.dailyRunway.runwayEyebrow")}),e.jsx(S,{content:"These are the tasks that matter most for today. Click a card to open the task details. Use Start to begin work immediately."})]}),e.jsx("h4",{className:"mt-2 font-display text-2xl text-[var(--ui-ink-strong)]",children:l("common.dailyRunway.runwayTitle")})]}),e.jsx(x,{className:"shrink-0 text-[var(--primary)]",children:l(s.length===1?"common.dailyRunway.prioritiesOne":"common.dailyRunway.prioritiesOther",{count:s.length})})]}),e.jsx("div",{className:"mt-4 grid min-w-0 gap-3",children:s.map((a,y)=>{const d=le(a,N),i=ne(a,o).slice(0,2),n=I(a,c),h=f===a.id,E=F(v,"task",a.id).count;return e.jsxs("article",{role:"button",tabIndex:0,"aria-pressed":h,className:$("grid w-full gap-3 rounded-[22px] border px-4 py-4 text-left transition",h?"border-[var(--primary)]/28 bg-[var(--ui-accent-soft)] shadow-[var(--ui-shadow-soft)]":"border-transparent bg-[var(--ui-surface-1)] hover:border-[var(--ui-border-subtle)] hover:bg-[var(--ui-surface-hover)]"),onClick:()=>r(a.id),onKeyDown:m=>re(m,()=>r(a.id)),children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",children:l("common.dailyRunway.runwayItem",{index:y+1})}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[n?e.jsx(w,{to:`/goals/${n.id}`,className:"min-w-0 max-w-full transition hover:opacity-85",onClick:m=>m.stopPropagation(),children:e.jsx(k,{kind:"goal",label:n.title,compact:!0,gradient:!1})}):e.jsx(k,{kind:"goal",label:l("common.dailyRunway.unassigned"),compact:!0,gradient:!1}),a.time.activeRunCount>0?e.jsx(x,{className:"border-[color-mix(in_srgb,#10b981_24%,transparent)] bg-[color-mix(in_srgb,#10b981_16%,var(--ui-surface-1))] text-[color-mix(in_srgb,#10b981_80%,var(--ui-ink-strong)_20%)]",children:"Live"}):null]}),e.jsx("div",{className:"mt-2",children:e.jsx(w,{to:`/tasks/${a.id}`,className:"block min-w-0 max-w-full transition hover:opacity-85",onClick:m=>m.stopPropagation(),children:e.jsx(R,{kind:"task",label:a.title,variant:"heading",size:"md"})})}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:a.description||l("common.dailyRunway.noNote")})]}),e.jsx(x,{className:"shrink-0 self-start",children:a.status.replaceAll("_"," ")})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(x,{className:"bg-[var(--primary)]/14 text-[var(--primary)]",children:[a.points," xp"]}),e.jsx(A,{entityType:"task",entityId:a.id,count:E}),a.time.totalCreditedSeconds>0?e.jsxs(x,{tone:"meta",children:[Math.floor(a.time.totalCreditedSeconds/60)," min tracked"]}):null,e.jsx(x,{tone:"meta",children:a.effort}),e.jsx(x,{tone:"meta",children:g(a.dueDate)}),i.map(m=>e.jsx(x,{className:"bg-[var(--ui-surface-2)]",style:{color:m.color},children:m.name},m.id))]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:a.owner}),d?e.jsxs(U,{variant:d.action==="start"?"primary":"secondary",className:"px-3 py-2 text-[11px] uppercase tracking-[0.16em]",onClick:async m=>{if(m.stopPropagation(),d.action==="start"){await p(a.id);return}d.nextStatus&&await u(a.id,d.nextStatus)},children:[e.jsx(d.icon,{className:"mr-2 size-3.5"}),d.label]}):null]})]},a.id)})})]}),e.jsxs(T,{className:"min-w-0 rounded-[24px]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",children:l("common.dailyRunway.timelineEyebrow")}),e.jsx(S,{content:"This groups today's tasks by status, so you can see what is already moving, what is ready to start, what is blocked, and what is done."})]}),e.jsx("h4",{className:"mt-2 font-display text-2xl text-[var(--ui-ink-strong)]",children:l("common.dailyRunway.timelineTitle")}),e.jsx("div",{className:"mt-4 grid min-w-0 gap-3",children:t.map(a=>e.jsxs(T,{muted:!0,className:"min-w-0 overflow-hidden rounded-[20px]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium text-[var(--ui-ink-strong)]",children:a.label}),e.jsx(x,{tone:"meta",children:a.tasks.length})]}),e.jsxs("div",{className:"mt-3 grid gap-2",children:[a.tasks.slice(0,3).map(y=>{const d=I(y,c);return e.jsxs(w,{to:`/tasks/${y.id}`,className:"flex min-w-0 items-center justify-between gap-3 overflow-hidden rounded-[16px] bg-[var(--ui-surface-1)] px-3 py-3 text-left transition hover:bg-[var(--ui-surface-hover)]",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx(R,{kind:"task",label:y.title,className:"max-w-full",labelClassName:"[overflow-wrap:anywhere]"}),e.jsx("div",{className:"mt-2",children:e.jsx(k,{kind:"goal",label:(d==null?void 0:d.title)??l("common.dailyRunway.unassigned"),compact:!0,gradient:!1})})]}),e.jsx(H,{className:"size-4 shrink-0 text-[var(--ui-ink-faint)]"})]},y.id)}),a.tasks.length===0?e.jsx("div",{className:"text-sm text-[var(--ui-ink-faint)]",children:l("common.dailyRunway.emptyBucket")}):null]})]},a.id))})]})]})}const oe=5;function ce(){const s=new Date;s.setHours(0,0,0,0);const t=new Date(s);return t.setDate(t.getDate()+1),{start:s,end:t,from:s.toISOString(),to:t.toISOString()}}function me(s,t){const c=new Date(s.startAt),o=new Date(s.endAt);return c<t.end&&o>t.start}function xe(s){if(s.isAllDay)return"All day";const t=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});return`${t.format(new Date(s.startAt))} - ${t.format(new Date(s.endAt))}`}function Re(){var d;const{t:s}=W(),t=M(),c=B(),o=C.useMemo(()=>ce(),[]),v=Array.isArray(t.selectedUserIds)?t.selectedUserIds:[],f=X({queryKey:["forge-calendar-overview",o.from,o.to,...v],queryFn:()=>ae({from:o.from,to:o.to,userIds:v})}),r=t.snapshot.today.directive.task,u=t.snapshot.today.milestoneRewards.find(i=>!i.completed)??t.snapshot.today.milestoneRewards[0]??null,p=t.snapshot.risk.blockedTasks[0]??t.snapshot.risk.overdueTasks[0]??null,l=Math.max(0,t.snapshot.metrics.nextLevelXp-t.snapshot.metrics.currentLevelXp),g=C.useMemo(()=>{var i;return(((i=f.data)==null?void 0:i.calendar.events)??[]).filter(n=>!n.deletedAt&&n.status!=="cancelled"&&me(n,o)).sort((n,h)=>new Date(n.startAt).getTime()-new Date(h.startAt).getTime())},[(d=f.data)==null?void 0:d.calendar.events,o]),N=g.slice(0,oe);if(!(t.snapshot.lifeForce!==void 0||r!==null||t.snapshot.overview.topTasks.length>0||t.snapshot.today.dueHabits.length>0||t.snapshot.today.dailyQuests.length>0||t.snapshot.today.milestoneRewards.length>0||g.length>0)&&!f.isLoading)return e.jsxs("div",{className:"grid gap-4",children:[e.jsx(D,{title:"Today",titleText:"Today",description:"Start a task, earn XP, and keep today's work clear.",badge:`${t.snapshot.metrics.weeklyXp} weekly xp`}),e.jsx(V,{eyebrow:s("common.todayPage.heroEyebrow"),title:s("common.todayPage.emptyTitle"),description:s("common.todayPage.emptyDescription"),action:e.jsx(w,{to:"/goals",className:"inline-flex min-h-10 min-w-max shrink-0 items-center justify-center rounded-full bg-[var(--primary)] px-4 py-2 text-sm font-medium whitespace-nowrap text-slate-950 transition hover:opacity-90",children:s("common.todayPage.emptyAction")})})]});const y=[{id:"hero",title:"Today",description:"Compact page header.",defaultWidth:12,defaultHeight:2,removable:!1,surfaceChrome:"none",defaultTitleVisible:!1,defaultDescriptionVisible:!1,render:()=>e.jsx(z,{children:e.jsx(D,{title:"Today",titleText:"Today",description:(r==null?void 0:r.description)??"Start one real task, collect XP, and keep today's work moving.",badge:`${t.snapshot.metrics.weeklyXp} weekly xp`})})},{id:"life-force",title:"Life Force",description:"Instant headroom, AP use today, and tiredness signals.",defaultWidth:12,defaultHeight:3,minWidth:5,render:()=>e.jsx(ie,{selectedUserIds:t.selectedUserIds,fallbackLifeForce:t.snapshot.lifeForce,onRefresh:t.refresh})},{id:"metrics",title:"Live metrics",description:"XP, level, and momentum stay visible but lighter than before.",defaultWidth:5,defaultHeight:4,minWidth:4,render:({compact:i})=>e.jsx(q,{children:e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs(j,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Weekly XP"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-[var(--primary)]",children:t.snapshot.metrics.weeklyXp}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[t.snapshot.metrics.totalXp," total XP"]})]}),e.jsxs(j,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Level"}),e.jsx("div",{className:"mt-2 font-display text-4xl text-white",children:t.snapshot.metrics.level}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[l," xp to the next level"]}),i?null:e.jsx("div",{className:"mt-3",children:e.jsx(K,{value:t.snapshot.metrics.currentLevelXp/t.snapshot.metrics.nextLevelXp*100,tone:"tertiary"})})]}),e.jsxs(j,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Momentum"}),e.jsxs("div",{className:"mt-2 font-display text-4xl text-white",children:[t.snapshot.metrics.momentumScore,"%"]}),e.jsxs("div",{className:"mt-1 text-sm text-white/56",children:[t.snapshot.metrics.streakDays," day streak"]})]}),e.jsxs(j,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Next reward"}),e.jsx("div",{className:"mt-2 text-base font-semibold text-white",children:(u==null?void 0:u.title)??"Keep showing up"}),e.jsx("div",{className:"mt-1 text-sm text-white/56",children:(u==null?void 0:u.progressLabel)??"The next visible win comes from a task completion or aligned habit check-in."})]})]})})},{id:"runway",title:"Runway",description:"The execution lane itself can be widened or narrowed.",defaultWidth:7,defaultHeight:6,minWidth:5,render:()=>e.jsx(Q,{children:e.jsx(de,{tasks:t.snapshot.overview.topTasks,timeline:t.snapshot.today.timeline,goals:t.snapshot.goals,tags:t.snapshot.tags,notesSummaryByEntity:t.snapshot.dashboard.notesSummaryByEntity,selectedTaskId:(r==null?void 0:r.id)??null,onSelectTask:i=>c(`/tasks/${i}`),onStartTask:async i=>{await t.startTaskNow(i)},onMove:async(i,n)=>{await t.patchTaskStatus(i,n)}})})},{id:"calendar",title:"Calendar",description:"Today's events stay grouped with their results instead of splitting search from outcome.",defaultWidth:5,defaultHeight:5,minWidth:4,render:({compact:i})=>e.jsx(G,{children:e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"inline-flex size-10 shrink-0 items-center justify-center rounded-2xl bg-[var(--primary)]/14 text-[var(--primary)]",children:e.jsx(L,{className:"size-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Today's calendar"}),e.jsx("div",{className:"text-sm font-semibold text-white",children:new Intl.DateTimeFormat(void 0,{weekday:"short",month:"short",day:"numeric"}).format(o.start)}),e.jsxs("div",{className:"text-sm text-white/58",children:[g.length," event",g.length===1?"":"s"]})]})]}),e.jsxs(w,{to:"/calendar",className:"inline-flex shrink-0 items-center gap-2 rounded-full bg-white/[0.06] px-3 py-2 text-xs font-medium text-white/72 transition hover:bg-white/[0.1] hover:text-white",children:["Open calendar",e.jsx(_,{className:"size-3.5"})]})]}),g.length===0?e.jsx("div",{className:"rounded-[18px] bg-white/[0.04] px-4 py-4 text-sm text-white/58",children:"Nothing is scheduled yet for today."}):N.map(n=>e.jsxs("button",{type:"button",className:"grid min-w-0 gap-2 rounded-[18px] bg-white/[0.04] px-3 py-3 text-left transition hover:bg-white/[0.07]",onClick:()=>c("/calendar"),children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white",children:n.title}),e.jsx("div",{className:"mt-1 text-sm text-white/58",children:xe(n)})]}),e.jsx(x,{className:"shrink-0 bg-white/[0.08] text-white/72",children:n.originType==="native"?"Forge":n.originType})]}),!i&&n.description?e.jsx("div",{className:"line-clamp-2 text-sm leading-6 text-white/52",children:n.description}):null]},n.id))]})})},{id:"focus",title:"Current focus",description:"Current task, comeback task, and due habits stay in one movable stack.",defaultWidth:12,defaultHeight:4,minWidth:6,render:({compact:i})=>{var n;return e.jsx(J,{children:e.jsxs("div",{className:"grid min-w-0 gap-4 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]",children:[e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Current task"}),r?e.jsx(A,{entityType:"task",entityId:r.id,count:((n=t.snapshot.dashboard.notesSummaryByEntity[`task:${r.id}`])==null?void 0:n.count)??0}):null]}),e.jsx("div",{className:"mt-3 text-base font-semibold text-white",children:(r==null?void 0:r.title)??"Pick a task from the runway"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/58",children:(r==null?void 0:r.description)??"Once a task is active, the timer rail and this panel stay aligned."}),r?e.jsx("button",{type:"button",className:"mt-4 inline-flex min-h-10 items-center justify-center rounded-2xl bg-[rgba(192,193,255,0.16)] px-3.5 py-2 text-sm font-medium text-[var(--primary)] transition hover:bg-[rgba(192,193,255,0.24)]",onClick:async()=>{await t.startTaskNow(r.id)},children:"Start work"}):null]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Recovery task"}),e.jsx("div",{className:"mt-3 text-sm font-semibold text-white",children:(p==null?void 0:p.title)??"No blocked or overdue task is dominating today"}),i?null:e.jsx("div",{className:"mt-2 text-sm leading-6 text-white/56",children:(p==null?void 0:p.description)??"If something slips, it will surface here as the clean comeback move."})]}),e.jsxs("div",{className:"rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-white/38",children:"Due habits"}),e.jsx("div",{className:"mt-3 grid gap-2",children:t.snapshot.today.dueHabits.slice(0,i?2:3).map(h=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-white/[0.04] px-3 py-2.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white",children:h.title}),i?null:e.jsx("div",{className:"text-sm text-white/52",children:h.frequency})]}),e.jsxs(x,{className:"bg-[rgba(78,222,163,0.14)] text-[var(--secondary)]",children:[h.rewardXp," xp"]})]},h.id))})]})]})]})})}},{id:"time",title:"Clock",description:"Optional utility widget.",defaultWidth:3,defaultHeight:2,defaultHidden:!0,render:({compact:i})=>e.jsx(Y,{compact:i})},{id:"weather",title:"Weather",description:"Optional utility widget.",defaultWidth:3,defaultHeight:2,defaultHidden:!0,render:({compact:i})=>e.jsx(Z,{compact:i})},{id:"mini-calendar",title:"Mini calendar",description:"Optional utility widget.",defaultWidth:4,defaultHeight:3,defaultHidden:!0,render:({compact:i})=>e.jsx(ee,{compact:i})},{id:"spotify",title:"Spotify",description:"Optional utility widget.",defaultWidth:4,defaultHeight:2,defaultHidden:!0,render:()=>e.jsx(te,{surfaceId:"today"})},{id:"quick-capture",title:"Quick capture",description:"Save a note or wiki draft without leaving Today.",defaultWidth:5,defaultHeight:3,defaultHidden:!0,render:({compact:i})=>{var n;return e.jsx(se,{compact:i,defaultUserId:t.selectedUserIds[0]??((n=t.snapshot.users[0])==null?void 0:n.id)??null})}}];return e.jsx(O,{surfaceId:"today",baseWidgets:y})}export{Re as TodayPage};
@@ -1 +0,0 @@
1
- import{r as m,j as e,du as O,aL as K,bL as W,aH as B,cg as P,bF as F,dv as $,bG as V}from"./vendor-kIz9EZnX.js";import{i as G}from"./state-VYvD1QVP.js";import{C as g,aq as b,c as k,u as q,S as U,E as Q,eL as Y}from"./index-BHIKoiZ6.js";import{e as Z,C as I,X as C,Y as f,T as M,B as y,d as H,a as X,c as D,i as J,P as ee,j as te,k as ae,f as ie}from"./charts-FcU0F3XV.js";import{P as se}from"./page-hero-oFHaAjtL.js";import"./motion-CfdU2F35.js";import"./ui-CsEkP2V8.js";import"./forms-CmLAyGqz.js";import"./board-DqHzdCPQ.js";import"./graph-BTa79qum.js";function _({height:a,children:t}){const d=m.useRef(null),[n,l]=m.useState(0);return m.useEffect(()=>{const i=d.current;if(!i)return;const h=()=>{l(Math.max(0,Math.floor(i.getBoundingClientRect().width)))};if(h(),typeof ResizeObserver>"u")return window.addEventListener("resize",h),()=>window.removeEventListener("resize",h);const v=new ResizeObserver(h);return v.observe(i),()=>v.disconnect()},[]),e.jsx("div",{ref:d,style:{height:a},className:"min-w-0",children:n>24?t({width:n,height:a}):null})}const T=["below_z1","zone_1","zone_2","zone_3","zone_4","zone_5"],S={below_z1:"Below Z1",zone_1:"Z1",zone_2:"Z2",zone_3:"Z3",zone_4:"Z4",zone_5:"Z5"},re={below_z1:"#94a3b8",zone_1:"#38bdf8",zone_2:"#22c55e",zone_3:"#eab308",zone_4:"#f97316",zone_5:"#ef4444"},N={timeInZone:"Each block totals the minutes Forge can place into adaptive HRR zones from stored heart-rate samples. Weekly is the default planning view because it matches common training microcycles; monthly and daily views help detect longer trends or recent spikes.",smartMode:"Smart modes do not change the underlying data. They change the coaching lens: combat readiness prioritizes hard-day spacing and controlled high intensity, aerobic base prioritizes low-zone development, and endurance pro compares the distribution with pyramidal or polarized endurance planning patterns.",interpretation:"This paragraph explains what the selected mode concludes from the latest load balance, zone distribution, hard-day count, and data confidence. It is a planning summary, not a medical clearance.",drivers:"Drivers are the signals helping the selected mode: examples include enough easy/base work, controlled high-zone share, stable acute/chronic load, or improving data quality.",limiters:"Limiters are the signals that should constrain the next block. If Forge lists a limiter, the next target should usually solve that before adding more hard work.",targets:"Next targets translate the selected mode into a practical week and next workout. The range is intentionally bounded so training can progress without turning every good week into a maximal week."};function ne(a){return a.key==="combat_readiness"?"Combat":a.key==="aerobic_base"?"Base":"Endurance"}function de(a){return a>=82?"signal":a>=65?"default":"meta"}function le(a){switch(a){case"vo2max_4x4":return"4x4 VO2max";case"zone_2_base":return"Zone 2 / base";case"technical_kickboxing":return"Technical kickboxing";case"easy_aerobic":return"Easy aerobic";case"recovery":return"Recovery";default:return a.replaceAll("_"," ")}}function oe(a,t){return t==="daily"?a.bucketKey.slice(5):t==="monthly"?a.bucketKey.slice(2):a.bucketKey.replace(/^20/,"'")}function ce(a,t){const d=t==="daily"?30:12;return a.slice(-d).map(n=>({bucket:oe(n,t),total:Math.round(n.durationMinutes),load:n.trainingLoad,confidence:n.confidence,...Object.fromEntries(T.map(l=>[l,n.zoneMinutes[l]??0]))}))}function he(a,t){return a.zoneTimeSeries[t]}function xe({mode:a}){return e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-[8px] border border-white/8 bg-white/[0.035] p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.16em] text-white/44",children:[e.jsx(W,{className:"size-3.5"}),"Drivers",e.jsx(b,{label:"Explain training drivers",title:"Drivers",content:N.drivers})]}),e.jsx("div",{className:"mt-3 grid gap-2 text-[12px] leading-5 text-white/62",children:(a.drivers.length>0?a.drivers:["No positive driver is strong enough yet."]).map(t=>e.jsx("div",{children:t},t))})]}),e.jsxs("div",{className:"rounded-[8px] border border-white/8 bg-white/[0.035] p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.16em] text-white/44",children:[e.jsx(B,{className:"size-3.5"}),"Limiters",e.jsx(b,{label:"Explain training limiters",title:"Limiters",content:N.limiters})]}),e.jsx("div",{className:"mt-3 grid gap-2 text-[12px] leading-5 text-white/62",children:(a.limitingFactors.length>0?a.limitingFactors:["No major limiter in this mode right now."]).map(t=>e.jsx("div",{children:t},t))})]})]})}function me({trainingLoad:a}){const[t,d]=m.useState(a.trainingIntelligence.defaultMode),[n,l]=m.useState("weekly"),i=a.trainingIntelligence.modes.find(s=>s.key===t)??a.trainingIntelligence.modes[0],h=he(a,n),v=m.useMemo(()=>ce(h,n),[h,n]),L=h.slice(-8).reverse();return i?e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.25fr)_minmax(340px,0.75fr)]",children:[e.jsxs(g,{className:"overflow-hidden",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-1.5",children:[e.jsx("div",{className:"font-label text-[10px] uppercase tracking-[0.18em] text-white/45",children:"Zone intelligence"}),e.jsx(b,{label:"Explain zone intelligence",title:"Time in zone",content:N.timeInZone})]}),e.jsx("div",{className:"mt-2 text-lg text-white",children:"Time in zone by training block"}),e.jsx("div",{className:"mt-1 max-w-2xl text-[12px] leading-5 text-white/50",children:"Weekly by default because most training plans are adjusted week by week. The stacked bars preserve the full zone split, while the table adds load rate, hard days, and data confidence."})]}),e.jsx("div",{className:"grid grid-cols-3 gap-1 rounded-[8px] border border-white/8 bg-white/[0.035] p-1",children:[["weekly","Week"],["monthly","Month"],["daily","90d"]].map(([s,c])=>e.jsx("button",{type:"button",className:`rounded-[6px] px-3 py-1.5 text-[12px] ${n===s?"bg-white/[0.12] text-white":"text-white/54"}`,onClick:()=>l(s),children:c},s))})]}),e.jsx("div",{className:"mt-5",children:e.jsx(_,{height:320,children:({width:s,height:c})=>e.jsxs(Z,{data:v,width:s,height:c,children:[e.jsx(I,{stroke:"rgba(255,255,255,0.08)",vertical:!1}),e.jsx(C,{dataKey:"bucket",tick:{fill:"rgba(255,255,255,0.54)",fontSize:10}}),e.jsx(f,{tick:{fill:"rgba(255,255,255,0.54)",fontSize:10},width:42}),e.jsx(M,{formatter:(p,o)=>[`${Number(p).toFixed(0)} min`,S[o]??String(o)],contentStyle:{background:"rgba(6,10,18,0.96)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,color:"white"}}),T.map(p=>e.jsx(y,{dataKey:p,stackId:"zones",fill:re[p],name:p},p))]})})}),e.jsx("div",{className:"mt-4 grid gap-3 md:hidden",children:L.map(s=>e.jsxs("div",{className:"rounded-[8px] border border-white/8 bg-white/[0.035] p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-semibold text-white",children:s.bucketKey}),e.jsxs("div",{className:"mt-1 text-xs leading-5 text-white/50",children:["Load ",s.trainingLoad," · ",s.loadPerMinute," ","TRIMP/min"]})]}),e.jsx(k,{tone:"meta",children:s.confidence})]}),e.jsx("div",{className:"mt-3 grid grid-cols-2 gap-2 text-[12px] min-[360px]:grid-cols-3",children:T.map(c=>e.jsxs("div",{className:"rounded-[8px] bg-white/[0.04] px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.12em] text-white/42",children:S[c]}),e.jsxs("div",{className:"mt-0.5 text-white/72",children:[s.zoneMinutes[c]," min"]})]},c))}),e.jsxs("div",{className:"mt-3 text-xs leading-5 text-white/50",children:[s.hardDayCount," hard day",s.hardDayCount===1?"":"s"," in this block."]})]},s.bucketKey))}),e.jsxs("div",{className:"mt-4 hidden overflow-x-auto rounded-[8px] border border-white/8 md:block",children:[e.jsxs("div",{className:"grid min-w-[760px] grid-cols-[96px_72px_72px_repeat(6,64px)_72px_80px] bg-white/[0.045] px-3 py-2 text-[10px] uppercase tracking-[0.14em] text-white/42",children:[e.jsx("div",{children:"Block"}),e.jsx("div",{children:"Load"}),e.jsx("div",{children:"TRIMP/min"}),T.map(s=>e.jsx("div",{children:S[s]},s)),e.jsx("div",{children:"Hard"}),e.jsx("div",{children:"Quality"})]}),L.map(s=>e.jsxs("div",{className:"grid min-w-[760px] grid-cols-[96px_72px_72px_repeat(6,64px)_72px_80px] border-t border-white/8 px-3 py-2 text-[12px] text-white/62",children:[e.jsx("div",{className:"text-white",children:s.bucketKey}),e.jsx("div",{children:s.trainingLoad}),e.jsx("div",{children:s.loadPerMinute}),T.map(c=>e.jsx("div",{children:s.zoneMinutes[c]},c)),e.jsx("div",{children:s.hardDayCount}),e.jsx("div",{children:s.confidence})]},s.bucketKey))]})]}),e.jsxs(g,{className:"overflow-hidden",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-1.5",children:[e.jsx("div",{className:"font-label text-[10px] uppercase tracking-[0.18em] text-white/45",children:"Smart training mode"}),e.jsx(b,{label:"Explain smart training modes",title:"Training mode",content:N.smartMode})]}),e.jsx("div",{className:"mt-2 text-lg text-white",children:i.label})]}),e.jsxs(k,{tone:de(i.score),children:[i.score,"/100"]})]}),e.jsx("div",{className:"mt-4 grid grid-cols-3 gap-1 rounded-[8px] border border-white/8 bg-white/[0.035] p-1",children:a.trainingIntelligence.modes.map(s=>e.jsx("button",{type:"button",className:`rounded-[6px] px-2 py-2 text-[12px] ${s.key===i.key?"bg-white/[0.12] text-white":"text-white/54"}`,onClick:()=>d(s.key),children:ne(s)},s.key))}),e.jsxs("div",{className:"mt-4 rounded-[8px] border border-white/8 bg-white/[0.035] p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.16em] text-white/44",children:[e.jsx(O,{className:"size-3.5"}),"Interpretation",e.jsx(b,{label:"Explain this interpretation",title:"Interpretation",content:N.interpretation})]}),e.jsx("div",{className:"mt-3 text-[13px] leading-5 text-white/72",children:i.summary}),e.jsxs("div",{className:"mt-3 grid grid-cols-2 gap-2 text-[11px] text-white/50",children:[e.jsxs("div",{children:["Balance: ",i.loadBalance.status]}),e.jsxs("div",{children:["Confidence: ",i.confidence]}),e.jsxs("div",{children:["ACWR: ",i.loadBalance.acuteChronicRatio??"n/a"]}),e.jsxs("div",{children:["Baseline:"," ",i.loadBalance.latestWeekBaselineLoadRatio??"n/a","x"]})]})]}),e.jsx("div",{className:"mt-4",children:e.jsx(xe,{mode:i})}),e.jsxs("div",{className:"mt-4 grid gap-3 rounded-[8px] border border-white/8 bg-white/[0.035] p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.16em] text-white/44",children:[e.jsx(K,{className:"size-3.5"}),"Next targets",e.jsx(b,{label:"Explain next training targets",title:"Next targets",content:N.targets})]}),e.jsxs("div",{className:"grid gap-2 text-[12px] leading-5 text-white/62",children:[e.jsxs("div",{children:["Next week: ",i.nextWeekTargets.totalMinutesRange[0],"-",i.nextWeekTargets.totalMinutesRange[1]," min · max"," ",i.nextWeekTargets.maxHardSessions," hard sessions · at least ",i.nextWeekTargets.minimumEasyMinutes," easy/base min."]}),e.jsxs("div",{children:["Next workout:"," ",e.jsx("span",{className:"text-white",children:le(i.nextWorkout.recommendedType)})," ","for ",i.nextWorkout.durationMinutesRange[0],"-",i.nextWorkout.durationMinutesRange[1]," min, ceiling"," ",i.nextWorkout.intensityCeiling,"."]}),e.jsx("div",{className:"text-white/50",children:i.nextWorkout.reason}),i.nextWeekTargets.warning?e.jsx("div",{className:"rounded-[6px] bg-amber-300/10 px-2 py-1 text-amber-100/82",children:i.nextWeekTargets.warning}):null]})]})]})]}):null}const ge={low:"#22c55e",moderate:"#f59e0b",high:"#ef4444"},ue={below_z1:"#94a3b8",zone_1:"#38bdf8",zone_2:"#22c55e",zone_3:"#eab308",zone_4:"#f97316",zone_5:"#ef4444"},x={hero:"Forge estimates cardiovascular training stress from stored workouts, heart-rate samples, adaptive heart-rate-reserve zones, and recent vitals. Use this page to decide whether the next training block should build aerobic base, hold load steady, sharpen intensity, or recover. The numbers support coaching decisions; they are not medical diagnosis.",acuteLoad:"Acute load is the last seven days of Forge's TRIMP-like internal load. It rises when workouts are longer, harder, or spend more time in high heart-rate zones. Compare it with chronic load before adding hard sessions.",chronicBase:"Chronic base is the average weekly load over the last 28 days. It is Forge's estimate of the current load you have recently proven you can absorb.",acwr:"ACWR is acute load divided by chronic weekly load. Values near 1.0 usually mean the current week resembles the recent base. High values ask for recovery checks; low values suggest underloading. Treat it as a flag, not a verdict.",vo2max:"VO2max is the latest available wearable estimate in ml/kg/min. Forge shows the recent change when enough points exist, but wearable VO2max can move with device model, terrain, heat, and workout type.",weeklyMap:"This chart combines weekly internal load, training hours, and the share of time in zones 4 and 5. It helps reveal whether fatigue comes from total volume, hard intensity, or both.",adaptationRadar:"The radar compresses six signals into one coach view: current load, base capacity, acute/chronic balance, heart-rate data quality, high-intensity pressure, and VO2max movement.",intensityTarget:"This compares your recent or all-time low, moderate, and high intensity distribution with broad target bands used in endurance and combat-sport conditioning. The target is a planning reference, not a rule.",hrZones:"These bars show minutes in each adaptive HRR zone. Zone 2 is commonly used for aerobic base, zones 4 and 5 for threshold and VO2max work, and below-zone time often reflects warm-up, recovery, or missing cardiovascular load.",dailyTexture:"Daily texture shows whether load spikes are coming from easy volume, threshold work, or high-intensity minutes. It is useful for spacing hard days and avoiding accidental clusters.",sessionSignals:"Recent workout rows expose the session evidence behind the summary: date, activity, training load, high-zone share, heart-rate response, and data confidence.",sportContribution:"Sport contribution groups load by workout type. In kickboxing and other combat sports, wrist heart rate can undercount short striking spikes, so compare this with how the session actually felt."};function A(a,t=0){return a==null||Number.isNaN(a)?"n/a":`${(a*100).toFixed(t)}%`}function w(a,t=0){return a==null||Number.isNaN(a)?"n/a":a.toFixed(t)}function pe(a){switch(a){case"productive":return{label:"Productive",tone:"signal",text:"Acute load is close to the current chronic base."};case"underloaded":return{label:"Underloaded",tone:"meta",text:"The recent week is below the four-week baseline."};case"overload_watch":return{label:"Watch load",tone:"default",text:"Acute load or strain is elevated enough to deserve recovery checks."};default:return{label:"Building signal",tone:"meta",text:"Forge needs more recent training evidence for a cleaner read."}}}function R({label:a,value:t,detail:d,help:n,icon:l}){return e.jsxs(g,{className:"relative min-h-[136px] overflow-hidden",children:[e.jsx("div",{className:"absolute right-3 top-3 rounded-[8px] border border-white/8 bg-white/[0.045] p-2 text-white/58",children:e.jsx(l,{className:"size-4"})}),e.jsxs("div",{className:"flex max-w-[80%] items-center gap-1.5",children:[e.jsx("div",{className:"font-label text-[10px] uppercase tracking-[0.18em] text-white/45",children:a}),e.jsx(b,{label:`Explain ${a}`,title:a,content:n})]}),e.jsx("div",{className:"mt-4 font-display text-4xl leading-none text-white",children:t}),e.jsx("div",{className:"mt-3 max-w-[24rem] text-[12px] leading-5 text-white/56",children:d})]})}function j({eyebrow:a,title:t,description:d,help:n,action:l}){return e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"font-label text-[10px] uppercase tracking-[0.18em] text-white/45",children:a}),e.jsx(b,{label:`Explain ${a}`,title:t,content:n})]}),e.jsx("div",{className:"mt-2 text-lg text-white",children:t}),d?e.jsx("div",{className:"mt-1 max-w-2xl text-[12px] leading-5 text-white/50",children:d}):null]}),l?e.jsx("div",{className:"shrink-0",children:l}):null]})}function be(a){return a.weeklyLoad.map(t=>({week:t.weekKey.replace(/^20/,"'"),load:t.trainingLoad,hours:t.durationHours,loadPerHour:t.loadPerHour,high:Math.round(t.highPercentage*100),moderate:Math.round(t.moderatePercentage*100),low:Math.round(t.lowPercentage*100)}))}function we(a){return a.dailyLoad.map(t=>({date:t.dateKey.slice(5),load:t.trainingLoad,high:t.highIntensityMinutes,moderate:t.moderateIntensityMinutes,low:t.lowIntensityMinutes}))}function je(a,t){return(t==="recent"?a.recentIntensityDistribution:a.intensityDistribution).map(n=>({...n,percent:Math.round(n.percentage*100),targetLow:Math.round(n.targetRange[0]*100),targetHigh:Math.round(n.targetRange[1]*100),fill:ge[n.key]??"#f8fafc"}))}function ve(a,t){return(t==="recent"?a.recentZoneTotals:a.zoneTotals).map(n=>({...n,minutes:Math.round(n.seconds/60),percent:Math.round(n.percentage*100),fill:ue[n.key]??"#f8fafc"}))}function fe(a){const t=a.summary,d=t.acuteChronicRatio==null?45:Math.max(0,Math.min(100,100-Math.abs(t.acuteChronicRatio-1)*80));return[{axis:"Load",value:Math.min(100,t.acuteLoad7d/3)},{axis:"Base",value:Math.min(100,t.chronicWeeklyLoad28d/3)},{axis:"Balance",value:d},{axis:"Quality",value:Math.min(100,t.averageHeartRateCoverage*100)},{axis:"High",value:Math.min(100,t.highIntensityMinutes7d*1.8)},{axis:"VO2",value:t.vo2MaxDelta==null?50:Math.max(0,Math.min(100,50+t.vo2MaxDelta*10))}]}function ye({sessions:a}){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid gap-3 md:hidden",children:a.slice(0,20).map(t=>e.jsxs("div",{className:"rounded-[8px] border border-white/8 bg-white/[0.035] p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium text-white/86",children:t.workoutTypeLabel}),e.jsxs("div",{className:"mt-1 text-[11px] text-white/46",children:[t.dateKey.slice(5)," ·"," ",w(t.durationMinutes,0),"m ·"," ",t.confidence]})]}),e.jsxs(k,{tone:"meta",children:[w(t.trainingLoad,0)," load"]})]}),e.jsxs("div",{className:"mt-3 grid grid-cols-2 gap-2 text-[12px] text-white/62",children:[e.jsxs("div",{className:"rounded-[8px] bg-white/[0.04] px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.14em] text-white/38",children:"Z4+Z5"}),e.jsx("div",{className:"mt-0.5 text-white",children:A(t.highIntensityPercentage)})]}),e.jsxs("div",{className:"rounded-[8px] bg-white/[0.04] px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.14em] text-white/38",children:"HR"}),e.jsxs("div",{className:"mt-0.5 text-white",children:[t.averageHr?Math.round(t.averageHr):"n/a",t.maxHr?`/${Math.round(t.maxHr)}`:""]})]})]})]},t.id))}),e.jsxs("div",{className:"hidden overflow-hidden rounded-[8px] border border-white/8 md:block",children:[e.jsxs("div",{className:"grid grid-cols-[88px_minmax(118px,1fr)_64px_72px_72px] bg-white/[0.045] px-3 py-2 text-[10px] uppercase tracking-[0.16em] text-white/42",children:[e.jsx("div",{children:"Date"}),e.jsx("div",{children:"Session"}),e.jsx("div",{children:"Load"}),e.jsx("div",{children:"Z4+Z5"}),e.jsx("div",{children:"HR"})]}),e.jsx("div",{className:"max-h-[370px] overflow-auto",children:a.slice(0,20).map(t=>e.jsxs("div",{className:"grid grid-cols-[88px_minmax(118px,1fr)_64px_72px_72px] border-t border-white/6 px-3 py-2 text-[12px] text-white/66",children:[e.jsx("div",{className:"text-white/52",children:t.dateKey.slice(5)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-white/86",children:t.workoutTypeLabel}),e.jsxs("div",{className:"mt-0.5 text-[10px] text-white/42",children:[w(t.durationMinutes,0),"m ·"," ",t.confidence]})]}),e.jsx("div",{className:"text-white",children:w(t.trainingLoad,0)}),e.jsx("div",{children:A(t.highIntensityPercentage)}),e.jsxs("div",{children:[t.averageHr?Math.round(t.averageHr):"n/a",t.maxHr?`/${Math.round(t.maxHr)}`:""]})]},t.id))})]})]})}function Se(){const a=q(),t=Array.isArray(a.selectedUserIds)?a.selectedUserIds:[],[d,n]=m.useState("recent"),l=G({queryKey:["forge-training-load",...t],queryFn:async()=>(await Y(t)).trainingLoad}),i=l.data,h=pe((i==null?void 0:i.summary.readiness)??"insufficient_data"),v=m.useMemo(()=>i?be(i):[],[i]),L=m.useMemo(()=>i?we(i):[],[i]),s=m.useMemo(()=>i?je(i,d):[],[d,i]),c=m.useMemo(()=>i?ve(i,d):[],[d,i]),p=m.useMemo(()=>i?fe(i):[],[i]);if(l.isLoading)return e.jsx(U,{eyebrow:"Training Load",title:"Loading cardiovascular model",description:"Computing acute load, zone distribution, and target bands from workout evidence.",columns:3,blocks:8});if(l.isError||!i)return e.jsx(Q,{eyebrow:"Training Load",error:l.error??new Error("Training load data unavailable"),onRetry:()=>void l.refetch()});const{summary:o}=i;return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(se,{eyebrow:"Health",entityKind:"habit",title:"Training Load",titleText:"Training Load",description:"Forge estimates cardiovascular training stress from workout duration, heart-rate response, adaptive HRR zones, and recent vitals so you can plan the next training block with clearer load and recovery context.",helpContent:x.hero,badge:`${o.sessionCount} sessions · ${o.reliableSessionCount} high-resolution`,actions:e.jsx(k,{tone:h.tone,children:h.label})}),e.jsxs("section",{className:"grid gap-4 lg:grid-cols-4",children:[R({label:"Acute load",value:w(o.acuteLoad7d,0),detail:`Last 7 days of internal load. ${h.text}`,help:x.acuteLoad,icon:F}),R({label:"Chronic base",value:w(o.chronicWeeklyLoad28d,0),detail:"Average weekly load across the last 28 days.",help:x.chronicBase,icon:$}),R({label:"ACWR",value:w(o.acuteChronicRatio,2),detail:"Acute load divided by chronic weekly load. Useful as a flag, not a verdict.",help:x.acwr,icon:W}),R({label:"VO2 max",value:o.vo2MaxLatest?w(o.vo2MaxLatest,1):"n/a",detail:o.vo2MaxDelta==null?"No delta available yet.":`${o.vo2MaxDelta>=0?"+":""}${o.vo2MaxDelta} since the first recent point.`,help:x.vo2max,icon:V})]}),e.jsx(me,{trainingLoad:i}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.35fr)_minmax(320px,0.65fr)]",children:[e.jsxs(g,{className:"overflow-hidden",children:[e.jsx(j,{eyebrow:"Weekly load map",title:"Load, hours, and high-intensity share over the last 26 weeks.",description:"Load estimates internal stress; hours show volume; the red line shows how much of each week landed in zones 4 and 5.",help:x.weeklyMap,action:e.jsx(k,{tone:"meta",children:"TRIMP · HRR zones"})}),e.jsx("div",{className:"mt-5",children:e.jsx(_,{height:340,children:({width:r,height:u})=>e.jsxs(H,{data:v,width:r,height:u,children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"trainingLoadFill",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"#38bdf8",stopOpacity:.38}),e.jsx("stop",{offset:"100%",stopColor:"#38bdf8",stopOpacity:.04})]})}),e.jsx(I,{stroke:"rgba(255,255,255,0.08)",vertical:!1}),e.jsx(C,{dataKey:"week",tick:{fill:"rgba(255,255,255,0.54)",fontSize:10}}),e.jsx(f,{yAxisId:"load",tick:{fill:"rgba(255,255,255,0.54)",fontSize:10},width:42}),e.jsx(f,{yAxisId:"pct",orientation:"right",domain:[0,100],tick:{fill:"rgba(255,255,255,0.54)",fontSize:10},width:38}),e.jsx(M,{contentStyle:{background:"rgba(6,10,18,0.96)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,color:"white"}}),e.jsx(X,{yAxisId:"load",type:"monotone",dataKey:"load",name:"Training load",stroke:"#38bdf8",fill:"url(#trainingLoadFill)",strokeWidth:2}),e.jsx(y,{yAxisId:"load",dataKey:"hours",name:"Hours",fill:"#a78bfa",radius:[3,3,0,0]}),e.jsx(D,{yAxisId:"pct",type:"monotone",dataKey:"high",name:"Z4+Z5 %",stroke:"#ef4444",strokeWidth:2.4,dot:{r:2}})]})})})]}),e.jsxs(g,{className:"overflow-hidden",children:[e.jsx(j,{eyebrow:"Adaptation radar",title:"Current signal balance",description:"A compact coach view of load, base, balance, data quality, high-intensity pressure, and VO2max movement.",help:x.adaptationRadar}),e.jsx("div",{className:"mt-4",children:e.jsx(_,{height:300,children:({width:r,height:u})=>e.jsxs(J,{data:p,width:r,height:u,children:[e.jsx(ee,{stroke:"rgba(255,255,255,0.12)"}),e.jsx(te,{dataKey:"axis",tick:{fill:"rgba(255,255,255,0.64)",fontSize:10}}),e.jsx(ae,{dataKey:"value",stroke:"#22c55e",fill:"#22c55e",fillOpacity:.24}),e.jsx(M,{contentStyle:{background:"rgba(6,10,18,0.96)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,color:"white"}})]})})})]})]}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)]",children:[e.jsxs(g,{children:[e.jsx(j,{eyebrow:"Intensity target",title:"Distribution vs target bands",description:"Compare the selected time window with broad low, moderate, and high intensity bands.",help:x.intensityTarget,action:e.jsx("div",{className:"grid grid-cols-2 gap-1 rounded-[8px] border border-white/8 bg-white/[0.035] p-1",children:[["recent","28d"],["all","All"]].map(([r,u])=>e.jsx("button",{type:"button",className:`rounded-[6px] px-3 py-1.5 text-[12px] ${d===r?"bg-white/[0.12] text-white":"text-white/54"}`,onClick:()=>n(r),children:u},r))})}),e.jsx("div",{className:"mt-4 grid gap-3",children:s.map(r=>e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-[12px]",children:[e.jsx("span",{className:"text-white/74",children:r.label}),e.jsxs("span",{className:"text-white",children:[r.percent,"% · target ",r.targetLow,"-",r.targetHigh,"%"]})]}),e.jsxs("div",{className:"relative h-3 overflow-hidden rounded-full bg-white/[0.08]",children:[e.jsx("div",{className:"absolute inset-y-0 rounded-full bg-white/[0.12]",style:{left:`${r.targetLow}%`,width:`${Math.max(2,r.targetHigh-r.targetLow)}%`}}),e.jsx("div",{className:"relative h-full rounded-full",style:{width:`${Math.max(1,r.percent)}%`,background:r.fill}})]})]},r.key))}),e.jsx("div",{className:"mt-5 grid gap-2 rounded-[8px] border border-white/8 bg-white/[0.035] p-3 text-[12px] leading-5 text-white/54",children:i.targetModel.monitoringNotes.map(r=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(K,{className:"mt-0.5 size-3.5 shrink-0 text-[var(--primary)]"}),e.jsx("span",{children:r})]},r))})]}),e.jsxs(g,{children:[e.jsx(j,{eyebrow:"HR zones",title:`Detailed zone distribution for ${d==="recent"?"the last 28 days":"all available sessions"}.`,help:x.hrZones}),e.jsx("div",{className:"mt-4",children:e.jsx(_,{height:290,children:({width:r,height:u})=>e.jsxs(Z,{data:c,width:r,height:u,children:[e.jsx(I,{stroke:"rgba(255,255,255,0.08)",vertical:!1}),e.jsx(C,{dataKey:"label",interval:0,tick:{fill:"rgba(255,255,255,0.56)",fontSize:10}}),e.jsx(f,{tick:{fill:"rgba(255,255,255,0.56)",fontSize:10},width:38}),e.jsx(M,{formatter:(z,E)=>[E==="minutes"?`${z} min`:`${z}%`,E],contentStyle:{background:"rgba(6,10,18,0.96)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,color:"white"}}),e.jsx(y,{dataKey:"minutes",name:"minutes",radius:[4,4,0,0],children:c.map(z=>e.jsx(ie,{fill:z.fill},z.key))})]})})})]})]}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1fr)_420px]",children:[e.jsxs(g,{children:[e.jsx(j,{eyebrow:"Daily load texture",title:"Easy, threshold, and high-intensity minutes against daily load.",help:x.dailyTexture}),e.jsx("div",{className:"mt-4",children:e.jsx(_,{height:310,children:({width:r,height:u})=>e.jsxs(H,{data:L,width:r,height:u,children:[e.jsx(I,{stroke:"rgba(255,255,255,0.08)",vertical:!1}),e.jsx(C,{dataKey:"date",tick:{fill:"rgba(255,255,255,0.54)",fontSize:10}}),e.jsx(f,{yAxisId:"minutes",tick:{fill:"rgba(255,255,255,0.54)",fontSize:10},width:38}),e.jsx(f,{yAxisId:"load",orientation:"right",tick:{fill:"rgba(255,255,255,0.54)",fontSize:10},width:38}),e.jsx(M,{contentStyle:{background:"rgba(6,10,18,0.96)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,color:"white"}}),e.jsx(y,{yAxisId:"minutes",dataKey:"low",stackId:"zones",fill:"#22c55e",name:"low min"}),e.jsx(y,{yAxisId:"minutes",dataKey:"moderate",stackId:"zones",fill:"#f59e0b",name:"threshold min"}),e.jsx(y,{yAxisId:"minutes",dataKey:"high",stackId:"zones",fill:"#ef4444",name:"high min"}),e.jsx(D,{yAxisId:"load",type:"monotone",dataKey:"load",stroke:"#38bdf8",strokeWidth:2.2,dot:!1})]})})})]}),e.jsxs(g,{children:[e.jsx(j,{eyebrow:"Session signals",title:"Recent workouts",help:x.sessionSignals,action:e.jsxs(k,{tone:"meta",children:[o.hardDayCount7d," hard days / 7d"]})}),e.jsx("div",{className:"mt-4",children:e.jsx(ye,{sessions:i.sessionSignals})})]})]}),e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsxs(g,{children:[e.jsx(j,{eyebrow:"Sport contribution",title:"Load by workout type",help:x.sportContribution}),e.jsx("div",{className:"mt-3 grid gap-3",children:i.activityBreakdown.slice(0,8).map(r=>e.jsxs("div",{className:"grid gap-2 rounded-[8px] border border-white/8 bg-white/[0.035] p-3 sm:grid-cols-[minmax(0,1fr)_76px_76px_76px]",children:[e.jsxs("div",{children:[e.jsx("div",{className:"truncate text-sm text-white",children:r.workoutTypeLabel}),e.jsxs("div",{className:"mt-1 text-[11px] text-white/46",children:[r.sessionCount," sessions ·"," ",r.activityFamilyLabel]})]}),e.jsxs("div",{className:"text-[12px] text-white/62",children:[e.jsxs("span",{className:"block text-white",children:[r.durationHours,"h"]}),"volume"]}),e.jsxs("div",{className:"text-[12px] text-white/62",children:[e.jsx("span",{className:"block text-white",children:r.trainingLoad}),"load"]}),e.jsxs("div",{className:"text-[12px] text-white/62",children:[e.jsx("span",{className:"block text-white",children:A(r.highPercentage)}),"high"]})]},r.workoutType))})]}),e.jsxs(g,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(P,{className:"size-4 text-amber-300"}),e.jsx("div",{className:"font-label text-[10px] uppercase tracking-[0.18em] text-white/45",children:"Interpretation guardrails"})]}),e.jsxs("div",{className:"mt-4 grid gap-3 text-[12px] leading-5 text-white/56",children:[e.jsx("p",{children:"Forge is estimating training stress from heart-rate reserve zones and a TRIMP-like load. This is good for trend decisions, but it is not a substitute for lactate testing, gas exchange thresholds, or coach-led periodization."}),e.jsx("p",{children:"Combat sports add sensor noise: wrist HR can miss short spikes during punching and clinch work. Treat high-intensity minutes as minimum evidence when the session had a lot of arm motion."}),e.jsx("p",{children:"The practical target is not maximum Z5. Keep hard combat sessions meaningful, then add easy aerobic base when the high-intensity share is already high."})]})]})]})]})}export{Se as TrainingLoadPage};
@@ -1 +0,0 @@
1
- import{j as e}from"./vendor-kIz9EZnX.js";import{j as h,i as u,k as y}from"./state-VYvD1QVP.js";import{F as v}from"./flagship-signal-deck-BEFKOhvx.js";import{P as f,fp as g,i as j,S as k,E as x,C as o,c as w,B as N,fq as b}from"./index-BHIKoiZ6.js";import{P as R}from"./page-hero-oFHaAjtL.js";import{R as S,e as z,X as $,Y as P,B as X}from"./charts-FcU0F3XV.js";import"./motion-CfdU2F35.js";import"./ui-CsEkP2V8.js";import"./forms-CmLAyGqz.js";import"./board-DqHzdCPQ.js";import"./graph-BTa79qum.js";function M(){var c;const{t}=f(),n=h(),l=u({queryKey:["forge-weekly-review"],queryFn:b}),d=y({mutationFn:g,onSuccess:async()=>{await Promise.all([n.invalidateQueries({queryKey:["forge-weekly-review"]}),n.invalidateQueries({queryKey:["forge-xp-metrics"]}),n.invalidateQueries({queryKey:["forge-reward-ledger"]}),j(n),n.invalidateQueries({queryKey:["activity-archive"]})])}}),i=(c=l.data)==null?void 0:c.review;if(l.isLoading)return e.jsx(k,{});if(l.isError)return e.jsx(x,{eyebrow:t("common.weeklyReview.heroEyebrow"),error:l.error,onRetry:()=>void l.refetch()});if(!i)return e.jsx(x,{eyebrow:t("common.weeklyReview.heroEyebrow"),error:new Error("Forge returned an empty weekly review payload."),onRetry:()=>void l.refetch()});const r=i.wins[0]??null,a=i.calibration.find(s=>s.mode==="recover")??i.calibration[0]??null,m=i.calibration.find(s=>s.mode==="accelerate")??i.calibration[0]??null,p=[{id:"week",label:"This week",title:`${i.momentumSummary.totalXp} XP with ${i.momentumSummary.focusHours} focus hours`,detail:`Peak window: ${i.momentumSummary.peakWindow}. Efficiency score is holding at ${i.momentumSummary.efficiencyScore}.`,badge:i.windowLabel},{id:"wins",label:"Wins",title:(r==null?void 0:r.title)??t("common.weeklyReview.noWin"),detail:(r==null?void 0:r.summary)??t("common.weeklyReview.noWinDetail"),badge:r?`+${r.rewardXp} xp`:`${i.wins.length} wins`},{id:"recovery",label:"Recovery",title:(a==null?void 0:a.title)??t("common.weeklyReview.noRecovery"),detail:(a==null?void 0:a.note)??t("common.weeklyReview.noRecoveryDetail"),badge:(a==null?void 0:a.mode)??"maintain"},{id:"next-intent",label:"Next intent",title:(m==null?void 0:m.title)??i.reward.title,detail:(m==null?void 0:m.note)??i.reward.summary,badge:`+${i.reward.rewardXp} xp`}];return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(R,{title:"Weekly Review",description:`${i.windowLabel}. ${t("common.weeklyReview.heroDescription")}`,badge:`${i.momentumSummary.totalXp} xp`}),e.jsxs("section",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(o,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.weeklyReview.sectionMomentum")}),e.jsx("div",{className:"mt-4 h-64",children:e.jsx(S,{width:"100%",height:"100%",children:e.jsxs(z,{data:i.chart,children:[e.jsx($,{dataKey:"label",tick:{fill:"rgba(255,255,255,0.42)",fontSize:11}}),e.jsx(P,{hide:!0}),e.jsx(X,{dataKey:"xp",fill:"#c0c1ff",radius:[8,8,0,0]})]})})}),e.jsxs("div",{className:"mt-4 grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/40",children:"XP"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:i.momentumSummary.totalXp})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Focus hours"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:i.momentumSummary.focusHours})]}),e.jsxs("div",{className:"rounded-[18px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Peak window"}),e.jsx("div",{className:"mt-2 text-2xl text-white",children:i.momentumSummary.peakWindow})]})]})]}),e.jsxs(o,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.weeklyReview.sectionGoals")}),e.jsx("div",{className:"mt-4 grid gap-3",children:i.calibration.map(s=>e.jsxs("div",{className:"overflow-hidden rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0 flex-1 font-medium text-white",children:s.title}),e.jsx(w,{className:"max-w-[9rem] shrink-0 self-start",children:s.mode})]}),e.jsx("div",{className:"mt-3 text-sm text-white/58",children:s.note})]},s.id))})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(o,{children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/45",children:t("common.weeklyReview.sectionWins")}),e.jsx("div",{className:"mt-4 grid gap-3",children:i.wins.map(s=>e.jsxs("div",{className:"overflow-hidden rounded-[20px] bg-white/[0.04] p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0 flex-1 font-medium text-white",children:s.title}),e.jsxs(w,{className:"max-w-[8rem] shrink-0 self-start text-emerald-300",children:["+",s.rewardXp," xp"]})]}),e.jsx("div",{className:"mt-2 text-sm text-white/58",children:s.summary})]},s.id))})]}),e.jsxs(o,{children:[e.jsx("h2",{className:"font-display text-3xl text-white",children:i.reward.title}),e.jsx("p",{className:"mt-3 text-sm leading-7 text-white/60",children:i.reward.summary}),e.jsxs("div",{className:"mt-4 rounded-[20px] bg-white/[0.04] p-4",children:[e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-white/40",children:t("common.weeklyReview.completionBonus")}),e.jsxs("div",{className:"mt-2 text-3xl text-[var(--primary)]",children:["+",i.reward.rewardXp," XP"]})]}),e.jsx(N,{className:"mt-4 w-full",disabled:i.completion.finalized,pending:d.isPending,pendingLabel:t("common.weeklyReview.finalizePending"),onClick:async()=>{await d.mutateAsync()},children:i.completion.finalized?t("common.weeklyReview.finalized"):t("common.weeklyReview.finalize")}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-white/58",children:i.completion.finalized?`${t("common.weeklyReview.finalizedDetail")} ${i.completion.finalizedBy?`By ${i.completion.finalizedBy}. `:""}${i.completion.finalizedAt?new Date(i.completion.finalizedAt).toLocaleString():""}`.trim():i.reward.summary})]})]})]}),e.jsx(v,{eyebrow:t("common.weeklyReview.summaryEyebrow"),title:t("common.weeklyReview.summaryTitle"),description:t("common.weeklyReview.summaryDescription"),items:p})]})}export{M as WeeklyReviewPage};
@@ -1,5 +0,0 @@
1
- import{j as a,b4 as _e,aG as Ye,b3 as Je,cm as wa,dx as Ca,cG as Ma,bL as Ae,bX as Ga,cK as Ze,ce as Fa,c7 as Xe,dy as Sa,dz as Aa,bE as ea,dA as Ka,dB as _a,r as M,d8 as Ia,bH as Be,dC as Ta,bF as La,bu as Ea}from"./vendor-kIz9EZnX.js";import{j as $a,i as Da,k as z}from"./state-VYvD1QVP.js";import{P as Ra}from"./page-hero-oFHaAjtL.js";import{C as O,B as K,aq as ce,I as j,Z as aa,c as L,Q as ve,F as v,j as qe,T as xe,u as Pa,eW as Wa,eX as Ba,eY as He,eZ as qa,e_ as Ha,e$ as za,f0 as Oa,f1 as ze,f2 as Ua,f3 as Qa,f4 as Va,L as Ya,E as Ja,f5 as Za}from"./index-BHIKoiZ6.js";import{S as E,a as k}from"./surface-Bfz_sLX6.js";import"./motion-CfdU2F35.js";import"./ui-CsEkP2V8.js";import"./forms-CmLAyGqz.js";import"./board-DqHzdCPQ.js";import"./graph-BTa79qum.js";function Xa({view:e,onOpenPlan:t,onOpenFoodSearch:s,onOpenCustomFood:r,onOpenChatGptFood:n,onOpenCheckin:c,onOpenHistory:g}){return a.jsxs(O,{className:"grid gap-4 border-[var(--ui-border-subtle)] bg-[var(--ui-surface-section)] p-5 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-center",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",children:"Control center"}),a.jsx("h2",{className:"mt-1 text-xl font-semibold text-[var(--ui-ink-strong)]",children:e.target.bodyGoal?`Goal: ${e.target.bodyGoal}`:"Set the body objective"}),a.jsxs("p",{className:"mt-2 max-w-3xl text-sm leading-6 text-[var(--ui-ink-soft)]",children:["Current target: ",e.target.calorieTarget.toFixed(0)," kcal,"," ",e.target.proteinGramsTarget.toFixed(0),"g protein,"," ",e.target.fiberGramsTarget.toFixed(0),"g fiber. Adjust the plan, add food with exact quantities, or record body signals from guided flows."]})]}),a.jsxs("div",{className:"grid min-w-0 gap-2 sm:grid-cols-2 xl:grid-cols-3",children:[a.jsxs(K,{type:"button",onClick:r,children:[a.jsx(_e,{className:"size-4"}),"Custom food"]}),a.jsxs(K,{type:"button",variant:"secondary",onClick:n,children:[a.jsx(Ye,{className:"size-4"}),"Ask ChatGPT"]}),a.jsxs(K,{type:"button",variant:"secondary",onClick:s,children:[a.jsx(Je,{className:"size-4"}),"Search food"]}),a.jsxs(K,{type:"button",variant:"secondary",onClick:t,children:[a.jsx(wa,{className:"size-4"}),"Plan settings"]}),a.jsxs(K,{type:"button",variant:"secondary",onClick:c,children:[a.jsx(Ca,{className:"size-4"}),"Add measure"]}),a.jsxs(K,{type:"button",variant:"secondary",onClick:g,children:[a.jsx(Ma,{className:"size-4"}),"Food history"]})]})]})}function _(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ne(e){return typeof e=="string"&&e.trim()?e:null}function m(e,t=0){const s=_(e);return s===null?"n/a":s.toFixed(t)}function fe(e,t=0){const s=_(e);return s===null?"n/a":`${s>0?"+":""}${s.toFixed(t)}`}function he(e){const t=_(e);return t===null?"n/a":`${t.toFixed(1)}/10`}function et(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&!Array.isArray(t)):[]}function at(e){switch(e){case"user_override":return"Manual override for today";case"today_healthkit_active_energy":return"HealthKit active energy today";case"today_workout_movement_energy":return"Workout + movement today";case"today_workout_movement_step_energy":return"Workout + movement + steps today";case"today_workout_step_energy":return"Workout + steps today";case"today_movement_step_energy":return"Movement + steps today";case"today_workout_energy":return"Workout energy today";case"today_movement_trip_calories":return"Movement trips today";case"today_step_estimate":return"Step estimate today";default:return"Default daily active calories"}}function tt(e){switch(e){case"user_override":return"Using your manual value for today.";case"today_healthkit_active_energy":return"Using same-day HealthKit active energy instead of the default.";case"today_workout_movement_energy":return"Using today's workout and movement calories instead of the default.";case"today_workout_movement_step_energy":return"Using today's workouts, movement, and steps instead of the default.";case"today_workout_step_energy":return"Using today's workouts and steps instead of the default.";case"today_movement_step_energy":return"Using today's movement and steps instead of the default.";case"today_workout_energy":return"Using today's workout calories instead of the default.";case"today_movement_trip_calories":return"Using today's movement calories instead of the default.";case"today_step_estimate":return"Using today's step estimate instead of the default.";default:return"No same-day active evidence yet, so the default active calories are used."}}function st({view:e,draftValue:t,pending:s,error:r,onDraftChange:n,onSave:c,onReset:g}){const o=e.energyModel,i=e.todayLedger,l=o.todayActiveOverride,w=o.todayActiveCaloriesSource,x=`${i.plannedTargetCalories.toFixed(0)} + (${o.todayActiveCaloriesKcal.toFixed(0)} - ${o.baselineActiveCaloriesKcal.toFixed(0)}) = ${i.targetCalories.toFixed(0)} kcal`;return a.jsxs(O,{className:"grid min-w-0 gap-3 border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-4",children:[a.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-1 text-[11px] uppercase tracking-[0.14em] text-[var(--ui-ink-faint)]",children:["Active kcal",a.jsx(ce,{label:"Explain active calories",content:`Today target = baseline food target + (today active calories - default active calories). ${x}. Same-day HealthKit active energy, workouts, movement, or steps replace the default. A manual edit overrides today only.`})]}),a.jsxs("div",{className:"mt-1 text-2xl font-semibold leading-tight text-[var(--ui-ink-strong)]",children:[o.todayActiveCaloriesKcal.toFixed(0)," kcal"]})]}),a.jsx("div",{className:"rounded-[8px] bg-[var(--ui-info-soft)] p-2 text-[color-mix(in_srgb,var(--info)_78%,var(--ui-ink-strong)_22%)]",children:a.jsx(Ae,{className:"size-4"})})]}),a.jsxs("div",{className:"grid gap-1 text-xs leading-5 text-[var(--ui-ink-soft)]",children:[a.jsx("div",{className:"break-words font-medium text-[var(--ui-ink-medium)]",children:tt(w)}),a.jsxs("div",{children:["Default ",o.baselineActiveCaloriesKcal.toFixed(0)," kcal"," · ","observed"," ",o.todayObservedActiveCaloriesKcal!=null?`${o.todayObservedActiveCaloriesKcal.toFixed(0)} kcal`:"n/a"]}),a.jsxs("div",{className:"break-words",children:["Source: ",at(w)]})]}),a.jsxs("div",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)_auto] gap-2",children:[a.jsx(j,{inputMode:"decimal",value:t,onChange:b=>n(b.target.value),"aria-label":"Today active calories",className:"py-2.5"}),a.jsxs(K,{type:"button",onClick:c,pending:s,pendingLabel:"Applying",children:[a.jsx(Ga,{className:"size-4"}),"Apply"]})]}),a.jsxs(K,{type:"button",variant:"secondary",onClick:g,disabled:!l||s,children:[a.jsx(Ze,{className:"size-4"}),"Use evidence"]}),r?a.jsx("div",{className:"rounded-[8px] border border-[var(--danger)]/20 bg-[var(--ui-danger-soft)] px-3 py-2 text-xs leading-5 text-[color-mix(in_srgb,var(--danger)_76%,var(--ui-ink-strong)_24%)]",children:r}):null]})}const rt={default:"bg-[color-mix(in_srgb,var(--primary)_14%,transparent)] text-[var(--primary)]",green:"bg-[var(--ui-success-soft)] text-[color-mix(in_srgb,var(--success)_78%,var(--ui-ink-strong)_22%)]",amber:"bg-[var(--ui-warning-soft)] text-[color-mix(in_srgb,var(--warning)_76%,var(--ui-ink-strong)_24%)]",rose:"bg-[var(--ui-danger-soft)] text-[color-mix(in_srgb,var(--danger)_76%,var(--ui-ink-strong)_24%)]",cyan:"bg-[var(--ui-info-soft)] text-[color-mix(in_srgb,var(--info)_78%,var(--ui-ink-strong)_22%)]"};function Q({label:e,value:t,detail:s,icon:r,tone:n="default",help:c}){return a.jsxs(O,{className:"grid gap-4 border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-5",children:[a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsx("div",{className:aa("rounded-2xl p-2.5",rt[n]),children:a.jsx(r,{className:"size-5"})}),a.jsxs("div",{className:"flex items-center justify-end gap-1 text-right text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:[a.jsx("span",{children:e}),c?a.jsx(ce,{content:c,label:`Explain ${e}`}):null]})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-3xl font-semibold text-[var(--ui-ink-strong)]",children:t}),a.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:s})]})]})}function nt({meal:e,onLogAgain:t,onEdit:s,onDelete:r,pending:n=!1}){const c=e.items[0]??null,g=Math.max(0,e.items.length-1),o=c?`${c.name}${g>0?` + ${g} more`:""}`:e.mealLabel??"Meal",i=e.items.slice(0,3).map(l=>{const w=Number.isFinite(l.quantity)&&l.quantity>0?Number.isInteger(l.quantity)?String(l.quantity):l.quantity.toFixed(2).replace(/\.?0+$/,""):null,x=l.unit??"serving",b=l.grams!=null?`${l.grams.toFixed(0)}g`:null;return[w,x,b?`(${b})`:null].filter(Boolean).join(" ")}).filter(Boolean).join(" · ");return a.jsxs(E,{className:"grid min-w-0 gap-3",children:[a.jsxs("div",{className:"flex min-w-0 flex-wrap items-start justify-between gap-3",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsx("div",{className:"break-words text-base font-semibold leading-6 text-[var(--ui-ink-strong)]",children:o}),a.jsx("div",{className:"mt-1 text-xs leading-5 text-[var(--ui-ink-faint)]",children:i||e.notes||"No quantity recorded"})]}),a.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[e.mealLabel?a.jsx(L,{tone:"meta",children:e.mealLabel}):null,a.jsxs(L,{tone:"meta",children:[e.totals.calories.toFixed(0)," kcal"]})]})]}),a.jsxs("div",{className:"grid gap-2 text-xs text-[var(--ui-ink-soft)] sm:grid-cols-3 xl:grid-cols-6",children:[a.jsxs("span",{children:[e.totals.proteinGrams.toFixed(0),"g protein"]}),a.jsxs("span",{children:[e.totals.carbohydrateGrams.toFixed(0),"g carbs"]}),a.jsxs("span",{children:[e.totals.fatGrams.toFixed(0),"g fat"]}),a.jsxs("span",{children:[e.totals.fiberGrams.toFixed(0),"g fiber"]}),a.jsxs("span",{children:[e.totals.sodiumMg.toFixed(0),"mg sodium"]}),a.jsx("span",{children:e.confirmationState})]}),a.jsxs("div",{className:"flex flex-wrap gap-2",children:[s?a.jsxs(K,{type:"button",size:"sm",variant:"secondary",onClick:()=>s(e),children:[a.jsx(Fa,{className:"size-4"}),"Edit"]}):null,r?a.jsxs(K,{type:"button",size:"sm",variant:"ghost",pending:n,onClick:()=>r(e),children:[a.jsx(Xe,{className:"size-4"}),"Delete"]}):null,t?a.jsxs(K,{type:"button",size:"sm",variant:"ghost",pending:n,onClick:()=>t(e),children:[a.jsx(Ze,{className:"size-4"}),"Log again"]}):null]})]})}function Ie({children:e}){return a.jsx(E,{className:"border-dashed border-[var(--ui-border-strong)] p-5 text-sm text-[var(--ui-ink-soft)]",children:e})}function it({ledger:e,remainingCalories:t,intakePercent:s,logSavedPending:r,onLogAgain:n,onEditMeal:c,onDeleteMeal:g}){const o=e.totals;return a.jsxs(O,{className:"grid gap-5 border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-5",children:[a.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",children:"Food log"}),a.jsxs("h2",{className:"mt-1 flex items-center gap-2 text-xl font-semibold text-[var(--ui-ink-strong)]",children:[a.jsx("span",{children:"Calories, macros, and meal evidence"}),a.jsx(ce,{label:"Explain food log",content:"The food log is today's editable record of what was eaten. Edit a meal to change quantities, remove items, correct food parameters, or delete the meal entirely."})]})]}),a.jsxs(L,{tone:"meta",children:[e.meals.length," meals"]})]}),a.jsxs("div",{children:[a.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-[var(--ui-surface-2)]",children:a.jsx("div",{className:aa("h-full rounded-full",t>=0?"bg-[color-mix(in_srgb,var(--success)_82%,var(--secondary)_18%)]":"bg-[color-mix(in_srgb,var(--danger)_82%,var(--tertiary)_18%)]"),style:{width:`${Math.min(100,s)}%`}})}),a.jsxs("div",{className:"mt-3 grid gap-2 text-sm text-[var(--ui-ink-soft)] sm:grid-cols-4",children:[a.jsxs("span",{children:[o.carbohydrateGrams.toFixed(0),"g carbs"]}),a.jsxs("span",{children:[o.fatGrams.toFixed(0),"g fat"]}),a.jsxs("span",{children:[o.fiberGrams.toFixed(0),"g fiber"]}),a.jsxs("span",{children:[e.unconfirmedCount," unconfirmed"]})]})]}),a.jsx("div",{className:"grid gap-3",children:e.meals.length>0?e.meals.map(i=>a.jsx(nt,{meal:i,pending:r,onLogAgain:n,onEdit:c,onDelete:g},i.id)):a.jsx(Ie,{children:"No meals logged today yet."})})]})}function ot({hypotheses:e}){return a.jsxs(O,{className:"grid gap-4 border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-5",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",children:"Hypotheses"}),a.jsx("h2",{className:"mt-1 text-xl font-semibold text-[var(--ui-ink-strong)]",children:"Food and body pattern candidates"})]}),a.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:e.length>0?e.slice(0,6).map((t,s)=>a.jsxs(E,{children:[a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsx(L,{tone:"signal",children:ne(t.metric)??"pattern"}),a.jsx("span",{className:"text-xs text-[var(--ui-ink-faint)]",children:m(t.confidence,2)})]}),a.jsx("div",{className:"mt-3 text-sm font-medium text-[var(--ui-ink-strong)]",children:ne(t.label)??"Candidate pattern"}),a.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:ne(t.description)??"Forge needs more paired meals and check-ins to harden this signal."})]},String(t.key??s))):a.jsx("div",{className:"md:col-span-2",children:a.jsx(Ie,{children:"Log meals plus energy, gut, and look check-ins for a few days to generate pattern candidates."})})})]})}function lt({experiments:e}){return a.jsxs(O,{className:"grid content-start gap-4 border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-5",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"rounded-2xl bg-[var(--ui-info-soft)] p-2.5 text-[color-mix(in_srgb,var(--info)_78%,var(--ui-ink-strong)_22%)]",children:a.jsx(Sa,{className:"size-5"})}),a.jsxs("div",{children:[a.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",children:"Experiments"}),a.jsx("h2",{className:"text-xl font-semibold text-[var(--ui-ink-strong)]",children:"N-of-1 lab"})]})]}),a.jsxs("div",{className:"grid gap-3",children:[e.slice(0,4).map((t,s)=>a.jsxs(E,{children:[a.jsx("div",{className:"text-sm font-medium text-[var(--ui-ink-strong)]",children:ne(t.title)??"Nutrition experiment"}),a.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:ne(t.hypothesis)??ne(t.intervention)??"No hypothesis recorded."})]},String(t.id??s))),e.length===0?a.jsx(Ie,{children:"Start experiments from OpenClaw or the API: caffeine timing, fiber ramp, low-FODMAP trial, carb timing, sodium/puffiness, or pre-training fueling."}):null]})]})}function ct({view:e}){const t=e.dataQuality,s=e.todayLedger;return a.jsxs(O,{className:"grid gap-4 border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-5",children:[a.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",children:"Data quality"}),a.jsx("h2",{className:"mt-1 text-xl font-semibold text-[var(--ui-ink-strong)]",children:"Confidence, coverage, and next evidence"})]}),a.jsxs(L,{tone:"meta",children:[e.summary.dataQualityScore.toFixed(0),"% coverage"]})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[a.jsx(dt,{label:"Source confidence",value:t.sourceConfidence,children:"Food parsing stays candidate-based until accepted; wearable burn is treated as a trend input."}),a.jsxs(E,{children:[a.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:"Missing check-ins"}),a.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:t.missingHighValueCheckins.length>0?t.missingHighValueCheckins.map(r=>a.jsx(L,{tone:"signal",children:r},r)):a.jsx("span",{className:"text-sm text-[var(--ui-ink-soft)]",children:"Core evidence loop is covered."})})]}),a.jsxs(E,{children:[a.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:"Next best cue"}),a.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:t.notes}),a.jsxs("div",{className:"mt-3 text-xs text-[var(--ui-ink-faint)]",children:[s.unconfirmedCount," unconfirmed candidate",s.unconfirmedCount===1?"":"s"]})]})]})]})}function dt({label:e,value:t,children:s}){return a.jsxs(E,{children:[a.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:e}),a.jsx("div",{className:"mt-2 text-lg font-semibold text-[var(--ui-ink-strong)]",children:t}),a.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:s})]})}function q(e,t,s){return a.jsxs("li",{className:"grid gap-0.5",children:[a.jsx("span",{className:"font-medium text-[var(--ui-ink)]",children:e}),a.jsx("code",{className:"rounded-[6px] bg-[var(--ui-surface-2)] px-1.5 py-0.5 font-mono text-[11px] text-[var(--ui-ink-soft)]",children:t}),s?a.jsx("span",{className:"text-xs text-[var(--ui-ink-faint)]",children:s}):null]})}function ta({values:e,label:t="Show calorie and macro formulas"}){const r=((e==null?void 0:e.sex)??"male")==="male"?"+ 5":"- 161",n=(e==null?void 0:e.proteinFactor)!=null?`${e.proteinFactor.toFixed(1)}g/kg`:"1.6-2.0g/kg";return a.jsx(ce,{label:t,title:"Weight Loss Formulas",maxWidthPx:520,panelClassName:"text-xs leading-5",content:a.jsxs("div",{className:"grid gap-3",children:[a.jsx("p",{children:"Forge keeps activity independent from the goal. The goal only adds a deficit, surplus, or zero adjustment to resting plus active calories."}),a.jsxs("ol",{className:"grid gap-2",children:[q("Mifflin-St Jeor BMR",`10 x weight kg + 6.25 x height cm - 5 x age ${r}`,`Current formula value: ${m(e==null?void 0:e.bmrKcal)} kcal/day.`),q("Resting calories","HealthKit basal/resting kcal when present, otherwise BMR",`Using: ${m(e==null?void 0:e.restingKcal)} kcal/day${e!=null&&e.restingSource?` (${e.restingSource})`:""}.`),q("Maintenance calories","resting calories + active calories",`${m(e==null?void 0:e.restingKcal)} + ${m(e==null?void 0:e.activeKcal)} = ${m(e==null?void 0:e.maintenanceKcal)} kcal/day.`),q("Objective adjustment","weekly change kg x 7700 kcal/kg / 7",`Weekly rate ${fe(e==null?void 0:e.weeklyRateKg,2)} kg/week gives ${fe(e==null?void 0:e.dailyAdjustmentKcal)} kcal/day.`),q("Daily calorie target","max(sex floor, maintenance + objective adjustment)",`Floor ${m(e==null?void 0:e.calorieFloor)} kcal; target ${m(e==null?void 0:e.calorieTarget)} kcal/day.`),q("Protein target",`min(reference weight x ${n}, 45% of kcal / 4)`,`Reference ${m(e==null?void 0:e.proteinReferenceWeightKg,1)} kg; target ${m(e==null?void 0:e.proteinGrams)} g/day.`),q("Fat target","saved plan fat when present; otherwise min(remaining kcal after protein, 35% kcal / 9, max(0.6g/kg reference, 25% kcal / 9))",`Target ${m(e==null?void 0:e.fatGrams)} g/day.`),q("Carbohydrate target","(calorie target - protein g x 4 - fat g x 9) / 4",`Target ${m(e==null?void 0:e.carbohydrateGrams)} g/day. The 130g DRI is shown as reference, not forced if it breaks calories.`),q("Fiber target","14g per 1000 kcal; adult sex/age AI shown as reference",`Target ${m(e==null?void 0:e.fiberGrams)} g/day; energy-adjusted ${m(e==null?void 0:e.fiberEnergyAdjustedGrams)} g/day; adult AI reference ${m(e==null?void 0:e.fiberDriGrams)} g/day.`),q("Sport-loss estimate","training hours ~= active kcal / 500; sweat ~= 0.4-0.8 L/h; sodium ~= 500-1000 mg/L","Shown as expected loss ranges, not rigid supplement instructions.")]})]})})}function sa(e,t){var r;if(!e)return null;const s=e.match(new RegExp(`${t}=([^;]+)`));return((r=s==null?void 0:s[1])==null?void 0:r.trim())??null}function le(e,t){const s=typeof e=="string"?Number(e):_(e);return typeof s=="number"&&Number.isFinite(s)?s:t}function ut(e){return sa(e.target.notes,"sex")==="female"?"female":"male"}function gt(e){return le(sa(e.target.notes,"age_years"),35)}function h(e,t,s,r,n,c){return{id:e,label:t,target:typeof s=="number"?Ke(s):s,unit:r,note:n,source:c}}function Ke(e){return Number.isFinite(e)?Math.abs(e)>=100?e.toFixed(0):e.toFixed(1).replace(/\.0$/,""):"n/a"}function re(e,t){return`${Ke(e)}-${Ke(t)}`}function mt(e,t,s,r){const n=Math.round(s/1e3*14);return r>0?r:n}function ht({calorieTarget:e,currentWeightKg:t,protein:s,savedFat:r}){const n=Math.max(0,(e-s*4)/9),c=Math.max(0,Math.min(n,e*.35/9,Math.max(t*.6,e*.25/9))),g=r??c;return{carbs:Math.max(0,(e-s*4-g*9)/4),fat:g}}function pt(e,t){return e==="male"?t>=51?14:17:t>=51?11:12}function xt(e,t){const s=t>70,r=t>=51;return[h("vitamin_a","Vitamin A",e==="male"?900:700,"ug RAE","Retinol activity equivalent target.","NASEM DRI"),h("vitamin_c","Vitamin C",e==="male"?90:75,"mg","Adult RDA.","NASEM DRI"),h("vitamin_d","Vitamin D",s?20:15,"ug","Assumes limited sun exposure; older adults need more.","NASEM DRI"),h("vitamin_e","Vitamin E",15,"mg alpha-tocopherol","Adult RDA.","NASEM DRI"),h("vitamin_k","Vitamin K",e==="male"?120:90,"ug","Adult AI.","NASEM DRI"),h("thiamin_b1","Thiamin B1",e==="male"?1.2:1.1,"mg","Adult RDA.","NASEM DRI"),h("riboflavin_b2","Riboflavin B2",e==="male"?1.3:1.1,"mg","Adult RDA.","NASEM DRI"),h("niacin_b3","Niacin B3",e==="male"?16:14,"mg NE","Adult RDA.","NASEM DRI"),h("vitamin_b6","Vitamin B6",r?e==="male"?1.7:1.5:1.3,"mg","RDA rises after 50.","NASEM DRI"),h("folate","Folate",400,"ug DFE","Adult RDA.","NASEM DRI"),h("vitamin_b12","Vitamin B12",2.4,"ug","Adult RDA.","NASEM DRI"),h("pantothenic_acid","Pantothenic acid",5,"mg","Adult AI.","NASEM DRI"),h("biotin","Biotin",30,"ug","Adult AI.","NASEM DRI"),h("choline","Choline",e==="male"?550:425,"mg","Adult AI.","NASEM DRI")]}function ft(e,t){const s=t>70||e==="female"&&t>=51?1200:1e3,r=e==="male"?t>=31?420:400:t>=31?320:310,n=e==="male"?t>=51?30:35:t>=51?20:25,c=t>=71?1800:t>=51?2e3:2300;return[h("calcium","Calcium",s,"mg","Bone and muscle target; higher for older adults and women 51+.","NASEM DRI"),h("iron","Iron",e==="female"&&t<=50?18:8,"mg","Menstruating-age female target is higher.","NASEM DRI"),h("magnesium","Magnesium",r,"mg","Adult RDA.","NASEM DRI"),h("phosphorus","Phosphorus",700,"mg","Adult RDA.","NASEM DRI"),h("zinc","Zinc",e==="male"?11:8,"mg","Adult RDA.","NASEM DRI"),h("iodine","Iodine",150,"ug","Adult RDA.","NASEM DRI"),h("selenium","Selenium",55,"ug","Adult RDA.","NASEM DRI"),h("copper","Copper",.9,"mg","Adult RDA.","NASEM DRI"),h("manganese","Manganese",e==="male"?2.3:1.8,"mg","Adult AI.","NASEM DRI"),h("chromium","Chromium",n,"ug","Adult AI.","NASEM DRI"),h("molybdenum","Molybdenum",45,"ug","Adult RDA.","NASEM DRI"),h("fluoride","Fluoride",e==="male"?4:3,"mg","Adult AI.","NASEM DRI"),h("chloride","Chloride",c,"mg","Adult AI.","NASEM DRI"),h("potassium","Potassium",e==="male"?3400:2600,"mg","Current adult AI for non-pregnant adults.","NASEM DRI"),h("sodium_limit","Sodium ceiling",2300,"mg max","Default daily ceiling unless medically individualized.","U.S. Dietary Guidelines")]}function bt(e){const t=ut(e),s=gt(e),r=le(e.weightTrend.latestWeightKg,80),n=Math.max(1,le(e.target.calorieTarget,2200)),c=le(e.target.proteinGramsTarget,r*1.8),{carbs:g,fat:o}=ht({calorieTarget:n,currentWeightKg:r,protein:c,savedFat:_(e.target.fatGramsTarget)}),i=mt(t,s,n,le(e.target.fiberGramsTarget,0)),l=_(e.energyModel.activeBurnKcal)??_(e.energyModel.activeEnergyCalories)??null,w=_(e.energyModel.movementCaloriesKcal),x=_(e.energyModel.restingEnergyCalories);return ra({sex:t,ageYears:s,currentWeightKg:r,calorieTarget:n,proteinGramsTarget:c,carbohydrateGramsTarget:g,fatGramsTarget:o,fiberGramsTarget:i,activeBurnKcal:l,movementCaloriesKcal:w,restingEnergyKcal:x})}function ra(e){const{sex:t,ageYears:s,currentWeightKg:r,calorieTarget:n,proteinGramsTarget:c,carbohydrateGramsTarget:g,fatGramsTarget:o,fiberGramsTarget:i,activeBurnKcal:l,movementCaloriesKcal:w,restingEnergyKcal:x}=e,b=l!=null?Math.min(4,Math.max(.1,l/500)):null,d=b!=null?b*.4:null,I=b!=null?b*.8:null,S=d!=null?d*500:null,G=I!=null?I*1e3:null,A=d!=null?d*78:null,$=I!=null?I*312:null,D=l!=null?l*7/7700:null;return{profile:{sex:t,ageYears:s,currentWeightKg:r,calorieTarget:n,activeBurnKcal:l,movementCaloriesKcal:w,restingEnergyKcal:x},macros:[h("calories","Calories",n,"kcal","Plan target from BMR, active burn, and chosen weekly rate.","Forge plan"),h("protein","Protein",c,"g","Higher than the population RDA to preserve lean mass during weight change.","ISSN + Forge plan"),h("carbohydrate","Carbohydrate",g,"g","Remaining fuel after protein and fat. It may sit below the 130g/day adult DRI reference when needed to preserve the calorie target.","NASEM DRI + Forge plan"),h("fat","Total fat",o,"g","Uses the saved plan fat target when present; generated defaults aim for a practical floor around 0.6g/kg or 20-35% of calories when possible.","NASEM AMDR + Forge plan"),h("fiber","Fiber",i,"g","Uses 14g per 1000 kcal as the plan target; the sex/age adult AI remains a reference or stretch value when calories are low.","NASEM DRI"),h("saturated_fat","Saturated fat",n*.1/9,"g max","Keep below 10% of energy.","U.S. Dietary Guidelines"),h("added_sugar","Added sugar",n*.1/4,"g max","Keep below 10% of energy; lower is better when feasible.","U.S. Dietary Guidelines"),h("linoleic_acid","Linoleic acid",pt(t,s),"g","Essential n-6 fatty acid AI.","NASEM DRI"),h("ala","ALA omega-3",t==="male"?1.6:1.1,"g","Essential n-3 fatty acid AI.","NASEM DRI"),h("water","Total water",t==="male"?3.7:2.7,"L","All beverages and food water before extra training replacement.","NASEM DRI")],vitamins:xt(t,s),minerals:ft(t,s),sportLosses:[h("training_time","Estimated training time",b??"n/a","h/day","Derived from active burn at roughly 500 kcal/h.","Forge sport-loss model"),h("sweat_fluid","Expected sweat fluid",d!=null&&I!=null?re(d,I):"n/a","L/day","Planning range uses 0.4-0.8 L/h; measure body mass change to calibrate.","ACSM"),h("sweat_sodium","Expected sweat sodium",S!=null&&G!=null?re(S,G):"n/a","mg/day","Sodium varies widely; this uses a conservative range around common sweat sodium values.","ACSM + Sports Medicine review"),h("sweat_potassium","Expected sweat potassium",A!=null&&$!=null?re(A,$):"n/a","mg/day","Potassium is usually much smaller than sodium but useful for long/hot sessions.","Sports Medicine review"),h("gross_sport_equivalent","Gross sport burn equivalent",D??"n/a","kg/week","Energy equivalent if the active burn were not eaten back; the plan may already include it.","7700 kcal/kg model")],sportSummary:{trainingHours:b,fluidLossLiters:d!=null&&I!=null?re(d,I):"n/a",sodiumLossMg:S!=null&&G!=null?re(S,G):"n/a",potassiumLossMg:A!=null&&$!=null?re(A,$):"n/a",grossSportWeightEquivalentKgPerWeek:D}}}function Fe({rows:e,compact:t=!1}){return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"grid gap-2 md:hidden",children:e.map(s=>a.jsxs("div",{className:"grid min-w-0 gap-2 rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-3",children:[a.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[a.jsx("div",{className:"min-w-0 break-words text-sm font-semibold text-[var(--ui-ink)]",children:s.label}),a.jsxs("div",{className:"shrink-0 text-right text-sm font-semibold text-[var(--ui-ink)]",children:[s.target,a.jsx("div",{className:"text-xs font-normal text-[var(--ui-ink-faint)]",children:s.unit})]})]}),a.jsx("p",{className:"min-w-0 break-words text-xs leading-5 text-[var(--ui-ink-muted)]",children:s.note}),t?null:a.jsx(L,{tone:"meta",wrap:!0,className:"justify-self-start",children:s.source})]},s.id))}),a.jsx("div",{className:"hidden overflow-hidden rounded-[20px] border border-[var(--ui-border-subtle)] md:block",children:a.jsx("div",{className:"max-h-[460px] overflow-auto",children:a.jsxs("table",{className:"w-full min-w-[620px] border-collapse text-left text-sm",children:[a.jsx("thead",{className:"sticky top-0 bg-[var(--ui-surface-2)] text-xs uppercase text-[var(--ui-ink-faint)]",children:a.jsxs("tr",{children:[a.jsx("th",{className:"px-4 py-3 font-semibold",children:"Target"}),a.jsx("th",{className:"px-4 py-3 font-semibold",children:"Amount"}),a.jsx("th",{className:"px-4 py-3 font-semibold",children:"Rationale"}),t?null:a.jsx("th",{className:"px-4 py-3 font-semibold",children:"Source"})]})}),a.jsx("tbody",{className:"divide-y divide-[var(--ui-border-subtle)]",children:e.map(s=>a.jsxs("tr",{className:"bg-[var(--ui-surface-1)]",children:[a.jsx("td",{className:"px-4 py-3 font-medium text-[var(--ui-ink)]",children:s.label}),a.jsxs("td",{className:"px-4 py-3 text-[var(--ui-ink)]",children:[a.jsx("span",{className:"font-semibold",children:s.target})," ",a.jsx("span",{className:"text-[var(--ui-ink-faint)]",children:s.unit})]}),a.jsx("td",{className:"px-4 py-3 text-[var(--ui-ink-muted)]",children:s.note}),t?null:a.jsx("td",{className:"px-4 py-3",children:a.jsx(L,{tone:"meta",children:s.source})})]},s.id))})]})})})]})}function oe({title:e,description:t,children:s}){return a.jsxs(E,{children:[a.jsxs("div",{className:"mb-4",children:[a.jsx("h3",{className:"text-sm font-semibold text-[var(--ui-ink)]",children:e}),a.jsx("p",{className:"mt-1 text-sm text-[var(--ui-ink-muted)]",children:t})]}),s]})}function vt({view:e}){const t=bt(e),s=e.target.weeklyRateGoalKg??null,r=s!=null&&Number.isFinite(s)?s*7700/7:null,n=t.profile.restingEnergyKcal,c=t.profile.activeBurnKcal,g=n!=null&&c!=null?n+c:null,o=e.target.bodyGoal??"maintain",i=o.includes("lose")?2:o.includes("gain")?1.8:1.6,l=d=>{var G;const I=(G=t.macros.find(A=>A.id===d))==null?void 0:G.target,S=Number(I);return Number.isFinite(S)?S:null},w=t.profile.sex==="male"?t.profile.ageYears>=51?30:38:t.profile.ageYears>=51?21:25,x=Math.round(t.profile.calorieTarget/1e3*14),b=t.sportSummary.grossSportWeightEquivalentKgPerWeek!=null?`${t.sportSummary.grossSportWeightEquivalentKgPerWeek.toFixed(2)} kg/week`:"n/a";return a.jsx("section",{className:"grid gap-4",children:a.jsxs(O,{className:"p-5",children:[a.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-[var(--ui-ink)]",children:[a.jsx(Aa,{className:"size-4 text-[var(--ui-accent)]"}),"Macro And Micronutrient Targets",a.jsx(ta,{values:{sex:t.profile.sex,ageYears:t.profile.ageYears,currentWeightKg:t.profile.currentWeightKg,bmrKcal:null,restingKcal:n,restingSource:n!=null?"saved HealthKit basal/resting or plan value":null,activeKcal:c,maintenanceKcal:g,weeklyRateKg:s,dailyAdjustmentKcal:r,calorieTarget:t.profile.calorieTarget,calorieFloor:t.profile.sex==="male"?1500:1200,proteinReferenceWeightKg:null,proteinFactor:i,proteinGrams:l("protein"),fatGrams:l("fat"),carbohydrateGrams:l("carbohydrate"),fiberGrams:l("fiber"),fiberEnergyAdjustedGrams:x,fiberDriGrams:w}})]}),a.jsx("p",{className:"mt-1 max-w-3xl text-sm text-[var(--ui-ink-muted)]",children:"Daily targets use Forge plan values first, then adult DRI/Dietary Guidelines defaults for nutrients the food log can score as catalog detail improves."})]}),a.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.jsxs(L,{tone:"signal",children:[t.profile.calorieTarget.toFixed(0)," kcal"]}),a.jsxs(L,{tone:"meta",children:[t.profile.sex,", ",t.profile.ageYears.toFixed(0),"y"]})]})]}),a.jsxs("div",{className:"mt-5 grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(320px,0.58fr)]",children:[a.jsxs("div",{className:"grid gap-4",children:[a.jsx(oe,{title:"All macro targets",description:"Calories, protein, carbs, fat, fiber, sugar ceiling, saturated fat ceiling, essential fats, and water.",children:a.jsx(Fe,{rows:t.macros,compact:!0})}),a.jsx(oe,{title:"Vitamins",description:"Adult daily vitamin targets from DRI values, adjusted for sex and age where the reference differs.",children:a.jsx(Fe,{rows:t.vitamins})})]}),a.jsxs("div",{className:"grid content-start gap-4",children:[a.jsxs(oe,{title:"Expected sport losses",description:"Planning range from active burn. Calibrate with pre/post workout weight when possible.",children:[a.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[a.jsx(k,{label:"Active burn",value:t.profile.activeBurnKcal!=null?`${t.profile.activeBurnKcal.toFixed(0)} kcal`:"n/a"}),a.jsx(k,{label:"Sport equivalent",value:b}),a.jsx(k,{label:"Sweat fluid",value:`${t.sportSummary.fluidLossLiters} L`}),a.jsx(k,{label:"Sodium loss",value:`${t.sportSummary.sodiumLossMg} mg`})]}),a.jsxs("div",{className:"mt-4 flex items-start gap-3 rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-3 text-sm text-[var(--ui-ink-muted)]",children:[a.jsx(ea,{className:"mt-0.5 size-4 shrink-0 text-[var(--ui-accent)]"}),a.jsx("span",{children:"Sport burn is shown as gross energy equivalent, not a promise of scale loss. The calorie plan may already include active burn, and replacement depends on appetite, heat, sodium loss, and actual intake."})]})]}),a.jsx(oe,{title:"Minerals & oligoelements",description:"Daily mineral and trace-element targets including sodium ceiling and potassium AI.",children:a.jsx(Fe,{rows:t.minerals,compact:!0})}),a.jsx(oe,{title:"Sport electrolyte model",description:"Use these as expected losses, not rigid supplement prescriptions.",children:a.jsx("div",{className:"grid gap-3",children:t.sportLosses.map(d=>a.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-3",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-[var(--ui-ink)]",children:[d.id==="sweat_fluid"?a.jsx(Ka,{className:"size-4 text-[var(--ui-accent)]"}):a.jsx(_a,{className:"size-4 text-[var(--ui-accent)]"}),d.label]}),a.jsx("p",{className:"mt-1 text-xs text-[var(--ui-ink-faint)]",children:d.note})]}),a.jsxs("div",{className:"shrink-0 text-right text-sm font-semibold text-[var(--ui-ink)]",children:[d.target,a.jsx("div",{className:"text-xs font-normal text-[var(--ui-ink-faint)]",children:d.unit})]})]},d.id))})})]})]})]})})}function ee(e,t){var r;if(!e)return null;const s=e.match(new RegExp(`${t}=([^;]+)`));return((r=s==null?void 0:s[1])==null?void 0:r.trim())??null}function ae(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>0?t:null}function na(e,t){if(t==="maintain")return 0;const s=t==="gain"?.0025:.005,r=t==="gain"?.1:.2,n=t==="gain"?.35:Math.max(.5,e*.01);return Math.min(n,Math.max(r,e*s))}function ia(e,t){return t==="gain"?e*1.03:t==="maintain"?e:e*.95}function oa(e){return e.toFixed(1)}function yt(e,t){return e==="male"?t>=51?30:38:t>=51?21:25}function Oe(e,t){const s=e/100;return s>0?t*s*s:null}function jt(e){const t=e.goalMode==="lose"&&e.goalWeightKg!=null?Math.min(e.currentWeightKg,e.goalWeightKg):e.currentWeightKg,s=Oe(e.heightCm,30),r=Oe(e.heightCm,25);if(s!=null&&r!=null&&e.currentWeightKg>s){const n=r+(e.currentWeightKg-r)*.25;return Math.min(t,n)}return t}function kt(e,t){const s=ae(e.currentWeightKg)??80;return{...e,goalMode:t,goalWeightKg:oa(ia(s,t)),weeklyRateKg:na(s,t).toFixed(2)}}function Se(e){const t=_(e.weightTrend.latestWeightKg),s=e.target,r=ee(s.notes,"sex"),n=ee(s.notes,"age_years"),c=ee(s.notes,"height_cm"),g=_(e.energyModel.activeBurnKcal)??_(e.energyModel.activeEnergyCalories)??_(e.energyModel.movementCaloriesKcal)??_(ee(s.notes,"activity_kcal"))??0,o=_(e.energyModel.restingEnergyCalories)??_(ee(s.notes,"resting_kcal"))??null,i=s.bodyGoal??"",l=i.includes("gain")?"gain":i.includes("maintain")?"maintain":"lose",w=s.weightGoalKg??s.goalBodyWeightKg??null,x=t??80;return{goalMode:l,sex:r==="female"?"female":"male",ageYears:ae(n)?String(n):"",heightCm:ae(c)?String(c):"",currentWeightKg:t?t.toFixed(1):"",goalWeightKg:w?String(w):oa(ia(x,l)),weeklyRateKg:s.weeklyRateGoalKg!==null&&s.weeklyRateGoalKg!==void 0?String(Math.abs(s.weeklyRateGoalKg)):na(x,l).toFixed(2),activeCaloriesKcal:g.toFixed(0),restingCaloriesKcal:o!=null?o.toFixed(0):"",dietStyle:s.dietStyle??""}}function Nt(e){const t=ae(ee(e.target.notes,"age_years"))!=null,s=ae(ee(e.target.notes,"height_cm"))!=null,r=_(e.weightTrend.latestWeightKg)!=null,n=typeof e.target.bodyGoal=="string"&&e.target.bodyGoal.trim().length>0&&e.target.calorieTarget>0&&e.target.proteinGramsTarget>0;return t&&s&&r&&n}function la(e){const t=Number(e.currentWeightKg)||80,s=Number(e.heightCm)||178,r=Number(e.ageYears)||35,n=ae(e.goalWeightKg),c=Math.max(0,Number(e.activeCaloriesKcal)||0),g=ae(e.restingCaloriesKcal),o=e.sex==="male"?5:-161,i=10*t+6.25*s-5*r+o,l=g??i,w=l+c,x=Math.abs(Number(e.weeklyRateKg)||0),b=e.goalMode==="lose"?-x:e.goalMode==="gain"?x:0,d=b*7700/7,I=e.sex==="male"?1500:1200,S=Math.round(w+d),G=Math.max(I,S),A=jt({currentWeightKg:t,goalWeightKg:n,heightCm:s,goalMode:e.goalMode}),$=e.goalMode==="lose"?2:e.goalMode==="gain"?1.8:1.6,D=Math.round(A*$),te=Math.floor(G*.45/4),R=Math.max(1,Math.min(D,te)),W=A*.6,U=G*.25/9,ie=Math.max(0,(G-R*4)/9),V=Math.max(0,Math.floor(Math.min(ie,G*.35/9,Math.max(W,U)))),se=Math.max(0,Math.floor((G-R*4-V*9)/4)),Y=Math.round(G/1e3*14),J=yt(e.sex,r),B=Y,Z=Math.round(G*.1/9),X=Math.round(G*.1/4);return{bmr:Math.round(i),restingCalories:Math.round(l),restingSource:g!=null?"HealthKit basal/resting":"Mifflin-St Jeor",activeCalories:Math.round(c),maintenanceCalories:Math.round(w),plannedCalorieTarget:S,minimumCalorieFloor:I,weeklyRateGoalKg:b,dailyEnergyAdjustment:Math.round(d),calorieTarget:G,proteinReferenceWeight:Math.round(A*10)/10,proteinGramsTarget:R,carbohydrateGramsTarget:se,fatGramsTarget:V,fiberGramsTarget:B,fiberEnergyAdjustedGrams:Y,fiberDriGrams:J,saturatedFatLimitGrams:Z,addedSugarLimitGrams:X}}function wt(e){const t=[],s=Number(e.ageYears),r=Number(e.heightCm),n=Number(e.currentWeightKg),c=Number(e.goalWeightKg),g=Number(e.weeklyRateKg),o=e.activeCaloriesKcal.trim()?Number(e.activeCaloriesKcal):Number.NaN,i=e.restingCaloriesKcal.trim()?Number(e.restingCaloriesKcal):null;return(!Number.isFinite(s)||s<13||s>100)&&t.push("- Enter the user's real age. Forge uses it in Mifflin-St Jeor resting metabolism."),(!Number.isFinite(r)||r<120||r>230)&&t.push("- Enter height in cm. Height changes BMR and protein reference weight."),(!Number.isFinite(n)||n<30||n>300)&&t.push("- Enter current weight in kg. Use the latest known body measure as the starting state."),e.goalMode!=="maintain"&&(!Number.isFinite(c)||c<30||c>300)&&t.push("- Enter a target weight for the selected loss or gain objective."),(!Number.isFinite(g)||g<0)&&t.push("- Enter a non-negative weekly change rate in kg/week."),Number.isFinite(g)&&g>Math.max(1.5,n*.02)&&t.push("- The weekly rate is very aggressive. Choose a slower default unless this is a supervised plan."),(!Number.isFinite(o)||o<0||o>3e3)&&t.push("- Enter average active calories per day. Zero is valid only when Forge has no activity evidence."),i!=null&&(!Number.isFinite(i)||i<900||i>3500)&&t.push("- Resting calories should be blank for formula mode or a plausible HealthKit basal/resting value."),t.length>0?t.join(`
2
- `):null}function Ct(e){const t=la(e),s=Number(e.goalWeightKg);return{calorieTarget:t.calorieTarget,proteinGramsTarget:t.proteinGramsTarget,fiberGramsTarget:t.fiberGramsTarget,carbohydrateGramsTarget:t.carbohydrateGramsTarget,fatGramsTarget:t.fatGramsTarget,weightGoalKg:Number.isFinite(s)?s:null,weeklyRateGoalKg:t.weeklyRateGoalKg,dietStyle:e.dietStyle,bodyGoal:e.goalMode,notes:["Forge science plan",`height_cm=${Number(e.heightCm)||"unknown"}`,`age_years=${Number(e.ageYears)||"unknown"}`,`sex=${e.sex}`,"bmr_formula=Mifflin-St Jeor",`resting_kcal=${t.restingCalories}`,`activity_kcal=${t.activeCalories}`,`maintenance_kcal=${t.maintenanceCalories}`,"rate_model=7700 kcal/kg"].join("; ")}}function Mt({open:e,onOpenChange:t,view:s,value:r,onChange:n,onSubmit:c,pending:g,error:o}){const i=M.useMemo(()=>la(r),[r]),l=M.useMemo(()=>ra({sex:r.sex,ageYears:Number(r.ageYears)||35,currentWeightKg:Number(r.currentWeightKg)||80,calorieTarget:i.calorieTarget,proteinGramsTarget:i.proteinGramsTarget,carbohydrateGramsTarget:i.carbohydrateGramsTarget,fatGramsTarget:i.fatGramsTarget,fiberGramsTarget:i.fiberGramsTarget,activeBurnKcal:i.activeCalories,movementCaloriesKcal:_(s.energyModel.movementCaloriesKcal),restingEnergyKcal:i.restingCalories}),[i,r,s.energyModel.movementCaloriesKcal]),w=[{id:"profile",eyebrow:"Current state",title:"Confirm the body data Forge knows",description:"These fields drive resting metabolism. Saved values are reused when Forge has them.",render:(x,b)=>a.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[a.jsx(v,{label:"Sex",children:a.jsx(qe,{value:x.sex,onChange:d=>b({sex:d}),options:[{value:"male",label:"Male"},{value:"female",label:"Female"}]})}),a.jsx(v,{label:"Age",children:a.jsx(j,{inputMode:"numeric",value:x.ageYears,onChange:d=>b({ageYears:d.target.value}),placeholder:"35"})}),a.jsx(v,{label:"Height cm",children:a.jsx(j,{inputMode:"decimal",value:x.heightCm,onChange:d=>b({heightCm:d.target.value}),placeholder:"178"})}),a.jsx(v,{label:"Current weight kg",children:a.jsx(j,{inputMode:"decimal",value:x.currentWeightKg,onChange:d=>b({currentWeightKg:d.target.value}),placeholder:"80.0"})})]})},{id:"objective",eyebrow:"Goal",title:"Choose what should happen next",description:"Forge proposes a default target and weekly rate from current weight; you can change both.",render:(x,b)=>a.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[a.jsx("div",{className:"md:col-span-2",children:a.jsx(qe,{columns:3,value:x.goalMode,onChange:d=>b(kt(x,d)),options:[{value:"lose",label:"Lose fat",description:"Default: about 0.5% body weight per week."},{value:"gain",label:"Gain mass",description:"Default: small surplus around 0.25% per week."},{value:"maintain",label:"Maintain",description:"Hold weight while optimizing signals."}]})}),a.jsx(v,{label:"Target weight kg",hint:"Filled from the objective; change it anytime.",children:a.jsx(j,{inputMode:"decimal",value:x.goalWeightKg,onChange:d=>b({goalWeightKg:d.target.value}),placeholder:"75.0"})}),a.jsx(v,{label:"Weekly change kg",hint:"Loss/gain rate is converted to kcal/day with the 7700 kcal/kg planning model.",children:a.jsx(j,{inputMode:"decimal",value:x.weeklyRateKg,onChange:d=>b({weeklyRateKg:d.target.value}),placeholder:"0.35"})})]})},{id:"activity",eyebrow:"Activity",title:"Add active burn to resting burn",description:"Active calories are independent evidence from HealthKit, workouts, and movement. The objective only changes the deficit or surplus.",render:(x,b)=>a.jsxs("div",{className:"grid gap-4",children:[a.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[a.jsx(v,{label:"Resting calories/day",hint:`Forge uses HealthKit basal energy when present, otherwise Mifflin-St Jeor BMR. Current formula value: ${i.bmr} kcal.`,children:a.jsx(j,{inputMode:"decimal",value:x.restingCaloriesKcal,onChange:d=>b({restingCaloriesKcal:d.target.value}),placeholder:String(i.bmr)})}),a.jsx(v,{label:"Average active calories/day",hint:`This is the default active allowance used when today has no same-day workout or active-energy evidence. Forge currently sees ${m(s.energyModel.movementCaloriesKcal)} movement kcal, ${m(s.energyModel.activeBurnKcal)} average active burn, and ${m(s.energyModel.todayWorkoutEnergyKcal)} workout kcal today.`,children:a.jsx(j,{inputMode:"decimal",value:x.activeCaloriesKcal,onChange:d=>b({activeCaloriesKcal:d.target.value}),placeholder:"350"})})]}),a.jsxs("div",{className:"grid gap-3 rounded-[24px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-4 md:grid-cols-3",children:[a.jsx(k,{label:i.restingSource,value:`${i.restingCalories} kcal`}),a.jsx(k,{label:"Maintenance",value:`${i.maintenanceCalories} kcal`}),a.jsx(k,{label:"Daily adjustment",value:`${i.dailyEnergyAdjustment>0?"+":""}${i.dailyEnergyAdjustment} kcal`})]})]})},{id:"macros",eyebrow:"Macros",title:"Validate calories, macros, and limits",description:"Target intake equals resting burn plus active burn plus the objective adjustment. Macros are generated from protein-per-kg, a practical fat floor, remaining carbohydrates, fiber density, and dietary limits.",render:(x,b)=>a.jsxs("div",{className:"grid gap-4",children:[a.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-[20px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] px-4 py-3",children:[a.jsx("div",{className:"min-w-0 text-sm leading-6 text-[var(--ui-ink-muted)]",children:"Inspect the exact math behind the current calories, macro targets, and sport-loss preview."}),a.jsx(ta,{values:{sex:x.sex,ageYears:Number(x.ageYears)||null,currentWeightKg:Number(x.currentWeightKg)||null,heightCm:Number(x.heightCm)||null,bmrKcal:i.bmr,restingKcal:i.restingCalories,restingSource:i.restingSource,activeKcal:i.activeCalories,maintenanceKcal:i.maintenanceCalories,weeklyRateKg:i.weeklyRateGoalKg,dailyAdjustmentKcal:i.dailyEnergyAdjustment,calorieTarget:i.calorieTarget,calorieFloor:i.minimumCalorieFloor,proteinReferenceWeightKg:i.proteinReferenceWeight,proteinFactor:x.goalMode==="lose"?2:x.goalMode==="gain"?1.8:1.6,proteinGrams:i.proteinGramsTarget,fatGrams:i.fatGramsTarget,carbohydrateGrams:i.carbohydrateGramsTarget,fiberGrams:i.fiberGramsTarget,fiberEnergyAdjustedGrams:i.fiberEnergyAdjustedGrams,fiberDriGrams:i.fiberDriGrams}})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-4 xl:grid-cols-7",children:[a.jsx(k,{label:"Calories",value:`${i.calorieTarget}`}),a.jsx(k,{label:"Protein",value:`${i.proteinGramsTarget}g`}),a.jsx(k,{label:"Carbs",value:`${i.carbohydrateGramsTarget}g`}),a.jsx(k,{label:"Fat",value:`${i.fatGramsTarget}g`}),a.jsx(k,{label:"Fiber",value:`${i.fiberGramsTarget}g`}),a.jsx(k,{label:"Sat fat max",value:`${i.saturatedFatLimitGrams}g`}),a.jsx(k,{label:"Added sugar max",value:`${i.addedSugarLimitGrams}g`})]}),a.jsxs("div",{className:"grid gap-4 rounded-[24px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-4",children:[a.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-sm font-semibold text-[var(--ui-ink)]",children:"Micronutrient and sport-loss preview"}),a.jsx("div",{className:"mt-1 text-sm leading-6 text-[var(--ui-ink-muted)]",children:"The dashboard will track vitamin, mineral, trace-element, water, sodium-ceiling, essential-fat, and sport-loss targets from this plan."})]}),a.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.jsxs(L,{tone:"meta",children:[l.vitamins.length," vitamins"]}),a.jsxs(L,{tone:"meta",children:[l.minerals.length," minerals"]}),a.jsxs(L,{tone:"signal",children:[l.sportSummary.fluidLossLiters," L sweat"]})]})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[a.jsx(k,{label:"Sport sodium loss",value:`${l.sportSummary.sodiumLossMg} mg`}),a.jsx(k,{label:"Sport potassium loss",value:`${l.sportSummary.potassiumLossMg} mg`}),a.jsx(k,{label:"Water baseline",value:r.sex==="male"?"3.7 L":"2.7 L"}),a.jsx(k,{label:"Essential fats",value:r.sex==="male"?"17g LA / 1.6g ALA":"12g LA / 1.1g ALA"})]})]}),a.jsx(v,{label:"Diet style or constraints",children:a.jsx(xe,{value:x.dietStyle,onChange:d=>b({dietStyle:d.target.value}),placeholder:"Mediterranean, high protein, no lactose, low FODMAP trial..."})})]})}];return a.jsx(ve,{open:e,onOpenChange:t,eyebrow:"Weight plan",title:"Set weight objective",description:"Build an editable calorie and macro plan.",value:r,onChange:n,steps:w,onSubmit:c,submitLabel:"Save plan",pending:g,pendingLabel:"Saving plan",error:o,draftPersistenceKey:"weight-loss-plan"})}const Gt={tsp:5,tbsp:15,cup:240};function pe(){return{mealLabel:"Meal",notes:"",source:"search",selectedItems:[]}}function F(e,t,s){return typeof e!="number"||!Number.isFinite(e)?null:da(s)==="grams"?e:t>0?Math.round(e/t*10)/10:e}function Ft(e){const t=Number.isFinite(e.quantity)&&e.quantity>0?e.quantity:1,s=e.unit??"serving",r=s==="grams"?e.grams??t:e.grams!=null&&t>0?e.grams/t:e.grams;return{id:e.foodId??e.id,source:"saved_meal",sourceId:e.foodId??e.id,name:e.name,brand:e.brand??null,barcode:null,servingLabel:s,servingGrams:r??null,calories:F(e.calories,t,s),proteinGrams:F(e.proteinGrams,t,s),carbohydrateGrams:F(e.carbohydrateGrams,t,s),fatGrams:F(e.fatGrams,t,s),fiberGrams:F(e.fiberGrams,t,s),sugarGrams:F(e.sugarGrams,t,s),sodiumMg:F(e.sodiumMg,t,s),potassiumMg:F(e.potassiumMg,t,s),caffeineMg:F(e.caffeineMg,t,s),alcoholGrams:F(e.alcoholGrams,t,s),glycemicIndex:e.glycemicIndex??null,novaGroup:e.novaGroup??null,tags:e.tags??[],confidence:e.confidence??null}}function St(e,t,s){const r=Number.isFinite(e.quantity)&&e.quantity>0?e.quantity:1,n=e.unit??"serving",c=n==="grams"||n==="g"?e.grams??r:e.grams!=null&&r>0?e.grams/r:e.grams;return{id:e.foodId??`${s}_${t}_${Date.now()}`,source:s,sourceId:e.foodId??null,name:e.name,brand:e.brand??null,barcode:null,servingLabel:n,servingGrams:c??null,calories:F(e.calories,r,n),proteinGrams:F(e.proteinGrams,r,n),carbohydrateGrams:F(e.carbohydrateGrams,r,n),fatGrams:F(e.fatGrams,r,n),fiberGrams:F(e.fiberGrams,r,n),sugarGrams:F(e.sugarGrams,r,n),sodiumMg:F(e.sodiumMg,r,n),potassiumMg:F(e.potassiumMg,r,n),caffeineMg:F(e.caffeineMg,r,n),alcoholGrams:F(e.alcoholGrams,r,n),glycemicIndex:e.glycemicIndex??null,novaGroup:e.novaGroup??null,tags:e.tags??[],confidence:e.confidence??null}}function At(e){if(!e)return null;const s=e.toLowerCase().replace(",",".").match(/(\d+(?:\.\d+)?)\s*(kg|g|gram|grams|ml|l)\b/);if(!s)return null;const r=Number(s[1]);if(!Number.isFinite(r)||r<=0)return null;const n=s[2];return n==="kg"||n==="l"?r*1e3:r}function de(e){return typeof e.servingGrams=="number"&&Number.isFinite(e.servingGrams)&&e.servingGrams>0?e.servingGrams:At(e.servingLabel)}function Kt(e){const t=de(e);return t!=null?`${m(t)} g`:e.servingLabel??"serving"}function ca(e){const t=Number(e.amount)||0;if(t<=0)return null;const s=de(e.food);return e.unit==="grams"?t:e.unit==="tsp"||e.unit==="tbsp"||e.unit==="cup"?t*Gt[e.unit]:s!=null?t*s:null}function Ue(e){return!(e.unit==="grams"||e.unit==="tsp"||e.unit==="tbsp"||e.unit==="cup")||de(e.food)!=null?null:"Add base grams before using grams or household measures. Without a denominator, Forge will not guess a ratio."}function da(e){const t=e==null?void 0:e.trim().toLowerCase();return t==="g"||t==="gram"||t==="grams"?"grams":t==="tsp"||t==="teaspoon"?"tsp":t==="tbsp"||t==="tablespoon"?"tbsp":t==="cup"?"cup":t==="serving"||t==="servings"?"serving":"unit"}function _t(e){switch(e){case"manual":case"search":case"barcode":case"chatgpt":case"photo":case"saved_meal":return e;default:return"manual"}}function It(e){return{mealLabel:e.mealLabel??"Meal",notes:e.notes??"",source:_t(e.source),selectedItems:e.items.map(t=>({localId:t.id,food:Ft(t),amount:String(t.quantity||1),unit:t.unit??"serving"}))}}function Tt(e,t=e.source??"manual"){return{mealLabel:e.mealLabel??"Meal",notes:e.notes??"",source:e.source??"manual",selectedItems:e.items.map((s,r)=>({localId:`${t}-${r}-${Date.now()}`,food:St(s,r,t),amount:String(s.quantity||1),unit:da(s.unit)}))}}function ua(){return{id:`custom_food_${Date.now()}`,source:"manual",sourceId:null,name:"Custom food",brand:null,barcode:null,servingLabel:"100 g",servingGrams:100,calories:null,proteinGrams:null,carbohydrateGrams:null,fatGrams:null,fiberGrams:null,sugarGrams:null,sodiumMg:null,potassiumMg:null,caffeineMg:null,alcoholGrams:null,glycemicIndex:null,novaGroup:null,tags:["custom"],confidence:1}}function Lt(){return{mealLabel:"Meal",notes:"",source:"manual",selectedItems:[{localId:`custom-${Date.now()}`,food:ua(),amount:"100",unit:"grams"}]}}function Et({open:e,onOpenChange:t,value:s,onChange:r,foodResults:n,searchPending:c,chatGptPending:g=!1,chatGptError:o=null,logPending:i,onSearch:l,onParseWithChatGpt:w,onSubmit:x,mode:b="create",intent:d="search",initialStepId:I}){const[S,G]=M.useState(""),[A,$]=M.useState(""),[D,te]=M.useState(null),R=M.useMemo(()=>Bt(s.selectedItems),[s.selectedItems]),W=p=>r({...s,...p}),U=p=>{W({selectedItems:[...s.selectedItems,{localId:`${p.id}-${Date.now()}`,food:p,amount:"1",unit:"serving"}]}),te(null)},ie=()=>{U(ua())},V=async()=>{const p=A.trim();!p||!w||(await w(p),$(""))},se=(p,y)=>{W({selectedItems:s.selectedItems.map(C=>C.localId===p?{...C,...y}:C)})},Y=(p,y)=>{W({selectedItems:s.selectedItems.map(C=>C.localId===p?{...C,food:{...C.food,...y}}:C)})},J=p=>{W({selectedItems:s.selectedItems.filter(y=>y.localId!==p)})},B=async()=>{s.selectedItems.length!==0&&await x()},Z=a.jsxs(E,{className:"grid gap-3",children:[a.jsx(v,{label:"Ask ChatGPT",labelHelp:"Uses the connected OpenAI Codex OAuth / ChatGPT subscription model to create a reviewable candidate meal draft. It does not use the metered OpenAI Platform API.",children:a.jsx(xe,{value:A,onChange:p=>$(p.target.value),placeholder:"Example: 2 eggs, 150g Greek yogurt, one banana, and a cappuccino..."})}),o?a.jsx("div",{className:"rounded-[18px] border border-[var(--ui-danger-soft)] bg-[var(--ui-danger-soft)] px-3 py-2 text-xs leading-5 text-[var(--ui-ink)]",children:o}):null,a.jsxs(K,{type:"button",variant:d==="chatgpt"?"primary":"secondary",pending:g,pendingLabel:"Parsing",disabled:!A.trim()||!w,onClick:()=>void V(),children:[a.jsx(Ye,{className:"size-4"}),"Parse with ChatGPT"]})]}),X=a.jsx(E,{className:"grid gap-3",children:a.jsxs("div",{className:"flex items-start justify-between gap-3",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsx("div",{className:"text-sm font-semibold text-[var(--ui-ink-strong)]",children:"Create custom food"}),a.jsx("div",{className:"mt-1 text-xs leading-5 text-[var(--ui-ink-soft)]",children:"Start from a blank food, then define base grams, calories, macros, sodium, and exact quantity in the next step."})]}),a.jsxs(K,{type:"button",size:"sm",onClick:ie,children:[a.jsx(_e,{className:"size-4"}),"Add custom"]})]})}),H=d==="chatgpt"?[Z,X]:[X,Z],T=[{id:"search",eyebrow:d==="chatgpt"?"ChatGPT food parser":"Food",title:d==="chatgpt"?"Describe the meal, then review every item":"Search, create, or ask ChatGPT",description:d==="chatgpt"?"ChatGPT creates a candidate meal through the subscription-backed connection; you still review quantities and nutrients before saving.":"Search the catalog, create a custom food, or use ChatGPT to turn rough meal text into editable items.",render:()=>a.jsxs("div",{className:"grid gap-4",children:[a.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_auto]",children:[a.jsx(v,{label:"Food search",labelHelp:"Search returns food candidates with per-serving nutrition. Click a result to inspect macros before adding it to the meal draft.",children:a.jsx(j,{value:S,onChange:p=>G(p.target.value),placeholder:"Search eggs, yogurt, sourdough..."})}),a.jsxs(K,{type:"button",variant:"secondary",pending:c,disabled:!S.trim(),onClick:()=>l(S),children:[a.jsx(Je,{className:"size-4"}),"Search"]})]}),a.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:H.map((p,y)=>a.jsx("div",{children:p},`${d}-assistant-panel-${y}`))}),D?a.jsx(Wt,{food:D,onAdd:()=>U(D)}):null,a.jsx("div",{className:"grid gap-3",children:n.map(p=>a.jsx(E,{interactive:!0,className:"p-0",children:a.jsx("button",{type:"button",className:"block w-full rounded-[22px] p-4 text-left",onClick:()=>te(p),children:a.jsxs("div",{className:"flex items-start justify-between gap-3",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsx("div",{className:"truncate text-sm font-semibold text-[var(--ui-ink-strong)]",children:p.name}),a.jsx("div",{className:"mt-1 truncate text-xs text-[var(--ui-ink-faint)]",children:[p.brand,p.servingLabel,p.source].filter(Boolean).join(" · ")})]}),a.jsxs(L,{tone:"meta",children:[m(p.calories)," kcal"]})]})})},p.id))})]})},{id:"amounts",eyebrow:d==="custom"?"Custom food":"Quantity",title:d==="custom"?"Define the food and exact dose":"Set exactly how much you ate",description:"Scale by grams, servings, household measures, or units before saving the meal.",render:p=>a.jsxs("div",{className:"grid gap-4",children:[p.selectedItems.length===0?a.jsx("div",{className:"rounded-[22px] border border-dashed border-[var(--ui-border-strong)] bg-[var(--ui-surface-1)] p-5 text-sm text-[var(--ui-ink-soft)]",children:"Add at least one food from the search step."}):null,p.selectedItems.map(y=>a.jsxs(E,{className:"grid gap-3",children:[a.jsxs("div",{className:"flex items-start justify-between gap-3",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-sm font-semibold text-[var(--ui-ink-strong)]",children:y.food.name}),a.jsxs("div",{className:"text-xs text-[var(--ui-ink-faint)]",children:["Base: ",m(y.food.calories)," kcal per"," ",Kt(y.food)]})]}),a.jsxs(K,{type:"button",size:"sm",variant:"ghost",onClick:()=>J(y.localId),children:[a.jsx(Xe,{className:"size-4"}),"Remove"]})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto]",children:[a.jsx(v,{label:"Quantity",labelHelp:"This is the amount actually eaten. Forge converts the selected unit to an eaten gram equivalent when base grams are known, then scales every nutrient by eaten grams divided by base grams.",children:a.jsx(j,{inputMode:"decimal",value:y.amount,onChange:C=>se(y.localId,{amount:C.target.value}),placeholder:"1"})}),a.jsx(v,{label:"Unit",labelHelp:"Servings multiply the base serving. Grams, teaspoons, tablespoons, and cups use a gram conversion table and require base grams.",children:a.jsxs("select",{className:"interactive-tap w-full rounded-[22px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-3 text-[15px] text-[var(--ui-ink-strong)] outline-none",value:y.unit,onChange:C=>se(y.localId,{unit:C.target.value}),children:[a.jsx("option",{value:"serving",children:"serving"}),a.jsx("option",{value:"grams",children:"grams"}),a.jsx("option",{value:"unit",children:"unit"}),a.jsx("option",{value:"tsp",children:"teaspoon"}),a.jsx("option",{value:"tbsp",children:"tablespoon"}),a.jsx("option",{value:"cup",children:"cup"})]})}),a.jsxs(L,{tone:"signal",children:[m(be(y).calories)," kcal"]})]}),Ue(y)?a.jsx("div",{className:"rounded-[18px] border border-[var(--ui-warning-soft)] bg-[var(--ui-warning-soft)] px-3 py-2 text-xs leading-5 text-[var(--ui-ink)]",children:Ue(y)}):a.jsxs("div",{className:"text-xs text-[var(--ui-ink-faint)]",children:[m(Number(y.amount)||0)," ",y.unit," ="," ",m(ca(y))," g eaten; ratio ="," ",m(be(y).scale),"x the base nutrition."]}),a.jsx(Pt,{item:y,onChange:C=>Y(y.localId,C)})]},y.localId)),a.jsxs("div",{className:"grid gap-3 rounded-[24px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-4 md:grid-cols-4",children:[a.jsx(k,{label:"Calories",value:m(R.calories)}),a.jsx(k,{label:"Protein",value:`${m(R.proteinGrams)}g`}),a.jsx(k,{label:"Carbs",value:`${m(R.carbohydrateGrams)}g`}),a.jsx(k,{label:"Fat",value:`${m(R.fatGrams)}g`})]})]})},{id:"context",eyebrow:"Context",title:"Meal label and notes",description:"Add how it felt, where it happened, or anything relevant to future pattern detection.",render:(p,y)=>a.jsxs("div",{className:"grid gap-4",children:[a.jsx(v,{label:"Meal label",labelHelp:"The label groups the edited items as breakfast, lunch, snack, dinner, or any personal meal name.",children:a.jsx(j,{value:p.mealLabel,onChange:C=>y({mealLabel:C.target.value}),placeholder:"Breakfast"})}),a.jsx(v,{label:"Notes",labelHelp:"Use notes for context the numbers do not capture: hunger, cravings, gut comfort, energy, timing, place, or workout relationship.",children:a.jsx(xe,{value:p.notes,onChange:C=>y({notes:C.target.value}),placeholder:"Energy, cravings, gut comfort, training effect..."})})]})}];return a.jsx(ve,{open:e,onOpenChange:t,eyebrow:"Food log",title:b==="edit"?"Edit food":"Add food",description:"Search, inspect, scale, edit nutrition parameters, and save meal items.",value:s,onChange:r,steps:T,initialStepId:I,onSubmit:B,submitLabel:b==="edit"?"Update meal":"Save meal",pending:i,pendingLabel:"Saving meal",resolveError:p=>p!=="search"&&s.selectedItems.length===0?"Select at least one food before saving.":null,draftPersistenceKey:`weight-loss-food-log.${b}.${d}`})}function ga(e){return{mealLabel:Qe(e.mealLabel,"Meal"),source:e.source??"search",confirmationState:"confirmed",notes:Qe(e.notes),items:e.selectedItems.map(t=>{const s=be(t);return{foodId:$t(t),name:t.food.name,brand:t.food.brand,quantity:Number(t.amount)||1,unit:t.unit,grams:s.grams,calories:s.calories,proteinGrams:s.proteinGrams,carbohydrateGrams:s.carbohydrateGrams,fatGrams:s.fatGrams,fiberGrams:s.fiberGrams,sugarGrams:s.sugarGrams,sodiumMg:s.sodiumMg,potassiumMg:s.potassiumMg,caffeineMg:s.caffeineMg,alcoholGrams:s.alcoholGrams,novaGroup:t.food.novaGroup,tags:t.food.tags,confidence:.9}})}}function Qe(e,t=""){return typeof e=="string"?e:t}function $t(e){return e.food.source==="manual"||e.food.source==="chatgpt"||e.food.id.startsWith("custom_food_")||e.food.id.startsWith("chatgpt_")?null:e.food.id}function Dt(e){return ga(e)}function Rt(e){const t=Number(e);return Number.isFinite(t)?t:null}function Pt({item:e,onChange:t}){const s=e.food,r=(n,c)=>t({[n]:Rt(c)});return a.jsxs("div",{className:"grid gap-3 rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-[var(--ui-ink-strong)]",children:["Food parameters",a.jsx(ce,{label:`Explain editable food parameters for ${s.name}`,content:"These are the nutrient values for the base serving shown above. Changing them recalculates the eaten quantity and stores the corrected values in Forge."})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[a.jsx(v,{label:"Base label",labelHelp:"Human-readable denominator shown for the nutrition values, such as 100 g, 220 g, one burger, or one scoop.",children:a.jsx(j,{value:s.servingLabel??"",onChange:n=>t({servingLabel:n.target.value||null}),placeholder:"100 g"})}),a.jsx(v,{label:"Base grams",labelHelp:"Gram denominator for the base nutrition values. If kcal is per 220 g, enter 220. If kcal is per 100 g, enter 100.",children:a.jsx(j,{inputMode:"decimal",value:s.servingGrams??"",onChange:n=>r("servingGrams",n.target.value),placeholder:"100"})}),a.jsx(v,{label:"Food name",labelHelp:"Rename the item when the database result is too generic or wrong.",children:a.jsx(j,{value:s.name,onChange:n=>t({name:n.target.value})})}),a.jsx(v,{label:"Brand",labelHelp:"Optional brand or preparation source, useful when the same food has different nutrition.",children:a.jsx(j,{value:s.brand??"",onChange:n=>t({brand:n.target.value||null})})})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[a.jsx(v,{label:"kcal",labelHelp:"Kilocalories for the base amount above. Forge multiplies this by eaten grams divided by base grams, so 2 g of a 220 g base is not treated as 2 servings.",children:a.jsx(j,{inputMode:"decimal",value:s.calories??"",onChange:n=>r("calories",n.target.value)})}),a.jsx(v,{label:"Protein g",labelHelp:"Protein grams for the base amount above. This is scaled by the same gram ratio as calories.",children:a.jsx(j,{inputMode:"decimal",value:s.proteinGrams??"",onChange:n=>r("proteinGrams",n.target.value)})}),a.jsx(v,{label:"Carbs g",labelHelp:"Carbohydrate grams for the base amount above. Carbs are training fuel after protein and fat are allocated.",children:a.jsx(j,{inputMode:"decimal",value:s.carbohydrateGrams??"",onChange:n=>r("carbohydrateGrams",n.target.value)})}),a.jsx(v,{label:"Fat g",labelHelp:"Fat grams for the base amount above. Fat supports the practical floor and AMDR context in the plan.",children:a.jsx(j,{inputMode:"decimal",value:s.fatGrams??"",onChange:n=>r("fatGrams",n.target.value)})}),a.jsx(v,{label:"Fiber g",labelHelp:"Fiber grams for the base amount above. Forge compares this to the 14g per 1000 kcal planning target.",children:a.jsx(j,{inputMode:"decimal",value:s.fiberGrams??"",onChange:n=>r("fiberGrams",n.target.value)})}),a.jsx(v,{label:"Sugar g",labelHelp:"Sugar grams for the base amount above. Added sugar is tracked as a ceiling, not a goal.",children:a.jsx(j,{inputMode:"decimal",value:s.sugarGrams??"",onChange:n=>r("sugarGrams",n.target.value)})}),a.jsx(v,{label:"Sodium mg",labelHelp:"Sodium milligrams for the base amount above. Sodium affects daily ceiling, sport loss replacement, and water retention hypotheses.",children:a.jsx(j,{inputMode:"decimal",value:s.sodiumMg??"",onChange:n=>r("sodiumMg",n.target.value)})})]})]})}function Wt({food:e,onAdd:t}){return a.jsxs(O,{className:"grid gap-4 border-[var(--primary)]/20 bg-[var(--ui-accent-soft)] p-4",children:[a.jsxs("div",{className:"flex items-start justify-between gap-3",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-lg font-semibold text-[var(--ui-ink-strong)]",children:e.name}),a.jsx("div",{className:"mt-1 text-sm text-[var(--ui-ink-soft)]",children:[e.brand,e.servingLabel,e.source].filter(Boolean).join(" · ")})]}),a.jsxs(K,{type:"button",onClick:t,children:[a.jsx(_e,{className:"size-4"}),"Add"]})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[a.jsx(k,{label:"Calories",value:m(e.calories)}),a.jsx(k,{label:"Protein",value:`${m(e.proteinGrams)}g`}),a.jsx(k,{label:"Carbs",value:`${m(e.carbohydrateGrams)}g`}),a.jsx(k,{label:"Fat",value:`${m(e.fatGrams)}g`}),a.jsx(k,{label:"Fiber",value:`${m(e.fiberGrams)}g`}),a.jsx(k,{label:"Sugar",value:`${m(e.sugarGrams)}g`}),a.jsx(k,{label:"Sodium",value:`${m(e.sodiumMg)}mg`}),a.jsx(k,{label:"NOVA",value:e.novaGroup?String(e.novaGroup):"n/a"})]}),a.jsxs("div",{className:"flex items-center gap-2 text-xs text-[var(--ui-ink-soft)]",children:[a.jsx(Ia,{className:"size-4"}),"Base grams: ",m(de(e)),". Adjust exact intake in the next step."]})]})}function be(e){const t=Number(e.amount)||0,s=de(e.food),r=ca(e),n=e.unit==="serving"||e.unit==="unit",c=t<=0?0:s!=null&&r!=null?r/s:n?t:null,g=o=>c!=null&&typeof o=="number"&&Number.isFinite(o)?Math.round(o*c*10)/10:null;return{grams:r,scale:c,calories:g(e.food.calories),proteinGrams:g(e.food.proteinGrams),carbohydrateGrams:g(e.food.carbohydrateGrams),fatGrams:g(e.food.fatGrams),fiberGrams:g(e.food.fiberGrams),sugarGrams:g(e.food.sugarGrams),sodiumMg:g(e.food.sodiumMg),potassiumMg:g(e.food.potassiumMg),caffeineMg:g(e.food.caffeineMg),alcoholGrams:g(e.food.alcoholGrams)}}function Bt(e){return e.reduce((t,s)=>{const r=be(s);return{calories:t.calories+(r.calories??0),proteinGrams:t.proteinGrams+(r.proteinGrams??0),carbohydrateGrams:t.carbohydrateGrams+(r.carbohydrateGrams??0),fatGrams:t.fatGrams+(r.fatGrams??0)}},{calories:0,proteinGrams:0,carbohydrateGrams:0,fatGrams:0})}function Ve(){return{weightKg:"",waistCm:"",bodyFatPercent:"",energy:"",hunger:"",cravings:"",bloating:"",facePuffiness:"",leanness:"",notes:""}}function qt({open:e,onOpenChange:t,value:s,onChange:r,onSubmit:n,pending:c}){const g=[{id:"body",eyebrow:"Body",title:"Measurements",description:"Add weight and body measures when you have them. Empty fields are ignored.",render:(o,i)=>a.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[a.jsx(v,{label:"Weight kg",children:a.jsx(j,{inputMode:"decimal",value:o.weightKg,onChange:l=>i({weightKg:l.target.value})})}),a.jsx(v,{label:"Waist cm",children:a.jsx(j,{inputMode:"decimal",value:o.waistCm,onChange:l=>i({waistCm:l.target.value})})}),a.jsx(v,{label:"Body fat %",children:a.jsx(j,{inputMode:"decimal",value:o.bodyFatPercent,onChange:l=>i({bodyFatPercent:l.target.value})})})]})},{id:"state",eyebrow:"State",title:"Energy, appetite, and gut",description:"These subjective signals are what make the view more useful than a calorie ledger.",render:(o,i)=>a.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[a.jsx(v,{label:"Energy 0-10",children:a.jsx(j,{inputMode:"decimal",value:o.energy,onChange:l=>i({energy:l.target.value})})}),a.jsx(v,{label:"Hunger 0-10",children:a.jsx(j,{inputMode:"decimal",value:o.hunger,onChange:l=>i({hunger:l.target.value})})}),a.jsx(v,{label:"Cravings 0-10",children:a.jsx(j,{inputMode:"decimal",value:o.cravings,onChange:l=>i({cravings:l.target.value})})}),a.jsx(v,{label:"Bloating 0-10",children:a.jsx(j,{inputMode:"decimal",value:o.bloating,onChange:l=>i({bloating:l.target.value})})}),a.jsx(v,{label:"Face puffiness 0-10",children:a.jsx(j,{inputMode:"decimal",value:o.facePuffiness,onChange:l=>i({facePuffiness:l.target.value})})}),a.jsx(v,{label:"Leanness 0-10",children:a.jsx(j,{inputMode:"decimal",value:o.leanness,onChange:l=>i({leanness:l.target.value})})})]})},{id:"notes",eyebrow:"Context",title:"Notes",description:"Capture anything that explains the signal.",render:(o,i)=>a.jsx(v,{label:"Notes",children:a.jsx(xe,{value:o.notes,onChange:l=>i({notes:l.target.value}),placeholder:"Sleep, sodium, workout soreness, stressful day..."})})}];return a.jsx(ve,{open:e,onOpenChange:t,eyebrow:"Check-in",title:"Add body signal",description:"Add measurements, energy, gut, and appearance signals.",value:s,onChange:r,steps:g,onSubmit:n,submitLabel:"Save check-in",pending:c,pendingLabel:"Saving check-in",draftPersistenceKey:"weight-loss-checkin"})}function Ht(e){const t=s=>{const r=Number(s);return Number.isFinite(r)?r:null};return{body:{weightKg:t(e.weightKg),waistCm:t(e.waistCm),bodyFatPercent:t(e.bodyFatPercent),notes:e.notes},subjective:{energy:t(e.energy),hunger:t(e.hunger),cravings:t(e.cravings),timeRelation:"unspecified",notes:e.notes},gut:{bloating:t(e.bloating),notes:e.notes},appearance:{facePuffiness:t(e.facePuffiness),leanness:t(e.leanness),notes:e.notes}}}function zt(e){const t=e.items[0]??null,s=Math.max(0,e.items.length-1);return t?`${t.name}${s>0?` + ${s} more`:""}`:e.mealLabel??"Meal"}function Ot(e){return e.items.slice(0,3).map(t=>{const s=Number.isFinite(t.quantity)&&t.quantity>0?Number.isInteger(t.quantity)?String(t.quantity):t.quantity.toFixed(2).replace(/\.?0+$/,""):null,r=t.unit??"serving",n=t.grams!=null?`${t.grams.toFixed(0)}g`:null;return[s,r,n?`(${n})`:null].filter(Boolean).join(" ")}).filter(Boolean).join(" · ")}function Ut({open:e,onOpenChange:t,meals:s,onLogAgain:r,onEdit:n,onDelete:c,pending:g}){return a.jsx(ve,{open:e,onOpenChange:t,eyebrow:"History",title:"Food history",description:"Review recent foods and quickly log a previous meal again.",value:{},onChange:()=>{},steps:[{id:"history",title:"Recent meal history",render:()=>a.jsx("div",{className:"grid gap-3",children:s.map(o=>a.jsxs(E,{className:"grid gap-3",children:[a.jsxs("div",{className:"flex items-start justify-between gap-3",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-sm font-semibold text-[var(--ui-ink-strong)]",children:zt(o)}),a.jsxs("div",{className:"mt-1 text-xs text-[var(--ui-ink-faint)]",children:[o.loggedAt.slice(0,10)," ·"," ",Ot(o)||o.mealLabel||"No quantity recorded"]})]}),a.jsxs(L,{tone:"meta",children:[o.totals.calories.toFixed(0)," kcal"]})]}),a.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.jsx(K,{type:"button",size:"sm",variant:"secondary",onClick:()=>n(o),children:"Edit"}),a.jsx(K,{type:"button",size:"sm",variant:"ghost",pending:g,onClick:()=>c(o),children:"Delete"}),a.jsx(K,{type:"button",size:"sm",variant:"secondary",pending:g,onClick:()=>r(o),children:"Log again"})]})]},o.id))})}],onSubmit:async()=>t(!1),submitLabel:"Done"})}function Qt(e){const t=e.energyModel;return t.activeBurnKcal!=null||t.activeEnergyCalories!=null||t.movementCaloriesKcal!=null||t.workoutEnergyKcal!=null?`TDEE estimate ${m(t.estimatedTdeeKcal)} kcal, movement ${m(t.movementCaloriesKcal)} kcal, active burn ${m(t.activeBurnKcal)} kcal.`:"No recent HealthKit active energy, workout energy, or movement-trip calories for this user yet."}function Vt(e){switch(e){case"today_workout_energy":return"today's workout energy";case"today_healthkit_active_energy":return"today's HealthKit active energy";case"today_workout_movement_energy":return"today's workout and movement energy";case"today_workout_movement_step_energy":return"today's workout, movement, and step energy";case"today_workout_step_energy":return"today's workout and step energy";case"today_movement_step_energy":return"today's movement and step energy";case"today_movement_trip_calories":return"today's movement trip calories";case"today_step_estimate":return"today's estimated step calories";case"user_override":return"your manual active-calorie override";default:return"the default daily active calories"}}function is(){const e=Pa(),t=$a(),s=e.selectedUserIds,r=M.useMemo(()=>["forge-weight-loss-view",...s],[s]),[n,c]=M.useState(!1),[g,o]=M.useState(!1),[i,l]=M.useState(!1),[w,x]=M.useState(!1),[b,d]=M.useState(!1),[I,S]=M.useState(null),[G,A]=M.useState(null),[$,D]=M.useState(""),[te,R]=M.useState(null),[W,U]=M.useState(null),[ie,V]=M.useState("search"),[se,Y]=M.useState(void 0),[J,B]=M.useState(()=>pe()),[Z,X]=M.useState(()=>Ve()),H=Da({queryKey:r,queryFn:async()=>(await Za(s)).weightLoss}),T=H.data;M.useEffect(()=>{!T||g||n||Nt(T)||(o(!0),R(Se(T)),S(`Forge needs the missing profile fields before the calorie and macro plan can be trusted.
3
-
4
- - Confirm age, height, current weight, objective, weekly rate, and active calories.
5
- - Known HealthKit and movement values are prefilled when available.`),c(!0))},[g,T,n]),M.useEffect(()=>{T&&(D(String(Math.round(T.energyModel.todayActiveCaloriesKcal??0))),A(null))},[T==null?void 0:T.generatedAt,T==null?void 0:T.energyModel.todayActiveCaloriesKcal]);const p=()=>t.invalidateQueries({queryKey:r}),y=z({mutationFn:async u=>(await Wa({query:u,userIds:s})).foods}),C=z({mutationFn:async u=>Ba({text:u,userIds:s,commitCandidate:!1}),onSuccess:({candidate:u})=>{B(Tt(u,"chatgpt"))}}),Te=z({mutationFn:async u=>He(ga(u),s),onSuccess:()=>{B(pe()),l(!1),p()}}),Le=z({mutationFn:async({foodLogId:u,draft:f})=>qa(u,Dt(f),s),onSuccess:()=>{B(pe()),U(null),l(!1),p()}}),ye=z({mutationFn:async u=>Ha(u.id,s),onSuccess:()=>{p()}}),je=z({mutationFn:async u=>za({dayKey:T==null?void 0:T.todayLedger.dateKey,activeCaloriesKcal:u,notes:u==null?"":"Manual active-calorie override from the weight-loss view"},s),onSuccess:()=>{A(null),p()},onError:u=>{A(u instanceof Error?u.message:"Could not save active calories")}}),ue=z({mutationFn:async u=>{const f=Number(u.currentWeightKg);await Oa(Ct(u),s),Number.isFinite(f)&&await ze({weightKg:f,notes:"Updated from weight-plan setup."},s)},onSuccess:()=>{c(!1),p()}}),Ee=z({mutationFn:async u=>{const f=Ht(u);await Promise.all([f.body.weightKg!==null||f.body.waistCm!==null||f.body.bodyFatPercent!==null?ze(f.body,s):Promise.resolve(),f.subjective.energy!==null||f.subjective.hunger!==null||f.subjective.cravings!==null?Ua(f.subjective,s):Promise.resolve(),f.gut.bloating!==null?Qa(f.gut,s):Promise.resolve(),f.appearance.facePuffiness!==null||f.appearance.leanness!==null?Va(f.appearance,s):Promise.resolve()])},onSuccess:()=>{X(Ve()),x(!1),p()}}),ge=z({mutationFn:async u=>He({mealLabel:u.mealLabel??"Saved meal",source:"saved_meal",confirmationState:"confirmed",notes:u.notes??"",items:u.items.map(f=>({foodId:f.foodId,name:f.name,brand:f.brand,quantity:f.quantity,unit:f.unit,grams:f.grams,calories:f.calories,proteinGrams:f.proteinGrams,carbohydrateGrams:f.carbohydrateGrams,fatGrams:f.fatGrams,fiberGrams:f.fiberGrams,sugarGrams:f.sugarGrams,sodiumMg:f.sodiumMg,potassiumMg:f.potassiumMg,caffeineMg:f.caffeineMg,alcoholGrams:f.alcoholGrams,glycemicIndex:f.glycemicIndex,novaGroup:f.novaGroup,fermented:f.fermented,probiotic:f.probiotic,fodmapLevel:f.fodmapLevel,tags:f.tags,confidence:f.confidence??.85}))},s),onSuccess:()=>{p()}});if(H.isLoading)return a.jsx(Ya,{title:"Loading weight-loss signals",description:"Combining food logs, HealthKit, movement, workouts, body check-ins, subjective state, and gut signals."});if(H.isError||!H.data)return a.jsx(Ja,{error:H.error??new Error("Weight-loss view unavailable"),onRetry:()=>void H.refetch()});const N=H.data,P=N.todayLedger,$e=P.totals,ke=$e.calories,Ne=P.targetCalories-ke,ma=P.plannedTargetCalories??P.targetCalories,De=N.energyModel.todayActiveCaloriesKcal??N.energyModel.activeBurnKcal??N.energyModel.activeEnergyCalories??N.energyModel.movementCaloriesKcal??0,ha=N.energyModel.baselineActiveCaloriesKcal??De,we=P.activeAdjustmentCalories??0,pa=we===0?"no active-calorie adjustment":`${we>0?"+":""}${we.toFixed(0)} kcal from ${Vt(P.activeCaloriesSource)}`,xa=P.targetCalories>0?Math.min(140,Math.max(0,ke/P.targetCalories*100)):0,fa=N.energyModel,Re=N.weightTrend,me=N.foodQuality,Ce=N.trainingFuel,ba=N.subjective,va=N.gut,ya=et(N.hypotheses),Me=te??Se(N),ja=()=>{S(null),R(Se(N)),c(!0)},Ge=(u="search")=>{U(null),V(u),Y(u==="custom"?"amounts":"search"),B(u==="custom"?Lt():pe()),l(!0)},Pe=u=>{U(u.id),V("search"),Y("amounts"),B(It(u)),l(!0),d(!1)},We=u=>{typeof window<"u"&&!window.confirm(`Delete ${u.mealLabel??"this meal"} from the food log?`)||ye.mutate(u)},ka=()=>{const u=Number($);if(!Number.isFinite(u)||u<0){A("Enter a valid active-calorie value.");return}je.mutate(Math.round(u))},Na=()=>{je.mutate(null)};return a.jsxs("div",{className:"mx-auto grid w-full max-w-[1500px] gap-5",children:[a.jsx(Ra,{title:"Weight Loss",description:"A guided Forge body composition lab: editable goals, science-based calorie and macro planning, exact food quantities, body measures, energy, gut comfort, look, and testable food hypotheses.",badge:`${P.targetCalories.toFixed(0)} kcal budget · ${N.summary.loggedMealCount} food logs`}),a.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(340px,0.85fr)]",children:[a.jsx(it,{ledger:P,remainingCalories:Ne,intakePercent:xa,logSavedPending:ge.isPending||ye.isPending,onLogAgain:u=>ge.mutate(u),onEditMeal:Pe,onDeleteMeal:We}),a.jsxs("div",{className:"grid min-w-0 gap-4",children:[a.jsx(Xa,{view:N,onOpenPlan:ja,onOpenFoodSearch:()=>Ge("search"),onOpenCustomFood:()=>Ge("custom"),onOpenChatGptFood:()=>Ge("chatgpt"),onOpenCheckin:()=>x(!0),onOpenHistory:()=>d(!0)}),a.jsx(st,{view:N,draftValue:$,pending:je.isPending,error:G,onDraftChange:D,onSave:ka,onReset:Na})]})]}),a.jsxs("section",{className:"grid gap-4 xl:grid-cols-4",children:[a.jsx(Q,{label:"Today",value:`${ke.toFixed(0)} kcal`,detail:`${Ne.toFixed(0)} kcal remaining against today's ${P.targetCalories.toFixed(0)} kcal target; ${pa}.`,icon:Be,tone:Ne>=0?"green":"rose",help:`Today's target = baseline plan target + (today active calories - default active calories). Here: ${ma.toFixed(0)} + (${De.toFixed(0)} - ${ha.toFixed(0)}) = ${P.targetCalories.toFixed(0)} kcal. If no workout or same-day active evidence exists, Forge uses the default daily active calories so the target stays at baseline.`}),a.jsx(Q,{label:"Protein",value:`${$e.proteinGrams.toFixed(0)}g`,detail:`${N.target.proteinGramsTarget.toFixed(0)}g target. Protein anchors the plan while cutting or gaining.`,icon:Ta,help:"Protein grams are compared with the plan target, which uses g/kg body-weight logic and caps impossible values inside the calorie target."}),a.jsx(Q,{label:"Energy gap",value:fe(fa.estimatedDailyEnergyBalanceKcal),detail:Qt(N),icon:La,tone:"amber",help:"Energy gap estimates intake minus expenditure. Expenditure keeps active calories independent from the objective; the deficit or surplus comes from the selected weekly change rate."}),a.jsx(Q,{label:"Weight trend",value:fe(Re.sevenDayRateKg,2),detail:`Latest ${m(Re.latestWeightKg,1)} kg. Trend uses check-ins, not noisy single weigh-ins.`,icon:Ae,tone:"green",help:"Weight trend uses recent body check-ins to estimate direction. Single weigh-ins can jump from water, sodium, gut content, and training inflammation."})]}),a.jsx(ct,{view:N}),a.jsx(vt,{view:N}),a.jsxs("section",{className:"grid gap-4 xl:grid-cols-4",children:[a.jsx(Q,{label:"Food quality",value:he(me.qualityScore),detail:`Fiber density ${m(me.fiberPer1000Kcal,1)}g/1000 kcal, protein density ${m(me.proteinPer1000Kcal,1)}g/1000 kcal, ultra-processed share ${m(me.ultraProcessedShare,0)}%.`,icon:Be,tone:"green",help:"Food quality combines density and exposure signals such as fiber per 1000 kcal, protein per 1000 kcal, ultra-processed share, sodium, sugar, and available micronutrient evidence."}),a.jsx(Q,{label:"Training fuel",value:he(Ce.fuelingScore),detail:`Recent workout load ${m(Ce.recentTrainingLoad)} with ${m(Ce.carbsPerTrainingLoad,1)}g carbs per load unit.`,icon:ea,tone:"amber",help:"Training fuel relates carbohydrate and protein timing to recent workout load. It is meant to find performance and recovery patterns, not force a fixed carb rule."}),a.jsx(Q,{label:"Subjective",value:he(ba.averageFocus),detail:"Focus, energy, hunger, cravings, and performance are tracked as food-effect evidence.",icon:Ae,help:"Subjective signals are self-rated energy, focus, hunger, cravings, and performance. Forge uses them to discover food and timing effects."}),a.jsx(Q,{label:"Gut",value:he(va.averageBloating),detail:"Bloating, reflux, stool type, and suspected triggers connect food choices to comfort and look.",icon:Ea,tone:"rose",help:"Gut signals include bloating, reflux, stool type, and suspected triggers. They help connect foods to comfort, water retention, and appearance hypotheses."})]}),a.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1fr)_minmax(360px,0.8fr)]",children:[a.jsx(ot,{hypotheses:ya}),a.jsx(lt,{experiments:N.experiments})]}),a.jsx(Mt,{open:n,onOpenChange:c,view:N,value:Me,onChange:u=>{R(u),S(null)},pending:ue.isPending,error:I??(ue.error instanceof Error?ue.error.message:null),onSubmit:async()=>{const u=wt(Me);if(u){S(u);return}await ue.mutateAsync(Me)}}),a.jsx(Et,{open:i,onOpenChange:l,value:J,onChange:B,foodResults:y.data??[],searchPending:y.isPending,chatGptPending:C.isPending,chatGptError:C.error instanceof Error?C.error.message:null,logPending:Te.isPending||Le.isPending,intent:ie,initialStepId:se,onSearch:u=>y.mutate(u),onParseWithChatGpt:u=>C.mutateAsync(u).then(()=>{}),mode:W?"edit":"create",onSubmit:async()=>{if(W){await Le.mutateAsync({foodLogId:W,draft:J});return}await Te.mutateAsync(J)}}),a.jsx(qt,{open:w,onOpenChange:x,value:Z,onChange:X,pending:Ee.isPending,onSubmit:async()=>{await Ee.mutateAsync(Z)}}),a.jsx(Ut,{open:b,onOpenChange:d,meals:N.recentMeals,pending:ge.isPending||ye.isPending,onLogAgain:u=>ge.mutate(u),onEdit:Pe,onDelete:We})]})}export{is as WeightLossPage};
@@ -1,4 +0,0 @@
1
- import{j as a,aC as w,r as y}from"./vendor-kIz9EZnX.js";import{Z as m,bq as b,cL as j}from"./index-BHIKoiZ6.js";function v(s){const e=[];let r,i;for(const n of s){const t=n.trim();if(!t)continue;const o=t.indexOf(":");if(o<=0){e.push({label:"Note",value:t});continue}const c=t.slice(0,o).trim(),h=t.slice(o+1).trim();if(!h)continue;const p=c.toLowerCase();if(p==="title"){r=h;continue}if(p==="summary"){i=h;continue}e.push({label:c,value:h})}return{title:r,summary:i,rows:e}}function N(s){const e=[],r=/(!?\[\[([^\]]+)\]\]|\[([^\]]+)\]\(([^)]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|\*([^*]+)\*)/g;let i=0,n=null;for(;(n=r.exec(s))!==null;){if(n.index>i&&e.push({type:"text",value:s.slice(i,n.index)}),n[1]&&n[2]){const t=n[2].trim(),o=n[1].startsWith("!"),c=t.indexOf("|"),h=c>=0?t.slice(0,c).trim():t,p=c>=0?t.slice(c+1).trim():h;if(h.toLowerCase().startsWith("forge:")){const[,x,...l]=h.split(":");e.push({type:"forge-link",entityType:x??"",entityId:l.join(":").trim(),label:p})}else e.push({type:"wiki-link",target:h,label:p,embed:o})}else n[3]&&n[4]?e.push({type:"link",label:n[3],href:n[4].trim()}):n[5]?e.push({type:"code",value:n[5]}):n[6]?e.push({type:"strong",value:n[6]}):n[7]&&e.push({type:"em",value:n[7]});i=r.lastIndex}return i<s.length&&e.push({type:"text",value:s.slice(i)}),e}function $(s){const e=s.replace(/\r/g,"").split(`
2
- `),r=[],i=[];let n=null,t=0;for(;t<e.length;){const o=e[t]??"",c=o.trim();if(!c){t+=1;continue}if(c.startsWith("```")){const l=[];for(t+=1;t<e.length&&!(e[t]??"").trim().startsWith("```");)l.push(e[t]??""),t+=1;t+=1,r.push({type:"code",code:l.join(`
3
- `)});continue}const h=c.match(/^:::([a-z0-9-]+)\s*$/i);if(h){const l=h[1].toLowerCase(),d=[];for(t+=1;t<e.length&&(e[t]??"").trim()!==":::";)d.push(e[t]??""),t+=1;t<e.length&&(t+=1);const f=[`:::${l}`,...d,":::"].join(`
4
- `);i.push({kind:l,lines:d,raw:f}),l==="forge-infobox"?n=v(d):l==="note"||l==="tip"||l==="warning"||l==="danger"?r.push({type:"admonition",kind:l,lines:d}):(l==="forge-links"||l==="forge-media"||l==="forge-related")&&r.push({type:l,lines:d});continue}const p=o.match(/^(#{1,6})\s+(.*)$/);if(p){r.push({type:"heading",level:p[1].length,text:p[2].trim()}),t+=1;continue}if(/^>\s?/.test(o)){const l=[];for(;t<e.length&&/^>\s?/.test(e[t]??"");)l.push((e[t]??"").replace(/^>\s?/,"")),t+=1;r.push({type:"quote",text:l.join(" ").trim()});continue}if(/^[-*+]\s+/.test(o)||/^\d+\.\s+/.test(o)){const l=/^\d+\.\s+/.test(o),d=[];for(;t<e.length&&(/^[-*+]\s+/.test(e[t]??"")||/^\d+\.\s+/.test(e[t]??""));)d.push((e[t]??"").replace(/^[-*+]\s+/,"").replace(/^\d+\.\s+/,"").trim()),t+=1;r.push({type:"list",ordered:l,items:d});continue}const x=[];for(;t<e.length;){const l=e[t]??"",d=l.trim();if(!d||d.startsWith("```")||d.startsWith(":::")||/^#{1,6}\s+/.test(l)||/^>\s?/.test(l)||/^[-*+]\s+/.test(l)||/^\d+\.\s+/.test(l))break;x.push(d),t+=1}if(x.length>0){r.push({type:"paragraph",text:x.join(" ")});continue}t+=1}return{blocks:r,infobox:n,directives:i}}function L(s,e,r){return s.map((i,n)=>{const t=`${e}-${n}`;switch(i.type){case"text":return a.jsx(y.Fragment,{children:i.value},t);case"code":return a.jsx("code",{className:"rounded bg-black/10 px-1.5 py-0.5 font-mono text-[0.92em] text-white",children:i.value},t);case"strong":return a.jsx("strong",{className:"font-semibold text-white",children:i.value},t);case"em":return a.jsx("em",{className:"italic text-white/82",children:i.value},t);case"link":{const o=/^https?:\/\//i.test(i.href);return a.jsx("a",{href:i.href,target:o?"_blank":void 0,rel:o?"noreferrer":void 0,className:"text-[var(--secondary)] underline decoration-current/30 underline-offset-2 transition hover:text-white",children:i.label},t)}case"forge-link":{const o=b(i.entityType,i.entityId),c=o?j(o):null;return c?a.jsx("a",{href:c,className:"rounded-sm bg-white/[0.08] px-1.5 py-0.5 text-white no-underline ring-1 ring-black/5 transition hover:bg-white/[0.12]",children:i.label},t):a.jsx("span",{className:"rounded-sm bg-white/[0.08] px-1.5 py-0.5 text-white/64",children:i.label},t)}case"wiki-link":return a.jsx(w,{to:{pathname:`/wiki/page/${encodeURIComponent(i.target)}`,search:r?`?spaceId=${encodeURIComponent(r)}`:""},className:m("underline decoration-current/30 underline-offset-2 transition hover:text-white",i.embed?"text-[var(--primary)]":"text-[var(--secondary)]"),children:i.label},t)}})}function u(s,e,r){return L(N(s),e,r)}function W(s,e){const r=s.map(i=>i.trim()).filter(Boolean);return r.length===0?null:a.jsx("ul",{className:"space-y-1.5 pl-4 text-[13px] leading-6 text-white/76",children:r.map((i,n)=>a.jsx("li",{children:u(i,`directive-${n}`,e)},`${i}-${n}`))})}function g(s,e,r){switch(s.type){case"heading":{const i=s.level===1?"text-[1.9rem] leading-[1.08]":s.level===2?"text-[1.25rem] leading-[1.2]":s.level===3?"text-[1.05rem] leading-[1.3]":"text-[0.92rem] leading-[1.35]";return a.jsx("h2",{className:m("font-semibold tracking-[-0.02em] text-white",e>0&&"mt-6",i),children:u(s.text,`heading-${e}`,r)},`heading-${e}`)}case"paragraph":return a.jsx("p",{className:"text-[14px] leading-7 text-white/78",children:u(s.text,`paragraph-${e}`,r)},`paragraph-${e}`);case"quote":return a.jsx("blockquote",{className:"border-l-[3px] border-white/16 pl-4 text-[14px] leading-7 text-white/62",children:u(s.text,`quote-${e}`,r)},`quote-${e}`);case"list":{const i=s.ordered?"ol":"ul";return a.jsx(i,{className:m("space-y-1.5 pl-5 text-[14px] leading-7 text-white/78",s.ordered?"list-decimal":"list-disc"),children:s.items.map((n,t)=>a.jsx("li",{children:u(n,`list-${e}-${t}`,r)},`item-${e}-${t}`))},`list-${e}`)}case"code":return a.jsx("pre",{className:"overflow-x-auto rounded-xl bg-[rgba(10,16,30,0.9)] px-4 py-3 text-[12px] leading-6 text-white ring-1 ring-black/5",children:a.jsx("code",{children:s.code})},`code-${e}`);case"admonition":return a.jsxs("aside",{className:m("rounded-xl border px-4 py-3",s.kind==="warning"||s.kind==="danger"?"border-amber-500/25 bg-amber-500/8":"border-white/12 bg-white/[0.04]"),children:[a.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-white/48",children:s.kind}),a.jsx("div",{className:"grid gap-2 text-[13px] leading-6 text-white/76",children:s.lines.map((i,n)=>a.jsx("p",{children:u(i,`admonition-${e}-${n}`,r)},`admonition-line-${n}`))})]},`admonition-${e}`);case"forge-links":case"forge-media":case"forge-related":return a.jsxs("section",{className:"rounded-xl border border-white/10 bg-white/[0.03] px-4 py-3",children:[a.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-white/48",children:s.type.replace("forge-","")}),W(s.lines,r)]},`${s.type}-${e}`)}}function k(s,e,r){return a.jsx("div",{className:"text-[13px] leading-6 text-white/76",children:u(s,e,r)})}function q({infobox:s,spaceId:e,className:r}){return a.jsxs("aside",{className:m("wiki-infobox rounded-2xl border border-white/10 bg-white/[0.03] p-4",r),children:[s.title?a.jsx("div",{className:"text-[1rem] font-semibold leading-tight text-white",children:s.title}):null,s.summary?a.jsx("p",{className:"mt-2 text-[13px] leading-6 text-white/60",children:u(s.summary,"infobox-summary",e)}):null,a.jsx("dl",{className:"mt-3 grid gap-2",children:s.rows.map((i,n)=>a.jsxs("div",{className:"grid gap-1 border-t border-white/10 pt-2 first:border-t-0 first:pt-0",children:[a.jsx("dt",{className:"text-[10px] font-semibold uppercase tracking-[0.16em] text-white/48",children:i.label}),a.jsx("dd",{children:k(i.value,`infobox-row-${n}`,e)})]},`${i.label}-${n}`))})]})}function C(s){const e=[],r=[];let i=!1;for(const n of s)!i&&n.type==="heading"&&n.level<=2&&e.length>0&&(i=!0),i?r.push(n):e.push(n);return{intro:e.length>0?e:s.slice(0,1),rest:e.length>0?r:s.slice(1)}}function M({markdown:s,spaceId:e,className:r}){const i=$(s),{intro:n,rest:t}=C(i.blocks);return a.jsxs("div",{className:m("grid gap-4",r),children:[a.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1fr)_19rem] xl:items-start",children:[a.jsx("div",{className:"grid gap-4",children:n.map((o,c)=>g(o,c,e))}),i.infobox?a.jsx(q,{infobox:i.infobox,spaceId:e,className:"order-2 xl:order-none"}):null]}),t.length>0?a.jsx("div",{className:"grid gap-4",children:t.map((o,c)=>g(o,c+n.length,e))}):null]})}export{M as W};
@@ -1,26 +0,0 @@
1
- import{aJ as Ae,b5 as Ee,cc as Fe,c2 as Re,r as d,j as e,cw as Be,cx as Qe,bk as qe,bX as Ve,cb as De,aU as Ke,aR as _e,cg as He,dH as Ue,dI as Je,aK as be,bl as Xe}from"./vendor-kIz9EZnX.js";import{R as we,P as fe,O as je,C as ke,T as ve,D as ye,a as Ne}from"./ui-CsEkP2V8.js";import{j as Ye,i as _,k as Ze}from"./state-VYvD1QVP.js";import{u as Ge,c as u,g as M,fl as et,fm as tt,L as at,E as st,a as it,B as v,I as C,T as L,m as A,aq as me,Z as nt,bY as rt,fn as lt,fo as ot}from"./index-BHIKoiZ6.js";import{W as dt}from"./wiki-article-markdown-gsPTXTg1.js";import"./motion-CfdU2F35.js";import"./forms-CmLAyGqz.js";import"./board-DqHzdCPQ.js";import"./graph-BTa79qum.js";function T(s,i){return`${s}:${i}`}function ct(s){const i=s.indexOf(":");return i<=0||i>=s.length-1?null:{entityType:s.slice(0,i),entityId:s.slice(i+1)}}function Ce(s){return s.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function S(s){return Array.from(new Set(s.split(",").map(i=>i.trim()).filter(Boolean)))}function xt(s){if(!s.trim())return{};try{const i=JSON.parse(s);return i&&typeof i=="object"&&!Array.isArray(i)?i:{}}catch{return{}}}function Se(){return{pageId:null,kind:"wiki",title:"",slug:"",parentSlug:"index",indexOrder:0,showInIndex:!0,summary:"",aliasesText:"",contentMarkdown:`# Untitled
2
-
3
- `,author:"",tagsText:"",frontmatterText:`{
4
- "status": "draft"
5
- }`,linkedValues:[]}}function pt(s,i){const g=s.trim()||"Untitled";return{...Se(),title:g,slug:(i==null?void 0:i.trim())||Ce(g),contentMarkdown:`# ${g}
6
-
7
- `}}function ue(s){return{pageId:s.id,kind:s.kind,title:s.title,slug:s.slug,parentSlug:s.parentSlug,indexOrder:s.indexOrder,showInIndex:s.showInIndex,summary:s.summary,aliasesText:s.aliases.join(", "),contentMarkdown:s.contentMarkdown,author:s.author??"",tagsText:(s.tags??[]).join(", "),frontmatterText:JSON.stringify(s.frontmatter??{},null,2),linkedValues:s.links.map(i=>T(i.entityType,i.entityId))}}function I({open:s,title:i,description:g,children:O,onOpenChange:h}){return e.jsx(we,{open:s,onOpenChange:h,children:e.jsxs(fe,{children:[e.jsx(je,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.8)] backdrop-blur-sm"}),e.jsxs(ke,{className:"fixed left-1/2 top-[12vh] z-50 w-[min(32rem,calc(100vw-1.5rem))] -translate-x-1/2 rounded-[24px] border border-white/10 bg-[rgba(10,15,28,0.96)] p-4 shadow-[0_24px_80px_rgba(0,0,0,0.45)] sm:p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(ve,{className:"text-[1.05rem] font-semibold text-white",children:i}),e.jsx(ye,{className:"mt-1 text-[13px] leading-6 text-white/56",children:g})]}),e.jsx(Ne,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white","aria-label":"Close",children:e.jsx(be,{className:"size-4"})})})]}),e.jsx("div",{className:"mt-4",children:O})]})]})})}const ht="w-full rounded-[18px] border border-white/10 bg-[rgba(10,16,30,0.78)] px-3.5 py-3 text-[13px] text-white outline-none transition focus:border-[rgba(192,193,255,0.35)]";function ge(s){return s.trim().toLowerCase()}function mt(s){const i=s.trim();return i?i.split(/\s+/).length:0}function ut({icon:s,label:i,onClick:g}){return e.jsxs("div",{className:"group relative",children:[e.jsx("button",{type:"button","aria-label":i,className:"inline-flex size-10 items-center justify-center rounded-[14px] border border-white/8 bg-white/[0.04] text-white/62 transition hover:bg-white/[0.08] hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[rgba(192,193,255,0.35)]",onClick:g,children:e.jsx(s,{className:"size-4"})}),e.jsx("div",{className:"pointer-events-none absolute left-1/2 top-[calc(100%+0.55rem)] z-20 -translate-x-1/2 rounded-[12px] border border-white/8 bg-[rgba(10,15,28,0.96)] px-2.5 py-1.5 text-[11px] font-medium text-white/76 opacity-0 shadow-[0_18px_40px_rgba(0,0,0,0.32)] transition group-hover:opacity-100 group-focus-within:opacity-100",children:i})]})}function gt(s){return s.map(i=>({value:i.label,label:i.label,description:i.description,searchText:`${i.label} ${i.description}`,badge:e.jsx(u,{className:"bg-white/[0.08] text-white/80",style:i.color?{color:i.color}:void 0,children:i.label}),menuBadge:e.jsx(u,{className:"bg-white/[0.08] text-white/80",style:i.color?{color:i.color}:void 0,children:i.label})}))}function St(){var te,ae,se,ie,ne,re,le,oe,de,ce,xe,pe;const s=Ge(),i=Ye(),g=Ae(),O=Ee(),{pageId:h}=Fe(),[P,Ie]=Re(),[l,c]=d.useState(()=>Se()),[y,p]=d.useState(null),[E,H]=d.useState(""),[b,W]=d.useState(""),[Te,F]=d.useState(!1),[R,$e]=d.useState(!1),[B,Q]=d.useState(""),[q,V]=d.useState(""),U=d.useRef(null),J=d.useRef(!1),m=((te=g.state)==null?void 0:te.initialPage)??null,D=((ae=P.get("title"))==null?void 0:ae.trim())??"",X=((se=P.get("slug"))==null?void 0:se.trim())??"",f=_({queryKey:["forge-wiki-settings"],queryFn:rt}),w=_({queryKey:["forge-wiki-page",h],queryFn:()=>lt(h??""),enabled:!!h}),j=P.get("spaceId")||((ie=w.data)==null?void 0:ie.page.spaceId)||(m==null?void 0:m.spaceId)||((re=(ne=f.data)==null?void 0:ne.settings.spaces[0])==null?void 0:re.id)||"",Y=((oe=(le=f.data)==null?void 0:le.settings.spaces.find(t=>t.id===j))==null?void 0:oe.label)??"Current space",k=_({queryKey:["forge-wiki-pages",j],queryFn:()=>ot({spaceId:j||void 0,limit:500}),enabled:!!j});d.useEffect(()=>{m&&(!h||m.id===h)&&c(ue(m))},[h,m]),d.useEffect(()=>{h||m||J.current||!D||(J.current=!0,c(pt(D,X)))},[X,D,h,m]),d.useEffect(()=>{var t;(t=w.data)!=null&&t.page&&c(ue(w.data.page))},[w.data]);const $=d.useMemo(()=>{var t;return(((t=k.data)==null?void 0:t.pages)??[]).filter(a=>a.id!==l.pageId).sort((a,r)=>a.title.localeCompare(r.title))},[l.pageId,(de=k.data)==null?void 0:de.pages]),Me=d.useMemo(()=>{var a;const t=new Map;for(const r of((a=k.data)==null?void 0:a.pages)??[])for(const o of r.aliases??[]){const x=o.trim();x&&t.set(x.toLowerCase(),{value:x,label:x,description:`Alias on ${r.title}`,searchText:`${x} ${r.title} ${r.slug}`,badge:e.jsx(u,{className:"bg-white/[0.08] text-white/80",children:x}),menuBadge:e.jsx(u,{className:"bg-white/[0.08] text-white/80",children:x})})}for(const r of S(l.aliasesText))t.set(r.toLowerCase(),{value:r,label:r,description:"Wiki alias",searchText:r,badge:e.jsx(u,{className:"bg-white/[0.08] text-white/80",children:r}),menuBadge:e.jsx(u,{className:"bg-white/[0.08] text-white/80",children:r})});return Array.from(t.values()).sort((r,o)=>r.label.localeCompare(o.label))},[l.aliasesText,(ce=k.data)==null?void 0:ce.pages]),Le=d.useMemo(()=>[{value:"index",label:"Home",description:"Top-level index page",searchText:"home index top level root"},...$.map(t=>({value:t.slug,label:t.title,description:t.summary||t.slug,searchText:`${t.title} ${t.slug} ${t.summary}`}))],[$]),Z=d.useMemo(()=>{const t=ge(B);return t?$.filter(a=>`${a.title} ${a.slug} ${a.summary}`.toLowerCase().includes(t)).slice(0,12):$.slice(0,12)},[B,$]),z=d.useMemo(()=>{const t=s.snapshot.goals.map(n=>({value:T("goal",n.id),label:n.title,description:n.description,searchText:`${n.title} ${n.description}`,kind:M("goal")??void 0})),a=s.snapshot.dashboard.projects.map(n=>({value:T("project",n.id),label:n.title,description:[n.goalTitle,n.description].filter(Boolean).join(" · "),searchText:`${n.title} ${n.goalTitle} ${n.description}`,kind:M("project")??void 0})),r=s.snapshot.tasks.map(n=>({value:T("task",n.id),label:n.title,description:n.owner||n.description,searchText:`${n.title} ${n.owner} ${n.description}`,kind:M("task")??void 0})),o=s.snapshot.strategies.map(n=>({value:T("strategy",n.id),label:n.title,description:n.overview,searchText:`${n.title} ${n.overview} ${n.endStateDescription}`,kind:M("strategy")??void 0})),x=s.snapshot.habits.map(n=>({value:T("habit",n.id),label:n.title,description:n.description,searchText:`${n.title} ${n.description}`,kind:M("habit")??void 0}));return[...t,...a,...r,...o,...x].sort((n,K)=>n.label.localeCompare(K.label))},[s.snapshot.dashboard.projects,s.snapshot.goals,s.snapshot.habits,s.snapshot.strategies,s.snapshot.tasks]),G=d.useMemo(()=>{const t=ge(q);return t?z.filter(a=>`${a.label} ${a.description??""} ${a.searchText??""}`.toLowerCase().includes(t)).slice(0,12):z.slice(0,12)},[z,q]),Oe=d.useMemo(()=>{const t=s.snapshot.tags.map(o=>({label:o.name,description:`Forge ${o.kind} tag`,color:o.color})),a=S(l.tagsText).map(o=>({label:o,description:"Wiki tag"})),r=new Map;return[...t,...a].forEach(o=>{r.set(o.label.toLowerCase(),o)}),gt(Array.from(r.values()).sort((o,x)=>o.label.localeCompare(x.label)))},[l.tagsText,s.snapshot.tags]);function N(t){const a=U.current;c(r=>{const o=r.contentMarkdown;if(!a)return{...r,contentMarkdown:`${o}${o.endsWith(`
8
- `)?"":`
9
- `}${t}`};const x=a.selectionStart??o.length,n=a.selectionEnd??o.length,K=`${o.slice(0,x)}${t}${o.slice(n)}`;return requestAnimationFrame(()=>{a.focus();const he=x+t.length;a.setSelectionRange(he,he)}),{...r,contentMarkdown:K}})}const ee=Ze({mutationFn:async t=>{const a={kind:t.kind,title:t.title.trim(),slug:t.slug.trim()||Ce(t.title),parentSlug:t.parentSlug&&t.parentSlug!=="none"?t.parentSlug:null,indexOrder:t.indexOrder,showInIndex:t.showInIndex,summary:t.summary.trim(),aliases:S(t.aliasesText),contentMarkdown:t.contentMarkdown.trim(),author:t.author.trim()||null,tags:S(t.tagsText),spaceId:j,frontmatter:xt(t.frontmatterText),links:t.linkedValues.map(r=>ct(r)).filter(r=>r!==null)};return t.pageId?et(t.pageId,a):tt(a)},onSuccess:async t=>{await Promise.all([i.invalidateQueries({queryKey:["forge-wiki-pages"]}),i.invalidateQueries({queryKey:["forge-wiki-page"]}),i.invalidateQueries({queryKey:["forge-wiki-home"]}),i.invalidateQueries({queryKey:["forge-wiki-page-by-slug"]}),i.invalidateQueries({queryKey:["forge-wiki-tree"]})]),O({pathname:t.page.slug==="index"?"/wiki":`/wiki/page/${encodeURIComponent(t.page.slug)}`,search:`?spaceId=${encodeURIComponent(t.page.spaceId)}`})}});if(f.isLoading||h&&w.isLoading&&!m)return e.jsx(at,{eyebrow:"Wiki editor",title:"Preparing the editor",description:"Loading the draft, hierarchy, and link helpers."});if(f.isError||w.isError||k.isError)return e.jsx(st,{eyebrow:"Wiki editor",error:f.error??w.error??k.error,onRetry:()=>{f.refetch(),w.refetch(),k.refetch()}});if(h&&!((xe=w.data)!=null&&xe.page))return e.jsx(it,{eyebrow:"Wiki editor",title:"Page not found",description:"This wiki entry does not exist anymore."});const Pe=[{kind:"wiki-link",icon:De,label:"Wiki link"},{kind:"forge-link",icon:Ke,label:"Forge link"},{kind:"infobox",icon:_e,label:"Infobox"},{kind:"admonition",icon:He,label:"Admonition"},{kind:"related",icon:Ue,label:"Related"},{kind:"media",icon:Je,label:"Media"}],We=mt(l.contentMarkdown),ze=l.contentMarkdown.length;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-4 sm:px-5 lg:px-6",children:e.jsxs("div",{className:"mx-auto flex w-full max-w-[1720px] flex-col gap-4",children:[e.jsx("section",{className:"wiki-frame px-4 py-3 sm:px-5",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-white/42",children:"Wiki editor"}),e.jsx("h1",{className:"mt-1 text-[1.25rem] font-semibold tracking-[-0.04em] text-white",children:l.pageId?"Edit page":"New page"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(v,{variant:"secondary",size:"sm",className:"xl:hidden",onClick:()=>$e(t=>!t),"aria-expanded":R,children:[R?e.jsx(Be,{className:"size-3.5"}):e.jsx(Qe,{className:"size-3.5"}),"Metadata"]}),e.jsxs(v,{variant:"secondary",size:"sm",onClick:()=>O(-1),children:[e.jsx(qe,{className:"size-3.5"}),"Back"]}),e.jsxs(v,{size:"sm",pending:ee.isPending,pendingLabel:"Saving",disabled:!l.title.trim()||!l.contentMarkdown.trim(),onClick:()=>void ee.mutateAsync(l),children:[e.jsx(Ve,{className:"size-3.5"}),"Save page"]})]})]})}),e.jsxs("section",{className:"grid min-w-0 gap-4 xl:grid-cols-[minmax(19rem,23rem)_minmax(0,1fr)] xl:items-start",children:[e.jsx("aside",{className:nt("order-2 min-w-0 xl:order-1 xl:block",R?"block":"hidden"),children:e.jsxs("section",{className:"wiki-frame px-4 py-4 sm:px-5 xl:sticky xl:top-[5.75rem]",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3 border-b border-white/8 pb-3",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-white/42",children:"Metadata"}),e.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-white/34",children:Y})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Wiki space"}),e.jsxs("button",{type:"button",className:"flex min-h-[2.9rem] items-center justify-between gap-3 rounded-[18px] border border-white/8 bg-white/[0.04] px-3.5 text-[13px] text-white/82 transition hover:bg-white/[0.06] hover:text-white",onClick:()=>F(!0),children:[e.jsx("span",{className:"truncate",children:Y}),e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Change"})]})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Title"}),e.jsx(C,{value:l.title,onChange:t=>c(a=>({...a,title:t.target.value})),placeholder:"Page title"})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Slug"}),e.jsx(C,{value:l.slug,onChange:t=>c(a=>({...a,slug:t.target.value})),placeholder:"page-slug"})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Summary"}),e.jsx(L,{value:l.summary,onChange:t=>c(a=>({...a,summary:t.target.value})),rows:4,placeholder:"Short summary"})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Tags"}),e.jsx(A,{options:Oe,selectedValues:S(l.tagsText),onChange:t=>c(a=>({...a,tagsText:t.join(", ")})),placeholder:"Search or add tags",emptyMessage:"No tags yet.",createLabel:"Add tag",onCreate:async t=>{const a=t.trim();return{value:a,label:a,description:"Wiki tag",searchText:a,badge:e.jsx(u,{className:"bg-white/[0.08] text-white/80",children:a}),menuBadge:e.jsx(u,{className:"bg-white/[0.08] text-white/80",children:a})}}})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Forge entities"}),e.jsx(A,{options:z,selectedValues:l.linkedValues,onChange:t=>c(a=>({...a,linkedValues:t})),placeholder:"Search Forge entities"})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Aliases"}),e.jsx(A,{options:Me,selectedValues:S(l.aliasesText),onChange:t=>c(a=>({...a,aliasesText:t.join(", ")})),placeholder:"Search or add aliases",emptyMessage:"No aliases yet.",createLabel:"Add alias",onCreate:async t=>{const a=t.trim();return{value:a,label:a,description:"Wiki alias",searchText:a,badge:e.jsx(u,{className:"bg-white/[0.08] text-white/80",children:a}),menuBadge:e.jsx(u,{className:"bg-white/[0.08] text-white/80",children:a})}}})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-white/42",children:"Author"}),e.jsx(C,{value:l.author,onChange:t=>c(a=>({...a,author:t.target.value})),placeholder:"Optional author"})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("label",{className:"grid gap-1.5",children:[e.jsxs("span",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.16em] text-white/42",children:[e.jsx("span",{children:"Parent"}),e.jsx(me,{content:"Choose the page that should own this page in the wiki tree.",label:"Explain parent page"})]}),e.jsx(A,{options:Le,selectedValues:l.parentSlug?[l.parentSlug]:[],onChange:t=>c(a=>({...a,parentSlug:t[0]??null})),placeholder:"Search parent page",emptyMessage:"No matching pages."})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsxs("span",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.16em] text-white/42",children:[e.jsx("span",{children:"Order"}),e.jsx(me,{content:"Lower numbers appear earlier within the same parent page.",label:"Explain page order"})]}),e.jsx(C,{type:"number",value:String(l.indexOrder),onChange:t=>c(a=>({...a,indexOrder:Number(t.target.value||0)}))})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-[18px] border border-white/8 bg-white/[0.03] px-3.5 py-3 text-[13px] text-white/74",children:[e.jsx("input",{type:"checkbox",className:"mt-0.5",checked:l.showInIndex,onChange:t=>c(a=>({...a,showInIndex:t.target.checked}))}),e.jsx("span",{children:"Show in index"})]})]})]})}),e.jsxs("div",{className:"order-1 grid min-w-0 gap-4 xl:order-2",children:[e.jsxs("section",{className:"wiki-frame overflow-hidden",children:[e.jsxs("div",{className:"flex min-h-12 w-full flex-wrap items-center justify-between gap-3 border-b border-white/8 bg-[rgba(10,16,30,0.5)] px-3 py-2 sm:px-4",children:[e.jsx("div",{className:"flex min-w-0 flex-wrap items-center justify-start gap-1.5",children:Pe.map(t=>e.jsx(ut,{icon:t.icon,label:t.label,onClick:()=>{p(t.kind),H(""),W(""),Q(""),V("")}},t.kind))}),e.jsx("div",{className:"ml-auto flex min-w-0 flex-wrap items-center justify-end gap-3 pr-1",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-[11px] uppercase tracking-[0.14em] text-white/36",children:[e.jsxs("span",{children:[We.toLocaleString()," words"]}),e.jsxs("span",{children:[ze.toLocaleString()," chars"]})]})})]}),e.jsx("div",{className:"bg-[linear-gradient(180deg,rgba(8,13,24,0.98),rgba(9,14,26,0.94))]",children:e.jsx(L,{ref:U,value:l.contentMarkdown,onChange:t=>c(a=>({...a,contentMarkdown:t.target.value})),rows:26,className:"min-h-[38rem] resize-y rounded-none border-0 bg-transparent px-5 py-4 font-mono text-[13px] leading-6 text-white shadow-none outline-none focus-visible:ring-0 sm:min-h-[44rem] sm:px-6",placeholder:"Write the page in Markdown"})})]}),e.jsxs("section",{className:"wiki-frame overflow-hidden",children:[e.jsx("div",{className:"border-b border-white/8 px-4 py-3 sm:px-6",children:e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-white/42",children:"Preview"})}),e.jsx("div",{className:"px-4 py-5 sm:px-6",children:e.jsx("div",{className:"wiki-reading-copy wiki-reading-flow mx-auto max-w-[76rem]",children:e.jsx(dt,{markdown:l.contentMarkdown,spaceId:j})})})]})]})]})]})}),e.jsx(I,{open:y==="wiki-link",onOpenChange:t=>!t&&p(null),title:"Insert wiki link",description:"Search pages.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx(C,{autoFocus:!0,value:B,onChange:t=>Q(t.target.value),placeholder:"Search wiki pages",className:"h-11 rounded-2xl border-white/10 bg-white/[0.04] text-[14px] text-white placeholder:text-white/28"}),e.jsx("div",{className:"grid max-h-[22rem] gap-2 overflow-y-auto",children:Z.length>0?Z.map(t=>e.jsxs("button",{type:"button",className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-3 text-left transition hover:bg-white/[0.06]",onClick:()=>{N(`[[${t.slug}]]`),p(null),Q("")},children:[e.jsx("div",{className:"text-[14px] font-semibold text-white",children:t.title}),e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/46",children:t.slug}),t.summary?e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/56",children:t.summary}):null]},t.id)):e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 px-4 py-8 text-center text-[13px] text-white/42",children:"No pages match this search."})})]})}),e.jsx(I,{open:y==="forge-link",onOpenChange:t=>!t&&p(null),title:"Insert Forge link",description:"Search Forge entities.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx(C,{autoFocus:!0,value:q,onChange:t=>V(t.target.value),placeholder:"Search Forge entities",className:"h-11 rounded-2xl border-white/10 bg-white/[0.04] text-[14px] text-white placeholder:text-white/28"}),e.jsx("div",{className:"grid max-h-[22rem] gap-2 overflow-y-auto",children:G.length>0?G.map(t=>e.jsxs("button",{type:"button",className:"rounded-[18px] border border-white/8 bg-white/[0.03] px-4 py-3 text-left transition hover:bg-white/[0.06]",onClick:()=>{const[a,r]=t.value.split(":");N(`[[forge:${a}:${r}]]`),p(null),V("")},children:[e.jsx("div",{className:"text-[14px] font-semibold text-white",children:t.label}),t.description?e.jsx("div",{className:"mt-1 text-[12px] leading-5 text-white/56",children:t.description}):null]},t.value)):e.jsx("div",{className:"rounded-[18px] border border-dashed border-white/10 px-4 py-8 text-center text-[13px] text-white/42",children:"No entities match this search."})})]})}),e.jsx(I,{open:y==="infobox",onOpenChange:t=>!t&&p(null),title:"Insert infobox",description:"Create the article metadata box rendered beside the intro.",children:e.jsx("div",{className:"grid gap-3",children:e.jsx(v,{onClick:()=>{N(`:::forge-infobox
10
- Title: ${l.title||"Article title"}
11
- Summary: ${l.summary||"Short summary"}
12
- Tags: ${l.tagsText||"tag-one, tag-two"}
13
- Related: [[index|Home]]
14
- :::
15
- `),p(null)},children:"Insert infobox"})})}),e.jsx(I,{open:y==="admonition",onOpenChange:t=>!t&&p(null),title:"Insert admonition",description:"Add a callout block inside the article.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("select",{className:ht,value:E,onChange:t=>H(t.target.value),children:[e.jsx("option",{value:"",children:"Select type"}),e.jsx("option",{value:"note",children:"Note"}),e.jsx("option",{value:"tip",children:"Tip"}),e.jsx("option",{value:"warning",children:"Warning"}),e.jsx("option",{value:"danger",children:"Danger"})]}),e.jsx(L,{value:b,onChange:t=>W(t.target.value),rows:4,placeholder:"Admonition text"}),e.jsx(v,{disabled:!E||!b.trim(),onClick:()=>{N(`:::${E}
16
- ${b.trim()}
17
- :::
18
- `),p(null)},children:"Insert admonition"})]})}),e.jsx(I,{open:y==="related",onOpenChange:t=>!t&&p(null),title:"Insert related block",description:"Add an explicit related-pages block.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx(L,{value:b,onChange:t=>W(t.target.value),rows:5,placeholder:`[[page-one]]
19
- [[page-two|Readable label]]`}),e.jsx(v,{disabled:!b.trim(),onClick:()=>{N(`:::forge-related
20
- ${b.trim()}
21
- :::
22
- `),p(null)},children:"Insert related block"})]})}),e.jsx(I,{open:y==="media",onOpenChange:t=>!t&&p(null),title:"Insert media block",description:"Reference media or assets in a structured block.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx(L,{value:b,onChange:t=>W(t.target.value),rows:5,placeholder:`Image: /path/to/file.png
23
- Caption: Inspiration frame`}),e.jsx(v,{disabled:!b.trim(),onClick:()=>{N(`:::forge-media
24
- ${b.trim()}
25
- :::
26
- `),p(null)},children:"Insert media block"})]})}),e.jsx(we,{open:Te,onOpenChange:F,children:e.jsxs(fe,{children:[e.jsx(je,{className:"fixed inset-0 z-50 bg-[rgba(3,7,18,0.72)] backdrop-blur-sm"}),e.jsxs(ke,{className:"fixed left-1/2 top-[14vh] z-50 w-[min(28rem,calc(100vw-1.5rem))] -translate-x-1/2 rounded-[28px] border border-white/10 bg-[rgba(10,15,28,0.97)] p-4 shadow-[0_32px_90px_rgba(0,0,0,0.45)] sm:p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(ve,{className:"font-display text-[1.2rem] tracking-[-0.04em] text-white",children:"Choose wiki space"}),e.jsx(ye,{className:"mt-1 text-[13px] leading-6 text-white/56",children:"Save this page into a different wiki space."})]}),e.jsx(Ne,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-white/10 bg-white/[0.04] p-2 text-white/64 transition hover:bg-white/[0.08] hover:text-white","aria-label":"Close space picker",children:e.jsx(be,{className:"size-4"})})})]}),e.jsx("div",{className:"mt-4 grid gap-2",children:(pe=f.data)==null?void 0:pe.settings.spaces.map(t=>{const a=t.id===j;return e.jsxs("button",{type:"button",className:a?"flex items-center justify-between gap-3 rounded-[22px] border border-[rgba(192,193,255,0.22)] bg-[rgba(192,193,255,0.12)] px-4 py-3 text-left text-white transition":"flex items-center justify-between gap-3 rounded-[22px] border border-white/8 bg-white/[0.03] px-4 py-3 text-left text-white/78 transition hover:bg-white/[0.06] hover:text-white",onClick:()=>{const r=new URLSearchParams(P);r.set("spaceId",t.id),Ie(r,{replace:!0}),F(!1)},children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[14px] font-semibold",children:t.label}),e.jsx("span",{className:"mt-1 block text-[12px] leading-5 text-white/52",children:t.description||`/${t.slug}`})]}),a?e.jsx(Xe,{className:"size-4 shrink-0 text-[var(--primary)]"}):null]},t.id)})})]})]})})]})}export{St as WikiEditorPage};