forge-openclaw-plugin 0.2.102 → 0.2.104

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 (175) 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/server/src/watch-mobile.js +28 -0
  118. package/dist/server/src/components/workbench-boxes/shared/generic-node-view.js +13 -5
  119. package/dist/server/src/lib/api.js +10 -1
  120. package/openclaw.plugin.json +1 -1
  121. package/package.json +1 -1
  122. package/dist/assets/activity-page-CgF7K2ww.js +0 -1
  123. package/dist/assets/calendar-page-C1Wfd2Fy.js +0 -1
  124. package/dist/assets/calendar-rules-CaZXtlxt.js +0 -1
  125. package/dist/assets/companion-sync-lab-page-NgeK-O-P.js +0 -1
  126. package/dist/assets/entity-note-count-link-BrS1-O0o.js +0 -1
  127. package/dist/assets/execution-board-CpO2ch6v.js +0 -1
  128. package/dist/assets/floating-action-menu-zzC2r0Ob.js +0 -1
  129. package/dist/assets/goal-detail-page-JK_Nva8e.js +0 -1
  130. package/dist/assets/goals-page-yeoJ06Vw.js +0 -1
  131. package/dist/assets/habits-page-Dx5EhkJi.js +0 -1
  132. package/dist/assets/index-BHIKoiZ6.js +0 -19
  133. package/dist/assets/index-H8R-ABM3.css +0 -1
  134. package/dist/assets/insights-page-CujrosD_.js +0 -8
  135. package/dist/assets/kanban-page-Q9NuIz5w.js +0 -1
  136. package/dist/assets/knowledge-graph-page-DaJmlvvM.js +0 -1
  137. package/dist/assets/life-force-workspace-CLVexVnb.js +0 -1
  138. package/dist/assets/movement-page-ClaoTNuX.js +0 -1
  139. package/dist/assets/notes-page-DYI8s3NN.js +0 -1
  140. package/dist/assets/pill-cluster-7UZd_lHp.js +0 -1
  141. package/dist/assets/preferences-page-BrKEkmfD.js +0 -1
  142. package/dist/assets/project-collections-CZagCmeH.js +0 -1
  143. package/dist/assets/project-management-hierarchy-page-Dr7hW9PW.js +0 -1
  144. package/dist/assets/project-management-section-nav-BLdAgTge.js +0 -1
  145. package/dist/assets/projects-page-UKrby_5-.js +0 -1
  146. package/dist/assets/rewards-page-PZFPa6rR.js +0 -1
  147. package/dist/assets/scheduling-rules-editor-B9KNKsQz.js +0 -1
  148. package/dist/assets/settings-agents-page-DPx2F6wf.js +0 -6
  149. package/dist/assets/settings-bin-page-COwP3gjo.js +0 -1
  150. package/dist/assets/settings-calendar-page-C-ghE0YT.js +0 -5
  151. package/dist/assets/settings-data-page-CBubzKBw.js +0 -1
  152. package/dist/assets/settings-logs-page-uOuXMeBm.js +0 -1
  153. package/dist/assets/settings-mobile-page-C5rfj8_r.js +0 -1
  154. package/dist/assets/settings-models-page-DijmUWdU.js +0 -1
  155. package/dist/assets/settings-page-B4u5TR5g.js +0 -1
  156. package/dist/assets/settings-rewards-page-COiTwkMH.js +0 -1
  157. package/dist/assets/settings-users-page-DEGa5DNn.js +0 -1
  158. package/dist/assets/settings-wiki-page-Cvsiz5_e.js +0 -1
  159. package/dist/assets/sleep-page-BnSOwkEU.js +0 -1
  160. package/dist/assets/sports-page-l1RqXzA_.js +0 -1
  161. package/dist/assets/strategies-page-DEnPlpAs.js +0 -1
  162. package/dist/assets/strategy-detail-page-Ls8bxKeH.js +0 -1
  163. package/dist/assets/task-detail-page-CgrYgQLD.js +0 -1
  164. package/dist/assets/timebox-planning-dialog-Ww0NGLLo.js +0 -1
  165. package/dist/assets/today-page-CIuFHMi1.js +0 -1
  166. package/dist/assets/training-load-page-BIwc648i.js +0 -1
  167. package/dist/assets/weekly-review-page-BFpBe1kI.js +0 -1
  168. package/dist/assets/weight-loss-page-BgMoBpBt.js +0 -5
  169. package/dist/assets/wiki-article-markdown-gsPTXTg1.js +0 -4
  170. package/dist/assets/wiki-editor-page-BpAZHooY.js +0 -26
  171. package/dist/assets/wiki-ingest-history-page-C-ig8O22.js +0 -1
  172. package/dist/assets/wiki-ingest-modal-BK4eQgqs.js +0 -1
  173. package/dist/assets/wiki-page-CMTZ60Zt.js +0 -1
  174. package/dist/assets/workbench-flow-page-BIpWUcLJ.js +0 -5
  175. package/dist/assets/workbench-page-CtCjYSRe.js +0 -1
@@ -1 +1 @@
1
- import{j as e}from"./vendor-kIz9EZnX.js";import{i as x}from"./state-VYvD1QVP.js";import{P as v}from"./page-hero-oFHaAjtL.js";import{u as f,L as j,E as b,C as y,c as l,Z as N,bN as M,cv as k}from"./index-BHIKoiZ6.js";import{S as o,f as C,m as D,M as u}from"./daily-metrics-dashboard-BMyL0Qr4.js";import"./motion-CfdU2F35.js";import"./ui-CsEkP2V8.js";import"./forms-CmLAyGqz.js";import"./board-DqHzdCPQ.js";import"./graph-BTa79qum.js";import"./charts-FcU0F3XV.js";const R=["restingHeartRate","heartRateVariabilitySDNN","vo2Max","oxygenSaturation","bodyMass","stepCount"];function p(t,a){return a.map(r=>({...r,metrics:t.filter(s=>s.category===r.category)}))}function S(t){return t}function V({metrics:t}){if(!t.summary.hasData||t.metrics.length===0)return null;const a=p(t.metrics,t.summary.categoryBreakdown),r=t.metrics.find(n=>n.metric==="devrageSwearCount")??null,s=t.metrics.find(n=>n.metric==="swearingMessagePercent")??null;return e.jsxs("section",{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:"Psyche metrics"}),e.jsx("div",{className:"mt-1 text-2xl font-semibold text-white",children:"Conversation tone alongside body signals"})]}),e.jsxs(l,{className:"bg-amber-200/10 text-amber-50",children:[t.summary.trackedDays," tracked days"]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-2",children:[e.jsx(o,{title:"Devrage count",description:"Daily user-message swear count from stored conversation history.",metric:r}),e.jsx(o,{title:"Swearing rate",description:"Share of scanned user messages that contained at least one tracked swear.",metric:s})]}),e.jsx(u,{groups:a})]})}function I(){var h;const t=f(),a=x({queryKey:["forge-vitals-view",...t.selectedUserIds],queryFn:async()=>(await M(t.selectedUserIds)).vitals}),r=x({queryKey:["forge-psyche-metrics-vitals-view"],queryFn:async()=>(await k()).metrics});if(a.isLoading)return e.jsx(j,{title:"Loading body signals",description:"Reading recent HealthKit body metrics, recovery signals, and daily aggregates."});if(a.isError||!a.data)return e.jsx(b,{error:a.error??new Error("Vitals data unavailable"),onRetry:()=>void a.refetch()});const s=a.data,n=s.metrics.map(S),c=R.map(i=>n.find(d=>d.metric===i)??null),m=s.summary.categoryBreakdown,w=p(n,m),g=!r.isError&&((h=r.data)!=null&&h.summary.hasData)?r.data:null;return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1380px] gap-5",children:[e.jsx(v,{title:"Vitals",description:"Forge now keeps a daily body-signals layer across recovery, cardio fitness, breathing, composition, temperature, and activity. Use this surface to spot drift early, not just admire numbers late.",badge:`${s.summary.metricCount} live metrics`}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-4",children:[e.jsx(o,{title:"Recovery pulse",description:"Resting heart rate and HRV are the fastest read on load, stress, and whether today needs a gentler edge.",metric:c[0]??c[1]}),e.jsx(o,{title:"Cardio engine",description:"VO2 max and walking heart rate show whether baseline fitness is improving or whether your effort is costing more than usual.",metric:c[2]}),e.jsx(o,{title:"Breath and oxygen",description:"Respiratory rate and oxygen saturation help catch nights or stretches where recovery quality starts to slip.",metric:c[3]}),e.jsx(o,{title:"Body composition",description:"Mass and composition stay close to the daily story so progress is visible without flattening everything into weight alone.",metric:c[4]})]}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.1fr)_minmax(340px,0.9fr)]",children:[e.jsxs(y,{className:"overflow-hidden rounded-[30px] border-white/8 bg-[radial-gradient(circle_at_top_left,rgba(108,99,255,0.16),transparent_36%),linear-gradient(180deg,rgba(15,19,38,0.98),rgba(9,13,28,0.98))] p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Coverage"}),e.jsxs("div",{className:"text-2xl font-semibold text-white",children:[s.summary.trackedDays," tracked days across ",s.summary.metricCount," metrics"]}),e.jsx("div",{className:"max-w-3xl text-sm leading-6 text-white/58",children:"The companion is compressing HealthKit into daily signal bands, so what you see here is designed for decisions: how your recovery is trending, where your physiology is changing, and which body systems are actually being observed consistently."})]}),e.jsxs(l,{className:"bg-white/[0.08] text-white/72",children:["Latest snapshot ",C(s.summary.latestDateKey)]})]}),e.jsx("div",{className:"mt-5 grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:m.map(i=>{const d=D(i.category);return e.jsxs("div",{className:N("rounded-[22px] border bg-white/[0.03] p-4",d.ring),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(l,{className:d.badge,children:i.category}),e.jsxs("div",{className:"text-xs text-white/44",children:[i.coverageDays," days"]})]}),e.jsx("div",{className:"mt-3 text-2xl font-semibold text-white",children:i.metricCount}),e.jsxs("div",{className:"mt-1 text-sm text-white/58",children:["active metric",i.metricCount===1?"":"s"]})]},i.category)})})]}),e.jsx(y,{className:"rounded-[30px] border-white/8 bg-[linear-gradient(180deg,rgba(13,19,37,0.96),rgba(10,14,30,0.96))] p-6",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Daily interpretation"}),e.jsx("div",{className:"text-lg font-semibold text-white",children:"Body signals should feel operational, not medical-chart dead."}),e.jsxs("div",{className:"grid gap-3 text-sm leading-6 text-white/58",children:[e.jsx("div",{children:"Lower resting heart rate paired with stable or rising HRV usually means recovery is holding."}),e.jsx("div",{children:"Rising walking heart rate, falling HRV, or a jump in respiratory rate usually means you are carrying more load than the calendar admits."}),e.jsx("div",{children:"Composition and temperature metrics move slower, but they make the fast signals easier to trust because you can see the surrounding body context."})]}),e.jsxs("div",{className:"mt-2 rounded-[22px] border border-white/8 bg-white/[0.035] p-4 text-sm text-white/70",children:[s.summary.latestMetricCount," metrics updated on the latest tracked day."]})]})})]}),e.jsx(u,{groups:w}),g?e.jsx(V,{metrics:g}):null]})}export{I as VitalsPage};
1
+ import{j as e}from"./vendor-Dnkkx2co.js";import{i as x}from"./state-vCcAT5Hq.js";import{P as v}from"./page-hero-ffKzgyW3.js";import{u as f,L as j,E as b,C as y,c as l,Z as N,bN as M,cv as k}from"./index-EqQsXoat.js";import{S as o,f as C,m as D,M as u}from"./daily-metrics-dashboard-CiJkkkd1.js";import"./motion-Lt5B1XuE.js";import"./ui-C1iwpj2-.js";import"./forms-hB0SqEh-.js";import"./board-dIX6etHh.js";import"./graph-DDUZNRsO.js";import"./charts-DFnEuIMB.js";const R=["restingHeartRate","heartRateVariabilitySDNN","vo2Max","oxygenSaturation","bodyMass","stepCount"];function p(t,a){return a.map(r=>({...r,metrics:t.filter(s=>s.category===r.category)}))}function S(t){return t}function V({metrics:t}){if(!t.summary.hasData||t.metrics.length===0)return null;const a=p(t.metrics,t.summary.categoryBreakdown),r=t.metrics.find(n=>n.metric==="devrageSwearCount")??null,s=t.metrics.find(n=>n.metric==="swearingMessagePercent")??null;return e.jsxs("section",{className:"grid gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/38",children:"Psyche metrics"}),e.jsx("div",{className:"mt-1 text-2xl font-semibold text-white",children:"Conversation tone alongside body signals"})]}),e.jsxs(l,{className:"bg-amber-200/10 text-amber-50",children:[t.summary.trackedDays," tracked days"]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-2",children:[e.jsx(o,{title:"Devrage count",description:"Daily user-message swear count from stored conversation history.",metric:r}),e.jsx(o,{title:"Swearing rate",description:"Share of scanned user messages that contained at least one tracked swear.",metric:s})]}),e.jsx(u,{groups:a})]})}function I(){var h;const t=f(),a=x({queryKey:["forge-vitals-view",...t.selectedUserIds],queryFn:async()=>(await M(t.selectedUserIds)).vitals}),r=x({queryKey:["forge-psyche-metrics-vitals-view"],queryFn:async()=>(await k()).metrics});if(a.isLoading)return e.jsx(j,{title:"Loading body signals",description:"Reading recent HealthKit body metrics, recovery signals, and daily aggregates."});if(a.isError||!a.data)return e.jsx(b,{error:a.error??new Error("Vitals data unavailable"),onRetry:()=>void a.refetch()});const s=a.data,n=s.metrics.map(S),c=R.map(i=>n.find(d=>d.metric===i)??null),m=s.summary.categoryBreakdown,w=p(n,m),g=!r.isError&&((h=r.data)!=null&&h.summary.hasData)?r.data:null;return e.jsxs("div",{className:"mx-auto grid w-full max-w-[1380px] gap-5",children:[e.jsx(v,{title:"Vitals",description:"Forge now keeps a daily body-signals layer across recovery, cardio fitness, breathing, composition, temperature, and activity. Use this surface to spot drift early, not just admire numbers late.",badge:`${s.summary.metricCount} live metrics`}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-4",children:[e.jsx(o,{title:"Recovery pulse",description:"Resting heart rate and HRV are the fastest read on load, stress, and whether today needs a gentler edge.",metric:c[0]??c[1]}),e.jsx(o,{title:"Cardio engine",description:"VO2 max and walking heart rate show whether baseline fitness is improving or whether your effort is costing more than usual.",metric:c[2]}),e.jsx(o,{title:"Breath and oxygen",description:"Respiratory rate and oxygen saturation help catch nights or stretches where recovery quality starts to slip.",metric:c[3]}),e.jsx(o,{title:"Body composition",description:"Mass and composition stay close to the daily story so progress is visible without flattening everything into weight alone.",metric:c[4]})]}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.1fr)_minmax(340px,0.9fr)]",children:[e.jsxs(y,{className:"overflow-hidden rounded-[30px] border-white/8 bg-[radial-gradient(circle_at_top_left,rgba(108,99,255,0.16),transparent_36%),linear-gradient(180deg,rgba(15,19,38,0.98),rgba(9,13,28,0.98))] p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Coverage"}),e.jsxs("div",{className:"text-2xl font-semibold text-white",children:[s.summary.trackedDays," tracked days across ",s.summary.metricCount," metrics"]}),e.jsx("div",{className:"max-w-3xl text-sm leading-6 text-white/58",children:"The companion is compressing HealthKit into daily signal bands, so what you see here is designed for decisions: how your recovery is trending, where your physiology is changing, and which body systems are actually being observed consistently."})]}),e.jsxs(l,{className:"bg-white/[0.08] text-white/72",children:["Latest snapshot ",C(s.summary.latestDateKey)]})]}),e.jsx("div",{className:"mt-5 grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:m.map(i=>{const d=D(i.category);return e.jsxs("div",{className:N("rounded-[22px] border bg-white/[0.03] p-4",d.ring),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(l,{className:d.badge,children:i.category}),e.jsxs("div",{className:"text-xs text-white/44",children:[i.coverageDays," days"]})]}),e.jsx("div",{className:"mt-3 text-2xl font-semibold text-white",children:i.metricCount}),e.jsxs("div",{className:"mt-1 text-sm text-white/58",children:["active metric",i.metricCount===1?"":"s"]})]},i.category)})})]}),e.jsx(y,{className:"rounded-[30px] border-white/8 bg-[linear-gradient(180deg,rgba(13,19,37,0.96),rgba(10,14,30,0.96))] p-6",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-white/40",children:"Daily interpretation"}),e.jsx("div",{className:"text-lg font-semibold text-white",children:"Body signals should feel operational, not medical-chart dead."}),e.jsxs("div",{className:"grid gap-3 text-sm leading-6 text-white/58",children:[e.jsx("div",{children:"Lower resting heart rate paired with stable or rising HRV usually means recovery is holding."}),e.jsx("div",{children:"Rising walking heart rate, falling HRV, or a jump in respiratory rate usually means you are carrying more load than the calendar admits."}),e.jsx("div",{children:"Composition and temperature metrics move slower, but they make the fast signals easier to trust because you can see the surrounding body context."})]}),e.jsxs("div",{className:"mt-2 rounded-[22px] border border-white/8 bg-white/[0.035] p-4 text-sm text-white/70",children:[s.summary.latestMetricCount," metrics updated on the latest tracked day."]})]})})]}),e.jsx(u,{groups:w}),g?e.jsx(V,{metrics:g}):null]})}export{I as VitalsPage};
@@ -0,0 +1 @@
1
+ import{j as e}from"./vendor-Dnkkx2co.js";import{j as y,i as f,k as g}from"./state-vCcAT5Hq.js";import{F as j}from"./flagship-signal-deck-CtHC3mql.js";import{P as k,fp as b,i as N,S as R,E as v,C as w,c as h,B as $,fq as S}from"./index-EqQsXoat.js";import{P as z}from"./page-hero-ffKzgyW3.js";import"./motion-Lt5B1XuE.js";import"./ui-C1iwpj2-.js";import"./forms-hB0SqEh-.js";import"./board-dIX6etHh.js";import"./graph-DDUZNRsO.js";const o="font-label text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",d="overflow-hidden rounded-[20px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)]",x="text-sm leading-6 text-[var(--ui-ink-soft)]";function P({data:s}){const m=Math.max(1,...s.map(i=>i.xp)),t=s.length>0?Math.max(4,Math.min(18,280/s.length-4)):8,c=s.length>1?Math.max(1,(300-s.length*t)/(s.length-1)):0;return e.jsx("div",{className:"mt-4 aspect-[16/9] min-h-56 w-full min-w-0 overflow-hidden rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] p-3",children:e.jsxs("svg",{viewBox:"0 0 340 200",role:"img","aria-label":"Weekly review XP chart",className:"h-full w-full",children:[e.jsx("g",{stroke:"var(--ui-border-subtle)",strokeWidth:"1",children:[45,85,125,165].map(i=>e.jsx("line",{x1:"20",x2:"320",y1:i,y2:i},i))}),s.map((i,r)=>{const l=20+r*(t+c),n=Math.max(2,i.xp/m*128);return e.jsxs("g",{children:[e.jsx("rect",{x:l,y:168-n,width:t,height:n,rx:"5",fill:"var(--primary)"}),r===0||r===s.length-1||r%3===0?e.jsx("text",{x:l+t/2,y:"192",fill:"var(--ui-ink-faint)",fontSize:"10",textAnchor:"middle",children:i.label}):null]},`${i.label}-${r}`)})]})})}function L(){var u;const{t:s}=k(),m=y(),t=f({queryKey:["forge-weekly-review"],queryFn:S}),c=g({mutationFn:b,onSuccess:async()=>{await Promise.all([m.invalidateQueries({queryKey:["forge-weekly-review"]}),m.invalidateQueries({queryKey:["forge-xp-metrics"]}),m.invalidateQueries({queryKey:["forge-reward-ledger"]}),N(m),m.invalidateQueries({queryKey:["activity-archive"]})])}}),i=(u=t.data)==null?void 0:u.review;if(t.isLoading)return e.jsx(R,{});if(t.isError)return e.jsx(v,{eyebrow:s("common.weeklyReview.heroEyebrow"),error:t.error,onRetry:()=>void t.refetch()});if(!i)return e.jsx(v,{eyebrow:s("common.weeklyReview.heroEyebrow"),error:new Error("Forge returned an empty weekly review payload."),onRetry:()=>void t.refetch()});const r=i.wins[0]??null,l=i.calibration.find(a=>a.mode==="recover")??i.calibration[0]??null,n=i.calibration.find(a=>a.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)??s("common.weeklyReview.noWin"),detail:(r==null?void 0:r.summary)??s("common.weeklyReview.noWinDetail"),badge:r?`+${r.rewardXp} xp`:`${i.wins.length} wins`},{id:"recovery",label:"Recovery",title:(l==null?void 0:l.title)??s("common.weeklyReview.noRecovery"),detail:(l==null?void 0:l.note)??s("common.weeklyReview.noRecoveryDetail"),badge:(l==null?void 0:l.mode)??"maintain"},{id:"next-intent",label:"Next intent",title:(n==null?void 0:n.title)??i.reward.title,detail:(n==null?void 0:n.note)??i.reward.summary,badge:`+${i.reward.rewardXp} xp`}];return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(z,{title:"Weekly Review",description:`${i.windowLabel}. ${s("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(w,{children:[e.jsx("div",{className:o,children:s("common.weeklyReview.sectionMomentum")}),e.jsx(P,{data:i.chart}),e.jsxs("div",{className:"mt-4 grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:`${d} p-4`,children:[e.jsx("div",{className:o,children:"XP"}),e.jsx("div",{className:"mt-2 text-2xl text-[var(--ui-ink-strong)]",children:i.momentumSummary.totalXp})]}),e.jsxs("div",{className:`${d} p-4`,children:[e.jsx("div",{className:o,children:"Focus hours"}),e.jsx("div",{className:"mt-2 text-2xl text-[var(--ui-ink-strong)]",children:i.momentumSummary.focusHours})]}),e.jsxs("div",{className:`${d} p-4`,children:[e.jsx("div",{className:o,children:"Peak window"}),e.jsx("div",{className:"mt-2 break-words text-2xl text-[var(--ui-ink-strong)]",children:i.momentumSummary.peakWindow})]})]})]}),e.jsxs(w,{children:[e.jsx("div",{className:o,children:s("common.weeklyReview.sectionGoals")}),e.jsx("div",{className:"mt-4 grid gap-3",children:i.calibration.map(a=>e.jsxs("div",{className:`${d} 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 break-words font-medium text-[var(--ui-ink-strong)]",children:a.title}),e.jsx(h,{className:"max-w-[9rem] shrink-0 self-start",children:a.mode})]}),e.jsx("div",{className:`mt-3 break-words ${x}`,children:a.note})]},a.id))})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs(w,{children:[e.jsx("div",{className:o,children:s("common.weeklyReview.sectionWins")}),e.jsx("div",{className:"mt-4 grid gap-3",children:i.wins.map(a=>e.jsxs("div",{className:`${d} 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 break-words font-medium text-[var(--ui-ink-strong)]",children:a.title}),e.jsxs(h,{tone:"signal",className:"max-w-[8rem] shrink-0 self-start",children:["+",a.rewardXp," xp"]})]}),e.jsx("div",{className:`mt-2 break-words ${x}`,children:a.summary})]},a.id))})]}),e.jsxs(w,{children:[e.jsx("h2",{className:"break-words font-display text-3xl text-[var(--ui-ink-strong)]",children:i.reward.title}),e.jsx("p",{className:`mt-3 leading-7 ${x}`,children:i.reward.summary}),e.jsxs("div",{className:`mt-4 ${d} p-4`,children:[e.jsx("div",{className:o,children:s("common.weeklyReview.completionBonus")}),e.jsxs("div",{className:"mt-2 text-3xl text-[var(--primary)]",children:["+",i.reward.rewardXp," XP"]})]}),e.jsx($,{className:"mt-4 w-full",disabled:i.completion.finalized,pending:c.isPending,pendingLabel:s("common.weeklyReview.finalizePending"),onClick:async()=>{await c.mutateAsync()},children:i.completion.finalized?s("common.weeklyReview.finalized"):s("common.weeklyReview.finalize")}),e.jsx("div",{className:`mt-3 ${x}`,children:i.completion.finalized?`${s("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(j,{eyebrow:s("common.weeklyReview.summaryEyebrow"),title:s("common.weeklyReview.summaryTitle"),description:s("common.weeklyReview.summaryDescription"),items:p})]})}export{L as WeeklyReviewPage};
@@ -0,0 +1,5 @@
1
+ import{j as a,b4 as De,aG as ta,b3 as na,cm as Aa,dx as Ea,cG as _a,bL as _e,bX as $a,cK as ra,ce as Ta,c7 as sa,dy as Da,dz as Ia,bE as ia,dA as La,dB as Pa,r as F,d8 as Ra,bH as Qe,dC as Wa,bF as Ba,bu as Ha}from"./vendor-Dnkkx2co.js";import{j as qa,i as za,k as q}from"./state-vCcAT5Hq.js";import{P as Oa}from"./page-hero-ffKzgyW3.js";import{C as z,B as K,aq as de,I as k,Z as oa,c as $,Q as je,F as y,j as Ve,T as ve,u as Ua,eW as Qa,eX as Va,eY as Ye,eZ as Ya,e_ as Ja,e$ as Za,f0 as Xa,f1 as Je,f2 as et,f3 as at,f4 as tt,L as nt,E as rt,f5 as st}from"./index-EqQsXoat.js";import{S as D,a as N}from"./surface-CJI17F3n.js";import{f as $e}from"./date-keys-Cj1G3TOn.js";import"./motion-Lt5B1XuE.js";import"./ui-C1iwpj2-.js";import"./forms-hB0SqEh-.js";import"./board-dIX6etHh.js";import"./graph-DDUZNRsO.js";function it({view:e,onOpenPlan:t,onOpenFoodSearch:n,onOpenCustomFood:r,onOpenChatGptFood:s,onOpenCheckin:d,onOpenHistory:g}){return a.jsxs(z,{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(De,{className:"size-4"}),"Custom food"]}),a.jsxs(K,{type:"button",variant:"secondary",onClick:s,children:[a.jsx(ta,{className:"size-4"}),"Ask ChatGPT"]}),a.jsxs(K,{type:"button",variant:"secondary",onClick:n,children:[a.jsx(na,{className:"size-4"}),"Search food"]}),a.jsxs(K,{type:"button",variant:"secondary",onClick:t,children:[a.jsx(Aa,{className:"size-4"}),"Plan settings"]}),a.jsxs(K,{type:"button",variant:"secondary",onClick:d,children:[a.jsx(Ea,{className:"size-4"}),"Add measure"]}),a.jsxs(K,{type:"button",variant:"secondary",onClick:g,children:[a.jsx(_a,{className:"size-4"}),"Food history"]})]})]})}function A(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ie(e){return typeof e=="string"&&e.trim()?e:null}function i(e,t=0){const n=A(e);return n===null?"n/a":n.toFixed(t)}function W(e,t=0){const n=A(e);return n===null?"n/a":`${n>0?"+":""}${n.toFixed(t)}`}function be(e){const t=A(e);return t===null?"n/a":`${t.toFixed(1)}/10`}function ot(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&!Array.isArray(t)):[]}function lt(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 ct(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 because it is above the default.";default:return"No meaningful same-day active evidence yet, so the default active calories are used."}}function dt({view:e,draftValue:t,pending:n,error:r,onDraftChange:s,onSave:d,onReset:g}){const l=e.energyModel,o=e.todayLedger,c=l.todayActiveOverride,w=l.todayActiveCaloriesSource,b=`${o.plannedTargetCalories.toFixed(0)} + (${l.todayActiveCaloriesKcal.toFixed(0)} - ${l.baselineActiveCaloriesKcal.toFixed(0)}) = ${o.targetCalories.toFixed(0)} kcal`;return a.jsxs(z,{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(de,{label:"Explain active calories",content:`Today target = baseline food target + (today active calories - default active calories). ${b}. 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:[l.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(_e,{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:ct(w)}),a.jsxs("div",{children:["Default ",l.baselineActiveCaloriesKcal.toFixed(0)," kcal"," · ","observed"," ",l.todayObservedActiveCaloriesKcal!=null?`${l.todayObservedActiveCaloriesKcal.toFixed(0)} kcal`:"n/a"]}),a.jsxs("div",{className:"break-words",children:["Source: ",lt(w)]})]}),a.jsxs("div",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)_auto] gap-2",children:[a.jsx(k,{inputMode:"decimal",value:t,onChange:x=>s(x.target.value),"aria-label":"Today active calories",className:"py-2.5"}),a.jsxs(K,{type:"button",onClick:d,pending:n,pendingLabel:"Applying",children:[a.jsx($a,{className:"size-4"}),"Apply"]})]}),a.jsxs(K,{type:"button",variant:"secondary",onClick:g,disabled:!c||n,children:[a.jsx(ra,{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 ut={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 Y({label:e,value:t,detail:n,icon:r,tone:s="default",help:d,helpMaxWidthPx:g}){return a.jsxs(z,{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:oa("rounded-2xl p-2.5",ut[s]),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}),d?a.jsx(de,{content:d,label:`Explain ${e}`,maxWidthPx:g}):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:n})]})]})}function gt({meal:e,onLogAgain:t,onEdit:n,onDelete:r,pending:s=!1}){const d=e.items[0]??null,g=Math.max(0,e.items.length-1),l=d?`${d.name}${g>0?` + ${g} more`:""}`:e.mealLabel??"Meal",o=e.items.slice(0,3).map(c=>{const w=Number.isFinite(c.quantity)&&c.quantity>0?Number.isInteger(c.quantity)?String(c.quantity):c.quantity.toFixed(2).replace(/\.?0+$/,""):null,b=c.unit??"serving",x=c.grams!=null?`${c.grams.toFixed(0)}g`:null;return[w,b,x?`(${x})`:null].filter(Boolean).join(" ")}).filter(Boolean).join(" · ");return a.jsxs(D,{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:l}),a.jsx("div",{className:"mt-1 text-xs leading-5 text-[var(--ui-ink-faint)]",children:o||e.notes||"No quantity recorded"})]}),a.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[e.mealLabel?a.jsx($,{tone:"meta",children:e.mealLabel}):null,a.jsxs($,{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:[n?a.jsxs(K,{type:"button",size:"sm",variant:"secondary",onClick:()=>n(e),children:[a.jsx(Ta,{className:"size-4"}),"Edit"]}):null,r?a.jsxs(K,{type:"button",size:"sm",variant:"ghost",pending:s,onClick:()=>r(e),children:[a.jsx(sa,{className:"size-4"}),"Delete"]}):null,t?a.jsxs(K,{type:"button",size:"sm",variant:"ghost",pending:s,onClick:()=>t(e),children:[a.jsx(ra,{className:"size-4"}),"Log again"]}):null]})]})}function Ie({children:e}){return a.jsx(D,{className:"border-dashed border-[var(--ui-border-strong)] p-5 text-sm text-[var(--ui-ink-soft)]",children:e})}function mt({ledger:e,remainingCalories:t,intakePercent:n,logSavedPending:r,onLogAgain:s,onEditMeal:d,onDeleteMeal:g}){const l=e.totals;return a.jsxs(z,{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(de,{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($,{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:oa("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,n)}%`}})}),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:[l.carbohydrateGrams.toFixed(0),"g carbs"]}),a.jsxs("span",{children:[l.fatGrams.toFixed(0),"g fat"]}),a.jsxs("span",{children:[l.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(o=>a.jsx(gt,{meal:o,pending:r,onLogAgain:s,onEdit:d,onDelete:g},o.id)):a.jsx(Ie,{children:"No meals logged today yet."})})]})}function ht({hypotheses:e}){return a.jsxs(z,{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,n)=>a.jsxs(D,{children:[a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsx($,{tone:"signal",children:ie(t.metric)??"pattern"}),a.jsx("span",{className:"text-xs text-[var(--ui-ink-faint)]",children:i(t.confidence,2)})]}),a.jsx("div",{className:"mt-3 text-sm font-medium text-[var(--ui-ink-strong)]",children:ie(t.label)??"Candidate pattern"}),a.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:ie(t.description)??"Forge needs more paired meals and check-ins to harden this signal."})]},String(t.key??n))):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 pt({experiments:e}){return a.jsxs(z,{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(Da,{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,n)=>a.jsxs(D,{children:[a.jsx("div",{className:"text-sm font-medium text-[var(--ui-ink-strong)]",children:ie(t.title)??"Nutrition experiment"}),a.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:ie(t.hypothesis)??ie(t.intervention)??"No hypothesis recorded."})]},String(t.id??n))),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 xt({view:e}){const t=e.dataQuality,n=e.todayLedger;return a.jsxs(z,{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($,{tone:"meta",children:[e.summary.dataQualityScore.toFixed(0),"% coverage"]})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[a.jsx(bt,{label:"Source confidence",value:t.sourceConfidence,children:"Food parsing stays candidate-based until accepted; wearable burn is treated as a trend input."}),a.jsxs(D,{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($,{tone:"signal",children:r},r)):a.jsx("span",{className:"text-sm text-[var(--ui-ink-soft)]",children:"Core evidence loop is covered."})})]}),a.jsxs(D,{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:[n.unconfirmedCount," unconfirmed candidate",n.unconfirmedCount===1?"":"s"]})]})]})]})}function bt({label:e,value:t,children:n}){return a.jsxs(D,{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:n})]})}function R(e,t,n){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}),n?a.jsx("span",{className:"text-xs text-[var(--ui-ink-faint)]",children:n}):null]})}function la({values:e,label:t="Show calorie and macro formulas"}){const r=((e==null?void 0:e.sex)??"male")==="male"?"+ 5":"- 161",s=(e==null?void 0:e.proteinFactor)!=null?`${e.proteinFactor.toFixed(1)}g/kg`:"1.6-2.0g/kg";return a.jsx(de,{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:[R("Mifflin-St Jeor BMR",`10 x weight kg + 6.25 x height cm - 5 x age ${r}`,`Current formula value: ${i(e==null?void 0:e.bmrKcal)} kcal/day.`),R("Resting calories","HealthKit basal/resting kcal when present, otherwise BMR",`Using: ${i(e==null?void 0:e.restingKcal)} kcal/day${e!=null&&e.restingSource?` (${e.restingSource})`:""}.`),R("Maintenance calories","resting calories + active calories",`${i(e==null?void 0:e.restingKcal)} + ${i(e==null?void 0:e.activeKcal)} = ${i(e==null?void 0:e.maintenanceKcal)} kcal/day.`),R("Objective adjustment","weekly change kg x 7700 kcal/kg / 7",`Weekly rate ${W(e==null?void 0:e.weeklyRateKg,2)} kg/week gives ${W(e==null?void 0:e.dailyAdjustmentKcal)} kcal/day.`),R("Daily calorie target","max(sex floor, maintenance + objective adjustment)",`Floor ${i(e==null?void 0:e.calorieFloor)} kcal; target ${i(e==null?void 0:e.calorieTarget)} kcal/day.`),R("Protein target",`min(reference weight x ${s}, 45% of kcal / 4)`,`Reference ${i(e==null?void 0:e.proteinReferenceWeightKg,1)} kg; target ${i(e==null?void 0:e.proteinGrams)} g/day.`),R("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 ${i(e==null?void 0:e.fatGrams)} g/day.`),R("Carbohydrate target","(calorie target - protein g x 4 - fat g x 9) / 4",`Target ${i(e==null?void 0:e.carbohydrateGrams)} g/day. The 130g DRI is shown as reference, not forced if it breaks calories.`),R("Fiber target","14g per 1000 kcal; adult sex/age AI shown as reference",`Target ${i(e==null?void 0:e.fiberGrams)} g/day; energy-adjusted ${i(e==null?void 0:e.fiberEnergyAdjustedGrams)} g/day; adult AI reference ${i(e==null?void 0:e.fiberDriGrams)} g/day.`),R("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 ca(e,t){var r;if(!e)return null;const n=e.match(new RegExp(`${t}=([^;]+)`));return((r=n==null?void 0:n[1])==null?void 0:r.trim())??null}function ce(e,t){const n=typeof e=="string"?Number(e):A(e);return typeof n=="number"&&Number.isFinite(n)?n:t}function ft(e){return ca(e.target.notes,"sex")==="female"?"female":"male"}function vt(e){return ce(ca(e.target.notes,"age_years"),35)}function p(e,t,n,r,s,d){return{id:e,label:t,target:typeof n=="number"?Te(n):n,unit:r,note:s,source:d}}function Te(e){return Number.isFinite(e)?Math.abs(e)>=100?e.toFixed(0):e.toFixed(1).replace(/\.0$/,""):"n/a"}function se(e,t){return`${Te(e)}-${Te(t)}`}function yt(e,t,n,r){const s=Math.round(n/1e3*14);return r>0?r:s}function jt({calorieTarget:e,currentWeightKg:t,protein:n,savedFat:r}){const s=Math.max(0,(e-n*4)/9),d=Math.max(0,Math.min(s,e*.35/9,Math.max(t*.6,e*.25/9))),g=r??d;return{carbs:Math.max(0,(e-n*4-g*9)/4),fat:g}}function kt(e,t){return e==="male"?t>=51?14:17:t>=51?11:12}function Nt(e,t){const n=t>70,r=t>=51;return[p("vitamin_a","Vitamin A",e==="male"?900:700,"ug RAE","Retinol activity equivalent target.","NASEM DRI"),p("vitamin_c","Vitamin C",e==="male"?90:75,"mg","Adult RDA.","NASEM DRI"),p("vitamin_d","Vitamin D",n?20:15,"ug","Assumes limited sun exposure; older adults need more.","NASEM DRI"),p("vitamin_e","Vitamin E",15,"mg alpha-tocopherol","Adult RDA.","NASEM DRI"),p("vitamin_k","Vitamin K",e==="male"?120:90,"ug","Adult AI.","NASEM DRI"),p("thiamin_b1","Thiamin B1",e==="male"?1.2:1.1,"mg","Adult RDA.","NASEM DRI"),p("riboflavin_b2","Riboflavin B2",e==="male"?1.3:1.1,"mg","Adult RDA.","NASEM DRI"),p("niacin_b3","Niacin B3",e==="male"?16:14,"mg NE","Adult RDA.","NASEM DRI"),p("vitamin_b6","Vitamin B6",r?e==="male"?1.7:1.5:1.3,"mg","RDA rises after 50.","NASEM DRI"),p("folate","Folate",400,"ug DFE","Adult RDA.","NASEM DRI"),p("vitamin_b12","Vitamin B12",2.4,"ug","Adult RDA.","NASEM DRI"),p("pantothenic_acid","Pantothenic acid",5,"mg","Adult AI.","NASEM DRI"),p("biotin","Biotin",30,"ug","Adult AI.","NASEM DRI"),p("choline","Choline",e==="male"?550:425,"mg","Adult AI.","NASEM DRI")]}function wt(e,t){const n=t>70||e==="female"&&t>=51?1200:1e3,r=e==="male"?t>=31?420:400:t>=31?320:310,s=e==="male"?t>=51?30:35:t>=51?20:25,d=t>=71?1800:t>=51?2e3:2300;return[p("calcium","Calcium",n,"mg","Bone and muscle target; higher for older adults and women 51+.","NASEM DRI"),p("iron","Iron",e==="female"&&t<=50?18:8,"mg","Menstruating-age female target is higher.","NASEM DRI"),p("magnesium","Magnesium",r,"mg","Adult RDA.","NASEM DRI"),p("phosphorus","Phosphorus",700,"mg","Adult RDA.","NASEM DRI"),p("zinc","Zinc",e==="male"?11:8,"mg","Adult RDA.","NASEM DRI"),p("iodine","Iodine",150,"ug","Adult RDA.","NASEM DRI"),p("selenium","Selenium",55,"ug","Adult RDA.","NASEM DRI"),p("copper","Copper",.9,"mg","Adult RDA.","NASEM DRI"),p("manganese","Manganese",e==="male"?2.3:1.8,"mg","Adult AI.","NASEM DRI"),p("chromium","Chromium",s,"ug","Adult AI.","NASEM DRI"),p("molybdenum","Molybdenum",45,"ug","Adult RDA.","NASEM DRI"),p("fluoride","Fluoride",e==="male"?4:3,"mg","Adult AI.","NASEM DRI"),p("chloride","Chloride",d,"mg","Adult AI.","NASEM DRI"),p("potassium","Potassium",e==="male"?3400:2600,"mg","Current adult AI for non-pregnant adults.","NASEM DRI"),p("sodium_limit","Sodium ceiling",2300,"mg max","Default daily ceiling unless medically individualized.","U.S. Dietary Guidelines")]}function Ct(e){const t=ft(e),n=vt(e),r=ce(e.weightTrend.latestWeightKg,80),s=Math.max(1,ce(e.target.calorieTarget,2200)),d=ce(e.target.proteinGramsTarget,r*1.8),{carbs:g,fat:l}=jt({calorieTarget:s,currentWeightKg:r,protein:d,savedFat:A(e.target.fatGramsTarget)}),o=yt(t,n,s,ce(e.target.fiberGramsTarget,0)),c=A(e.energyModel.activeBurnKcal)??A(e.energyModel.activeEnergyCalories)??null,w=A(e.energyModel.movementCaloriesKcal),b=A(e.energyModel.restingEnergyCalories);return da({sex:t,ageYears:n,currentWeightKg:r,calorieTarget:s,proteinGramsTarget:d,carbohydrateGramsTarget:g,fatGramsTarget:l,fiberGramsTarget:o,activeBurnKcal:c,movementCaloriesKcal:w,restingEnergyKcal:b})}function da(e){const{sex:t,ageYears:n,currentWeightKg:r,calorieTarget:s,proteinGramsTarget:d,carbohydrateGramsTarget:g,fatGramsTarget:l,fiberGramsTarget:o,activeBurnKcal:c,movementCaloriesKcal:w,restingEnergyKcal:b}=e,x=c!=null?Math.min(4,Math.max(.1,c/500)):null,m=x!=null?x*.4:null,S=x!=null?x*.8:null,E=m!=null?m*500:null,M=S!=null?S*1e3:null,_=m!=null?m*78:null,T=S!=null?S*312:null,L=c!=null?c*7/7700:null;return{profile:{sex:t,ageYears:n,currentWeightKg:r,calorieTarget:s,activeBurnKcal:c,movementCaloriesKcal:w,restingEnergyKcal:b},macros:[p("calories","Calories",s,"kcal","Plan target from BMR, active burn, and chosen weekly rate.","Forge plan"),p("protein","Protein",d,"g","Higher than the population RDA to preserve lean mass during weight change.","ISSN + Forge plan"),p("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"),p("fat","Total fat",l,"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"),p("fiber","Fiber",o,"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"),p("saturated_fat","Saturated fat",s*.1/9,"g max","Keep below 10% of energy.","U.S. Dietary Guidelines"),p("added_sugar","Added sugar",s*.1/4,"g max","Keep below 10% of energy; lower is better when feasible.","U.S. Dietary Guidelines"),p("linoleic_acid","Linoleic acid",kt(t,n),"g","Essential n-6 fatty acid AI.","NASEM DRI"),p("ala","ALA omega-3",t==="male"?1.6:1.1,"g","Essential n-3 fatty acid AI.","NASEM DRI"),p("water","Total water",t==="male"?3.7:2.7,"L","All beverages and food water before extra training replacement.","NASEM DRI")],vitamins:Nt(t,n),minerals:wt(t,n),sportLosses:[p("training_time","Estimated training time",x??"n/a","h/day","Derived from active burn at roughly 500 kcal/h.","Forge sport-loss model"),p("sweat_fluid","Expected sweat fluid",m!=null&&S!=null?se(m,S):"n/a","L/day","Planning range uses 0.4-0.8 L/h; measure body mass change to calibrate.","ACSM"),p("sweat_sodium","Expected sweat sodium",E!=null&&M!=null?se(E,M):"n/a","mg/day","Sodium varies widely; this uses a conservative range around common sweat sodium values.","ACSM + Sports Medicine review"),p("sweat_potassium","Expected sweat potassium",_!=null&&T!=null?se(_,T):"n/a","mg/day","Potassium is usually much smaller than sodium but useful for long/hot sessions.","Sports Medicine review"),p("gross_sport_equivalent","Gross sport burn equivalent",L??"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:x,fluidLossLiters:m!=null&&S!=null?se(m,S):"n/a",sodiumLossMg:E!=null&&M!=null?se(E,M):"n/a",potassiumLossMg:_!=null&&T!=null?se(_,T):"n/a",grossSportWeightEquivalentKgPerWeek:L}}}function Ae({rows:e,compact:t=!1}){return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"grid gap-2 md:hidden",children:e.map(n=>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:n.label}),a.jsxs("div",{className:"shrink-0 text-right text-sm font-semibold text-[var(--ui-ink)]",children:[n.target,a.jsx("div",{className:"text-xs font-normal text-[var(--ui-ink-faint)]",children:n.unit})]})]}),a.jsx("p",{className:"min-w-0 break-words text-xs leading-5 text-[var(--ui-ink-muted)]",children:n.note}),t?null:a.jsx($,{tone:"meta",wrap:!0,className:"justify-self-start",children:n.source})]},n.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(n=>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:n.label}),a.jsxs("td",{className:"px-4 py-3 text-[var(--ui-ink)]",children:[a.jsx("span",{className:"font-semibold",children:n.target})," ",a.jsx("span",{className:"text-[var(--ui-ink-faint)]",children:n.unit})]}),a.jsx("td",{className:"px-4 py-3 text-[var(--ui-ink-muted)]",children:n.note}),t?null:a.jsx("td",{className:"px-4 py-3",children:a.jsx($,{tone:"meta",children:n.source})})]},n.id))})]})})})]})}function le({title:e,description:t,children:n}){return a.jsxs(D,{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})]}),n]})}function Ft({view:e}){const t=Ct(e),n=e.target.weeklyRateGoalKg??null,r=n!=null&&Number.isFinite(n)?n*7700/7:null,s=t.profile.restingEnergyKcal,d=t.profile.activeBurnKcal,g=s!=null&&d!=null?s+d:null,l=e.target.bodyGoal??"maintain",o=l.includes("lose")?2:l.includes("gain")?1.8:1.6,c=m=>{var M;const S=(M=t.macros.find(_=>_.id===m))==null?void 0:M.target,E=Number(S);return Number.isFinite(E)?E:null},w=t.profile.sex==="male"?t.profile.ageYears>=51?30:38:t.profile.ageYears>=51?21:25,b=Math.round(t.profile.calorieTarget/1e3*14),x=t.sportSummary.grossSportWeightEquivalentKgPerWeek!=null?`${t.sportSummary.grossSportWeightEquivalentKgPerWeek.toFixed(2)} kg/week`:"n/a";return a.jsx("section",{className:"grid gap-4",children:a.jsxs(z,{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(Ia,{className:"size-4 text-[var(--ui-accent)]"}),"Macro And Micronutrient Targets",a.jsx(la,{values:{sex:t.profile.sex,ageYears:t.profile.ageYears,currentWeightKg:t.profile.currentWeightKg,bmrKcal:null,restingKcal:s,restingSource:s!=null?"saved HealthKit basal/resting or plan value":null,activeKcal:d,maintenanceKcal:g,weeklyRateKg:n,dailyAdjustmentKcal:r,calorieTarget:t.profile.calorieTarget,calorieFloor:t.profile.sex==="male"?1500:1200,proteinReferenceWeightKg:null,proteinFactor:o,proteinGrams:c("protein"),fatGrams:c("fat"),carbohydrateGrams:c("carbohydrate"),fiberGrams:c("fiber"),fiberEnergyAdjustedGrams:b,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($,{tone:"signal",children:[t.profile.calorieTarget.toFixed(0)," kcal"]}),a.jsxs($,{tone:"meta",children:[t.profile.sex,", ",t.profile.ageYears.toFixed(0),"y"]})]})]}),a.jsxs("div",{className:"mt-5 grid gap-4 2xl:grid-cols-[minmax(0,1fr)_minmax(320px,0.58fr)]",children:[a.jsxs("div",{className:"grid gap-4",children:[a.jsx(le,{title:"All macro targets",description:"Calories, protein, carbs, fat, fiber, sugar ceiling, saturated fat ceiling, essential fats, and water.",children:a.jsx(Ae,{rows:t.macros,compact:!0})}),a.jsx(le,{title:"Vitamins",description:"Adult daily vitamin targets from DRI values, adjusted for sex and age where the reference differs.",children:a.jsx(Ae,{rows:t.vitamins})})]}),a.jsxs("div",{className:"grid content-start gap-4",children:[a.jsxs(le,{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(N,{label:"Active burn",value:t.profile.activeBurnKcal!=null?`${t.profile.activeBurnKcal.toFixed(0)} kcal`:"n/a"}),a.jsx(N,{label:"Sport equivalent",value:x}),a.jsx(N,{label:"Sweat fluid",value:`${t.sportSummary.fluidLossLiters} L`}),a.jsx(N,{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(ia,{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(le,{title:"Minerals & oligoelements",description:"Daily mineral and trace-element targets including sodium ceiling and potassium AI.",children:a.jsx(Ae,{rows:t.minerals,compact:!0})}),a.jsx(le,{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(m=>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:[m.id==="sweat_fluid"?a.jsx(La,{className:"size-4 text-[var(--ui-accent)]"}):a.jsx(Pa,{className:"size-4 text-[var(--ui-accent)]"}),m.label]}),a.jsx("p",{className:"mt-1 text-xs text-[var(--ui-ink-faint)]",children:m.note})]}),a.jsxs("div",{className:"shrink-0 text-right text-sm font-semibold text-[var(--ui-ink)]",children:[m.target,a.jsx("div",{className:"text-xs font-normal text-[var(--ui-ink-faint)]",children:m.unit})]})]},m.id))})})]})]})]})})}function ee(e,t){var r;if(!e)return null;const n=e.match(new RegExp(`${t}=([^;]+)`));return((r=n==null?void 0:n[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 ua(e,t){if(t==="maintain")return 0;const n=t==="gain"?.0025:.005,r=t==="gain"?.1:.2,s=t==="gain"?.35:Math.max(.5,e*.01);return Math.min(s,Math.max(r,e*n))}function ga(e,t){return t==="gain"?e*1.03:t==="maintain"?e:e*.95}function ma(e){return e.toFixed(1)}function Mt(e,t){return e==="male"?t>=51?30:38:t>=51?21:25}function Ze(e,t){const n=e/100;return n>0?t*n*n:null}function Gt(e){const t=e.goalMode==="lose"&&e.goalWeightKg!=null?Math.min(e.currentWeightKg,e.goalWeightKg):e.currentWeightKg,n=Ze(e.heightCm,30),r=Ze(e.heightCm,25);if(n!=null&&r!=null&&e.currentWeightKg>n){const s=r+(e.currentWeightKg-r)*.25;return Math.min(t,s)}return t}function St(e,t){const n=ae(e.currentWeightKg)??80;return{...e,goalMode:t,goalWeightKg:ma(ga(n,t)),weeklyRateKg:ua(n,t).toFixed(2)}}function Ee(e){const t=A(e.weightTrend.latestWeightKg),n=e.target,r=ee(n.notes,"sex"),s=ee(n.notes,"age_years"),d=ee(n.notes,"height_cm"),g=A(e.energyModel.activeBurnKcal)??A(e.energyModel.activeEnergyCalories)??A(e.energyModel.movementCaloriesKcal)??A(ee(n.notes,"activity_kcal"))??0,l=A(e.energyModel.restingEnergyCalories)??A(ee(n.notes,"resting_kcal"))??null,o=n.bodyGoal??"",c=o.includes("gain")?"gain":o.includes("maintain")?"maintain":"lose",w=n.weightGoalKg??n.goalBodyWeightKg??null,b=t??80;return{goalMode:c,sex:r==="female"?"female":"male",ageYears:ae(s)?String(s):"",heightCm:ae(d)?String(d):"",currentWeightKg:t?t.toFixed(1):"",goalWeightKg:w?String(w):ma(ga(b,c)),weeklyRateKg:n.weeklyRateGoalKg!==null&&n.weeklyRateGoalKg!==void 0?String(Math.abs(n.weeklyRateGoalKg)):ua(b,c).toFixed(2),activeCaloriesKcal:g.toFixed(0),restingCaloriesKcal:l!=null?l.toFixed(0):"",dietStyle:n.dietStyle??""}}function Kt(e){const t=ae(ee(e.target.notes,"age_years"))!=null,n=ae(ee(e.target.notes,"height_cm"))!=null,r=A(e.weightTrend.latestWeightKg)!=null,s=typeof e.target.bodyGoal=="string"&&e.target.bodyGoal.trim().length>0&&e.target.calorieTarget>0&&e.target.proteinGramsTarget>0;return t&&n&&r&&s}function At(e){const t=e.energyModel;return`This is the default active allowance used when today has no same-day workout, movement, step, or active-energy evidence. ${t.energySourceConfidence==="healthkit_daily_active_energy"?"HealthKit daily active energy is the active-burn source; workout and movement values are only visible evidence and are not added again.":t.energySourceConfidence==="workout_movement_fallback"?"HealthKit daily active energy is missing, so active burn already equals workout average plus movement-trip average.":"No measured active-burn stream is available, so Forge is using the plan/default estimate."} Current evidence: active burn ${i(t.activeBurnKcal)} kcal/day, workout average ${i(t.workoutEnergyKcal)} kcal/day, movement average ${i(t.movementCaloriesKcal)} kcal/day, today's workout ${i(t.todayWorkoutEnergyKcal)} kcal, today's movement ${i(t.todayMovementCaloriesKcal)} kcal.`}function ha(e){const t=Number(e.currentWeightKg)||80,n=Number(e.heightCm)||178,r=Number(e.ageYears)||35,s=ae(e.goalWeightKg),d=Math.max(0,Number(e.activeCaloriesKcal)||0),g=ae(e.restingCaloriesKcal),l=e.sex==="male"?5:-161,o=10*t+6.25*n-5*r+l,c=g??o,w=c+d,b=Math.abs(Number(e.weeklyRateKg)||0),x=e.goalMode==="lose"?-b:e.goalMode==="gain"?b:0,m=x*7700/7,S=e.sex==="male"?1500:1200,E=Math.round(w+m),M=Math.max(S,E),_=Gt({currentWeightKg:t,goalWeightKg:s,heightCm:n,goalMode:e.goalMode}),T=e.goalMode==="lose"?2:e.goalMode==="gain"?1.8:1.6,L=Math.round(_*T),B=Math.floor(M*.45/4),P=Math.max(1,Math.min(L,B)),H=_*.6,te=M*.25/9,J=Math.max(0,(M-P*4)/9),O=Math.max(0,Math.floor(Math.min(J,M*.35/9,Math.max(H,te)))),U=Math.max(0,Math.floor((M-P*4-O*9)/4)),ne=Math.round(M/1e3*14),re=Mt(e.sex,r),oe=ne,Z=Math.round(M*.1/9),Q=Math.round(M*.1/4);return{bmr:Math.round(o),restingCalories:Math.round(c),restingSource:g!=null?"HealthKit basal/resting":"Mifflin-St Jeor",activeCalories:Math.round(d),maintenanceCalories:Math.round(w),plannedCalorieTarget:E,minimumCalorieFloor:S,weeklyRateGoalKg:x,dailyEnergyAdjustment:Math.round(m),calorieTarget:M,proteinReferenceWeight:Math.round(_*10)/10,proteinGramsTarget:P,carbohydrateGramsTarget:U,fatGramsTarget:O,fiberGramsTarget:oe,fiberEnergyAdjustedGrams:ne,fiberDriGrams:re,saturatedFatLimitGrams:Z,addedSugarLimitGrams:Q}}function Et(e){const t=[],n=Number(e.ageYears),r=Number(e.heightCm),s=Number(e.currentWeightKg),d=Number(e.goalWeightKg),g=Number(e.weeklyRateKg),l=e.activeCaloriesKcal.trim()?Number(e.activeCaloriesKcal):Number.NaN,o=e.restingCaloriesKcal.trim()?Number(e.restingCaloriesKcal):null;return(!Number.isFinite(n)||n<13||n>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(s)||s<30||s>300)&&t.push("- Enter current weight in kg. Use the latest known body measure as the starting state."),e.goalMode!=="maintain"&&(!Number.isFinite(d)||d<30||d>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,s*.02)&&t.push("- The weekly rate is very aggressive. Choose a slower default unless this is a supervised plan."),(!Number.isFinite(l)||l<0||l>3e3)&&t.push("- Enter average active calories per day. Zero is valid only when Forge has no activity evidence."),o!=null&&(!Number.isFinite(o)||o<900||o>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 _t(e){const t=ha(e),n=Number(e.goalWeightKg);return{calorieTarget:t.calorieTarget,proteinGramsTarget:t.proteinGramsTarget,fiberGramsTarget:t.fiberGramsTarget,carbohydrateGramsTarget:t.carbohydrateGramsTarget,fatGramsTarget:t.fatGramsTarget,weightGoalKg:Number.isFinite(n)?n: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 $t({open:e,onOpenChange:t,view:n,value:r,onChange:s,onSubmit:d,pending:g,error:l}){const o=F.useMemo(()=>ha(r),[r]),c=F.useMemo(()=>da({sex:r.sex,ageYears:Number(r.ageYears)||35,currentWeightKg:Number(r.currentWeightKg)||80,calorieTarget:o.calorieTarget,proteinGramsTarget:o.proteinGramsTarget,carbohydrateGramsTarget:o.carbohydrateGramsTarget,fatGramsTarget:o.fatGramsTarget,fiberGramsTarget:o.fiberGramsTarget,activeBurnKcal:o.activeCalories,movementCaloriesKcal:A(n.energyModel.movementCaloriesKcal),restingEnergyKcal:o.restingCalories}),[o,r,n.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:(b,x)=>a.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[a.jsx(y,{label:"Sex",children:a.jsx(Ve,{value:b.sex,onChange:m=>x({sex:m}),options:[{value:"male",label:"Male"},{value:"female",label:"Female"}]})}),a.jsx(y,{label:"Age",children:a.jsx(k,{inputMode:"numeric",value:b.ageYears,onChange:m=>x({ageYears:m.target.value}),placeholder:"35"})}),a.jsx(y,{label:"Height cm",children:a.jsx(k,{inputMode:"decimal",value:b.heightCm,onChange:m=>x({heightCm:m.target.value}),placeholder:"178"})}),a.jsx(y,{label:"Current weight kg",children:a.jsx(k,{inputMode:"decimal",value:b.currentWeightKg,onChange:m=>x({currentWeightKg:m.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:(b,x)=>a.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[a.jsx("div",{className:"md:col-span-2",children:a.jsx(Ve,{columns:3,value:b.goalMode,onChange:m=>x(St(b,m)),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(y,{label:"Target weight kg",hint:"Filled from the objective; change it anytime.",children:a.jsx(k,{inputMode:"decimal",value:b.goalWeightKg,onChange:m=>x({goalWeightKg:m.target.value}),placeholder:"75.0"})}),a.jsx(y,{label:"Weekly change kg",hint:"Loss/gain rate is converted to kcal/day with the 7700 kcal/kg planning model.",children:a.jsx(k,{inputMode:"decimal",value:b.weeklyRateKg,onChange:m=>x({weeklyRateKg:m.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:(b,x)=>a.jsxs("div",{className:"grid gap-4",children:[a.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[a.jsx(y,{label:"Resting calories/day",hint:`Forge uses HealthKit basal energy when present, otherwise Mifflin-St Jeor BMR. Current formula value: ${o.bmr} kcal.`,children:a.jsx(k,{inputMode:"decimal",value:b.restingCaloriesKcal,onChange:m=>x({restingCaloriesKcal:m.target.value}),placeholder:String(o.bmr)})}),a.jsx(y,{label:"Average active calories/day",hint:At(n),children:a.jsx(k,{inputMode:"decimal",value:b.activeCaloriesKcal,onChange:m=>x({activeCaloriesKcal:m.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(N,{label:o.restingSource,value:`${o.restingCalories} kcal`}),a.jsx(N,{label:"Maintenance",value:`${o.maintenanceCalories} kcal`}),a.jsx(N,{label:"Daily adjustment",value:`${o.dailyEnergyAdjustment>0?"+":""}${o.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:(b,x)=>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(la,{values:{sex:b.sex,ageYears:Number(b.ageYears)||null,currentWeightKg:Number(b.currentWeightKg)||null,heightCm:Number(b.heightCm)||null,bmrKcal:o.bmr,restingKcal:o.restingCalories,restingSource:o.restingSource,activeKcal:o.activeCalories,maintenanceKcal:o.maintenanceCalories,weeklyRateKg:o.weeklyRateGoalKg,dailyAdjustmentKcal:o.dailyEnergyAdjustment,calorieTarget:o.calorieTarget,calorieFloor:o.minimumCalorieFloor,proteinReferenceWeightKg:o.proteinReferenceWeight,proteinFactor:b.goalMode==="lose"?2:b.goalMode==="gain"?1.8:1.6,proteinGrams:o.proteinGramsTarget,fatGrams:o.fatGramsTarget,carbohydrateGrams:o.carbohydrateGramsTarget,fiberGrams:o.fiberGramsTarget,fiberEnergyAdjustedGrams:o.fiberEnergyAdjustedGrams,fiberDriGrams:o.fiberDriGrams}})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-4 xl:grid-cols-7",children:[a.jsx(N,{label:"Calories",value:`${o.calorieTarget}`}),a.jsx(N,{label:"Protein",value:`${o.proteinGramsTarget}g`}),a.jsx(N,{label:"Carbs",value:`${o.carbohydrateGramsTarget}g`}),a.jsx(N,{label:"Fat",value:`${o.fatGramsTarget}g`}),a.jsx(N,{label:"Fiber",value:`${o.fiberGramsTarget}g`}),a.jsx(N,{label:"Sat fat max",value:`${o.saturatedFatLimitGrams}g`}),a.jsx(N,{label:"Added sugar max",value:`${o.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($,{tone:"meta",children:[c.vitamins.length," vitamins"]}),a.jsxs($,{tone:"meta",children:[c.minerals.length," minerals"]}),a.jsxs($,{tone:"signal",children:[c.sportSummary.fluidLossLiters," L sweat"]})]})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[a.jsx(N,{label:"Sport sodium loss",value:`${c.sportSummary.sodiumLossMg} mg`}),a.jsx(N,{label:"Sport potassium loss",value:`${c.sportSummary.potassiumLossMg} mg`}),a.jsx(N,{label:"Water baseline",value:r.sex==="male"?"3.7 L":"2.7 L"}),a.jsx(N,{label:"Essential fats",value:r.sex==="male"?"17g LA / 1.6g ALA":"12g LA / 1.1g ALA"})]})]}),a.jsx(y,{label:"Diet style or constraints",children:a.jsx(ve,{value:b.dietStyle,onChange:m=>x({dietStyle:m.target.value}),placeholder:"Mediterranean, high protein, no lactose, low FODMAP trial..."})})]})}];return a.jsx(je,{open:e,onOpenChange:t,eyebrow:"Weight plan",title:"Set weight objective",description:"Build an editable calorie and macro plan.",value:r,onChange:s,steps:w,onSubmit:d,submitLabel:"Save plan",pending:g,pendingLabel:"Saving plan",error:l,draftPersistenceKey:"weight-loss-plan"})}const Tt={tsp:5,tbsp:15,cup:240};function fe(){return{mealLabel:"Meal",notes:"",source:"search",selectedItems:[]}}function G(e,t,n){return typeof e!="number"||!Number.isFinite(e)?null:xa(n)==="grams"?e:t>0?Math.round(e/t*10)/10:e}function Dt(e){const t=Number.isFinite(e.quantity)&&e.quantity>0?e.quantity:1,n=e.unit??"serving",r=n==="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:n,servingGrams:r??null,calories:G(e.calories,t,n),proteinGrams:G(e.proteinGrams,t,n),carbohydrateGrams:G(e.carbohydrateGrams,t,n),fatGrams:G(e.fatGrams,t,n),fiberGrams:G(e.fiberGrams,t,n),sugarGrams:G(e.sugarGrams,t,n),sodiumMg:G(e.sodiumMg,t,n),potassiumMg:G(e.potassiumMg,t,n),caffeineMg:G(e.caffeineMg,t,n),alcoholGrams:G(e.alcoholGrams,t,n),glycemicIndex:e.glycemicIndex??null,novaGroup:e.novaGroup??null,tags:e.tags??[],confidence:e.confidence??null}}function It(e,t,n){const r=Number.isFinite(e.quantity)&&e.quantity>0?e.quantity:1,s=e.unit??"serving",d=s==="grams"||s==="g"?e.grams??r:e.grams!=null&&r>0?e.grams/r:e.grams;return{id:e.foodId??`${n}_${t}_${Date.now()}`,source:n,sourceId:e.foodId??null,name:e.name,brand:e.brand??null,barcode:null,servingLabel:s,servingGrams:d??null,calories:G(e.calories,r,s),proteinGrams:G(e.proteinGrams,r,s),carbohydrateGrams:G(e.carbohydrateGrams,r,s),fatGrams:G(e.fatGrams,r,s),fiberGrams:G(e.fiberGrams,r,s),sugarGrams:G(e.sugarGrams,r,s),sodiumMg:G(e.sodiumMg,r,s),potassiumMg:G(e.potassiumMg,r,s),caffeineMg:G(e.caffeineMg,r,s),alcoholGrams:G(e.alcoholGrams,r,s),glycemicIndex:e.glycemicIndex??null,novaGroup:e.novaGroup??null,tags:e.tags??[],confidence:e.confidence??null}}function Lt(e){if(!e)return null;const n=e.toLowerCase().replace(",",".").match(/(\d+(?:\.\d+)?)\s*(kg|g|gram|grams|ml|l)\b/);if(!n)return null;const r=Number(n[1]);if(!Number.isFinite(r)||r<=0)return null;const s=n[2];return s==="kg"||s==="l"?r*1e3:r}function ue(e){return typeof e.servingGrams=="number"&&Number.isFinite(e.servingGrams)&&e.servingGrams>0?e.servingGrams:Lt(e.servingLabel)}function Pt(e){const t=ue(e);return t!=null?`${i(t)} g`:e.servingLabel??"serving"}function pa(e){const t=Number(e.amount)||0;if(t<=0)return null;const n=ue(e.food);return e.unit==="grams"?t:e.unit==="tsp"||e.unit==="tbsp"||e.unit==="cup"?t*Tt[e.unit]:n!=null?t*n:null}function Xe(e){return!(e.unit==="grams"||e.unit==="tsp"||e.unit==="tbsp"||e.unit==="cup")||ue(e.food)!=null?null:"Add base grams before using grams or household measures. Without a denominator, Forge will not guess a ratio."}function xa(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 Rt(e){switch(e){case"manual":case"search":case"barcode":case"chatgpt":case"photo":case"saved_meal":return e;default:return"manual"}}function Wt(e){return{mealLabel:e.mealLabel??"Meal",notes:e.notes??"",loggedAt:e.loggedAt,dayKey:e.dayKey,source:Rt(e.source),selectedItems:e.items.map(t=>({localId:t.id,food:Dt(t),amount:String(t.quantity||1),unit:t.unit??"serving"}))}}function Bt(e,t=e.source??"manual"){return{mealLabel:e.mealLabel??"Meal",notes:e.notes??"",loggedAt:e.loggedAt,dayKey:e.dayKey,source:e.source??"manual",selectedItems:e.items.map((n,r)=>({localId:`${t}-${r}-${Date.now()}`,food:It(n,r,t),amount:String(n.quantity||1),unit:xa(n.unit)}))}}function ba(){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 Ht(){return{mealLabel:"Meal",notes:"",source:"manual",selectedItems:[{localId:`custom-${Date.now()}`,food:ba(),amount:"100",unit:"grams"}]}}function qt({open:e,onOpenChange:t,value:n,onChange:r,foodResults:s,searchPending:d,chatGptPending:g=!1,chatGptError:l=null,logPending:o,onSearch:c,onParseWithChatGpt:w,onSubmit:b,mode:x="create",intent:m="search",initialStepId:S}){const[E,M]=F.useState(""),[_,T]=F.useState(""),[L,B]=F.useState(null),P=F.useMemo(()=>Yt(n.selectedItems),[n.selectedItems]),H=f=>r({...n,...f}),te=f=>{H({selectedItems:[...n.selectedItems,{localId:`${f.id}-${Date.now()}`,food:f,amount:"1",unit:"serving"}]}),B(null)},J=()=>{te(ba())},O=async()=>{const f=_.trim();!f||!w||(await w(f),T(""))},U=(f,v)=>{H({selectedItems:n.selectedItems.map(j=>j.localId===f?{...j,...v}:j)})},ne=(f,v)=>{H({selectedItems:n.selectedItems.map(j=>j.localId===f?{...j,food:{...j.food,...v}}:j)})},re=f=>{H({selectedItems:n.selectedItems.filter(v=>v.localId!==f)})},oe=async()=>{n.selectedItems.length!==0&&await b()},Z=a.jsxs(D,{className:"grid gap-3",children:[a.jsx(y,{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(ve,{value:_,onChange:f=>T(f.target.value),placeholder:"Example: 2 eggs, 150g Greek yogurt, one banana, and a cappuccino..."})}),l?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:l}):null,a.jsxs(K,{type:"button",variant:m==="chatgpt"?"primary":"secondary",pending:g,pendingLabel:"Parsing",disabled:!_.trim()||!w,onClick:()=>void O(),children:[a.jsx(ta,{className:"size-4"}),"Parse with ChatGPT"]})]}),Q=a.jsx(D,{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:J,children:[a.jsx(De,{className:"size-4"}),"Add custom"]})]})}),V=m==="chatgpt"?[Z,Q]:[Q,Z],ge=[{id:"search",eyebrow:m==="chatgpt"?"ChatGPT food parser":"Food",title:m==="chatgpt"?"Describe the meal, then review every item":"Search, create, or ask ChatGPT",description:m==="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(y,{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(k,{value:E,onChange:f=>M(f.target.value),placeholder:"Search eggs, yogurt, sourdough..."})}),a.jsxs(K,{type:"button",variant:"secondary",pending:d,disabled:!E.trim(),onClick:()=>c(E),children:[a.jsx(na,{className:"size-4"}),"Search"]})]}),a.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:V.map((f,v)=>a.jsx("div",{children:f},`${m}-assistant-panel-${v}`))}),L?a.jsx(Vt,{food:L,onAdd:()=>te(L)}):null,a.jsx("div",{className:"grid gap-3",children:s.map(f=>a.jsx(D,{interactive:!0,className:"p-0",children:a.jsx("button",{type:"button",className:"block w-full rounded-[22px] p-4 text-left",onClick:()=>B(f),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:f.name}),a.jsx("div",{className:"mt-1 truncate text-xs text-[var(--ui-ink-faint)]",children:[f.brand,f.servingLabel,f.source].filter(Boolean).join(" · ")})]}),a.jsxs($,{tone:"meta",children:[i(f.calories)," kcal"]})]})})},f.id))})]})},{id:"amounts",eyebrow:m==="custom"?"Custom food":"Quantity",title:m==="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:f=>a.jsxs("div",{className:"grid gap-4",children:[f.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,f.selectedItems.map(v=>a.jsxs(D,{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:v.food.name}),a.jsxs("div",{className:"text-xs text-[var(--ui-ink-faint)]",children:["Base: ",i(v.food.calories)," kcal per"," ",Pt(v.food)]})]}),a.jsxs(K,{type:"button",size:"sm",variant:"ghost",onClick:()=>re(v.localId),children:[a.jsx(sa,{className:"size-4"}),"Remove"]})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto]",children:[a.jsx(y,{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(k,{inputMode:"decimal",value:v.amount,onChange:j=>U(v.localId,{amount:j.target.value}),placeholder:"1"})}),a.jsx(y,{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:v.unit,onChange:j=>U(v.localId,{unit:j.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($,{tone:"signal",children:[i(ye(v).calories)," kcal"]})]}),Xe(v)?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:Xe(v)}):a.jsxs("div",{className:"text-xs text-[var(--ui-ink-faint)]",children:[i(Number(v.amount)||0)," ",v.unit," ="," ",i(pa(v))," g eaten; ratio ="," ",i(ye(v).scale),"x the base nutrition."]}),a.jsx(Qt,{item:v,onChange:j=>ne(v.localId,j)})]},v.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(N,{label:"Calories",value:i(P.calories)}),a.jsx(N,{label:"Protein",value:`${i(P.proteinGrams)}g`}),a.jsx(N,{label:"Carbs",value:`${i(P.carbohydrateGrams)}g`}),a.jsx(N,{label:"Fat",value:`${i(P.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:(f,v)=>a.jsxs("div",{className:"grid gap-4",children:[a.jsx(y,{label:"Meal label",labelHelp:"The label groups the edited items as breakfast, lunch, snack, dinner, or any personal meal name.",children:a.jsx(k,{value:f.mealLabel,onChange:j=>v({mealLabel:j.target.value}),placeholder:"Breakfast"})}),a.jsx(y,{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(ve,{value:f.notes,onChange:j=>v({notes:j.target.value}),placeholder:"Energy, cravings, gut comfort, training effect..."})})]})}];return a.jsx(je,{open:e,onOpenChange:t,eyebrow:"Food log",title:x==="edit"?"Edit food":"Add food",description:"Search, inspect, scale, edit nutrition parameters, and save meal items.",value:n,onChange:r,steps:ge,initialStepId:S,onSubmit:oe,submitLabel:x==="edit"?"Update meal":"Save meal",pending:o,pendingLabel:"Saving meal",resolveError:f=>f!=="search"&&n.selectedItems.length===0?"Select at least one food before saving.":null,draftPersistenceKey:`weight-loss-food-log.${x}.${m}`})}function fa(e){return{loggedAt:e.loggedAt,dayKey:e.dayKey??$e(),mealLabel:ea(e.mealLabel,"Meal"),source:e.source??"search",confirmationState:"confirmed",notes:ea(e.notes),items:e.selectedItems.map(t=>{const n=ye(t);return{foodId:zt(t),name:t.food.name,brand:t.food.brand,quantity:Number(t.amount)||1,unit:t.unit,grams:n.grams,calories:n.calories,proteinGrams:n.proteinGrams,carbohydrateGrams:n.carbohydrateGrams,fatGrams:n.fatGrams,fiberGrams:n.fiberGrams,sugarGrams:n.sugarGrams,sodiumMg:n.sodiumMg,potassiumMg:n.potassiumMg,caffeineMg:n.caffeineMg,alcoholGrams:n.alcoholGrams,novaGroup:t.food.novaGroup,tags:t.food.tags,confidence:.9}})}}function ea(e,t=""){return typeof e=="string"?e:t}function zt(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 Ot(e){return fa(e)}function Ut(e){const t=Number(e);return Number.isFinite(t)?t:null}function Qt({item:e,onChange:t}){const n=e.food,r=(s,d)=>t({[s]:Ut(d)});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(de,{label:`Explain editable food parameters for ${n.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(y,{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(k,{value:n.servingLabel??"",onChange:s=>t({servingLabel:s.target.value||null}),placeholder:"100 g"})}),a.jsx(y,{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(k,{inputMode:"decimal",value:n.servingGrams??"",onChange:s=>r("servingGrams",s.target.value),placeholder:"100"})}),a.jsx(y,{label:"Food name",labelHelp:"Rename the item when the database result is too generic or wrong.",children:a.jsx(k,{value:n.name,onChange:s=>t({name:s.target.value})})}),a.jsx(y,{label:"Brand",labelHelp:"Optional brand or preparation source, useful when the same food has different nutrition.",children:a.jsx(k,{value:n.brand??"",onChange:s=>t({brand:s.target.value||null})})})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[a.jsx(y,{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(k,{inputMode:"decimal",value:n.calories??"",onChange:s=>r("calories",s.target.value)})}),a.jsx(y,{label:"Protein g",labelHelp:"Protein grams for the base amount above. This is scaled by the same gram ratio as calories.",children:a.jsx(k,{inputMode:"decimal",value:n.proteinGrams??"",onChange:s=>r("proteinGrams",s.target.value)})}),a.jsx(y,{label:"Carbs g",labelHelp:"Carbohydrate grams for the base amount above. Carbs are training fuel after protein and fat are allocated.",children:a.jsx(k,{inputMode:"decimal",value:n.carbohydrateGrams??"",onChange:s=>r("carbohydrateGrams",s.target.value)})}),a.jsx(y,{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(k,{inputMode:"decimal",value:n.fatGrams??"",onChange:s=>r("fatGrams",s.target.value)})}),a.jsx(y,{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(k,{inputMode:"decimal",value:n.fiberGrams??"",onChange:s=>r("fiberGrams",s.target.value)})}),a.jsx(y,{label:"Sugar g",labelHelp:"Sugar grams for the base amount above. Added sugar is tracked as a ceiling, not a goal.",children:a.jsx(k,{inputMode:"decimal",value:n.sugarGrams??"",onChange:s=>r("sugarGrams",s.target.value)})}),a.jsx(y,{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(k,{inputMode:"decimal",value:n.sodiumMg??"",onChange:s=>r("sodiumMg",s.target.value)})})]})]})}function Vt({food:e,onAdd:t}){return a.jsxs(z,{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(De,{className:"size-4"}),"Add"]})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[a.jsx(N,{label:"Calories",value:i(e.calories)}),a.jsx(N,{label:"Protein",value:`${i(e.proteinGrams)}g`}),a.jsx(N,{label:"Carbs",value:`${i(e.carbohydrateGrams)}g`}),a.jsx(N,{label:"Fat",value:`${i(e.fatGrams)}g`}),a.jsx(N,{label:"Fiber",value:`${i(e.fiberGrams)}g`}),a.jsx(N,{label:"Sugar",value:`${i(e.sugarGrams)}g`}),a.jsx(N,{label:"Sodium",value:`${i(e.sodiumMg)}mg`}),a.jsx(N,{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(Ra,{className:"size-4"}),"Base grams: ",i(ue(e)),". Adjust exact intake in the next step."]})]})}function ye(e){const t=Number(e.amount)||0,n=ue(e.food),r=pa(e),s=e.unit==="serving"||e.unit==="unit",d=t<=0?0:n!=null&&r!=null?r/n:s?t:null,g=l=>d!=null&&typeof l=="number"&&Number.isFinite(l)?Math.round(l*d*10)/10:null;return{grams:r,scale:d,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 Yt(e){return e.reduce((t,n)=>{const r=ye(n);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 aa(){return{weightKg:"",waistCm:"",bodyFatPercent:"",energy:"",hunger:"",cravings:"",bloating:"",facePuffiness:"",leanness:"",notes:""}}function Jt({open:e,onOpenChange:t,value:n,onChange:r,onSubmit:s,pending:d}){const g=[{id:"body",eyebrow:"Body",title:"Measurements",description:"Add weight and body measures when you have them. Empty fields are ignored.",render:(l,o)=>a.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[a.jsx(y,{label:"Weight kg",children:a.jsx(k,{inputMode:"decimal",value:l.weightKg,onChange:c=>o({weightKg:c.target.value})})}),a.jsx(y,{label:"Waist cm",children:a.jsx(k,{inputMode:"decimal",value:l.waistCm,onChange:c=>o({waistCm:c.target.value})})}),a.jsx(y,{label:"Body fat %",children:a.jsx(k,{inputMode:"decimal",value:l.bodyFatPercent,onChange:c=>o({bodyFatPercent:c.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:(l,o)=>a.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[a.jsx(y,{label:"Energy 0-10",children:a.jsx(k,{inputMode:"decimal",value:l.energy,onChange:c=>o({energy:c.target.value})})}),a.jsx(y,{label:"Hunger 0-10",children:a.jsx(k,{inputMode:"decimal",value:l.hunger,onChange:c=>o({hunger:c.target.value})})}),a.jsx(y,{label:"Cravings 0-10",children:a.jsx(k,{inputMode:"decimal",value:l.cravings,onChange:c=>o({cravings:c.target.value})})}),a.jsx(y,{label:"Bloating 0-10",children:a.jsx(k,{inputMode:"decimal",value:l.bloating,onChange:c=>o({bloating:c.target.value})})}),a.jsx(y,{label:"Face puffiness 0-10",children:a.jsx(k,{inputMode:"decimal",value:l.facePuffiness,onChange:c=>o({facePuffiness:c.target.value})})}),a.jsx(y,{label:"Leanness 0-10",children:a.jsx(k,{inputMode:"decimal",value:l.leanness,onChange:c=>o({leanness:c.target.value})})})]})},{id:"notes",eyebrow:"Context",title:"Notes",description:"Capture anything that explains the signal.",render:(l,o)=>a.jsx(y,{label:"Notes",children:a.jsx(ve,{value:l.notes,onChange:c=>o({notes:c.target.value}),placeholder:"Sleep, sodium, workout soreness, stressful day..."})})}];return a.jsx(je,{open:e,onOpenChange:t,eyebrow:"Check-in",title:"Add body signal",description:"Add measurements, energy, gut, and appearance signals.",value:n,onChange:r,steps:g,onSubmit:s,submitLabel:"Save check-in",pending:d,pendingLabel:"Saving check-in",draftPersistenceKey:"weight-loss-checkin"})}function Zt(e){const t=n=>{const r=Number(n);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 Xt(e){const t=e.items[0]??null,n=Math.max(0,e.items.length-1);return t?`${t.name}${n>0?` + ${n} more`:""}`:e.mealLabel??"Meal"}function en(e){return e.items.slice(0,3).map(t=>{const n=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",s=t.grams!=null?`${t.grams.toFixed(0)}g`:null;return[n,r,s?`(${s})`:null].filter(Boolean).join(" ")}).filter(Boolean).join(" · ")}function an({open:e,onOpenChange:t,meals:n,onLogAgain:r,onEdit:s,onDelete:d,pending:g}){return a.jsx(je,{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:n.map(l=>a.jsxs(D,{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:Xt(l)}),a.jsxs("div",{className:"mt-1 text-xs text-[var(--ui-ink-faint)]",children:[l.loggedAt.slice(0,10)," ·"," ",en(l)||l.mealLabel||"No quantity recorded"]})]}),a.jsxs($,{tone:"meta",children:[l.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:()=>s(l),children:"Edit"}),a.jsx(K,{type:"button",size:"sm",variant:"ghost",pending:g,onClick:()=>d(l),children:"Delete"}),a.jsx(K,{type:"button",size:"sm",variant:"secondary",pending:g,onClick:()=>r(l),children:"Log again"})]})]},l.id))})}],onSubmit:async()=>t(!1),submitLabel:"Done"})}function tn(e){switch(e){case"healthkit_daily_active_energy":return"HealthKit daily active energy";case"workout_movement_fallback":return"workout + movement fallback";case"target_inference_only":return"plan target inference";default:return e||"unknown source"}}function nn(e){const t=e.energyModel,n=t.sourceAvailability,r=[n.healthKitDailyEnergy?"HealthKit active energy":null,t.restingEnergyCalories!=null?"HealthKit resting energy":null,n.workoutEnergy?"workout energy":null,n.movementTripCalories?"movement-trip calories":null].filter(Boolean);return r.length>0?r.join(", "):"no measured expenditure streams"}function rn(e){const t=e.energyModel,n=t.recentFoodLogDayCount>0?`${t.recentFoodLogCount} recent food log${t.recentFoodLogCount===1?"":"s"} across ${t.recentFoodLogDayCount} logged day${t.recentFoodLogDayCount===1?"":"s"}`:"no recent logged food days";if(t.estimatedTdeeKcal==null)return`No TDEE estimate yet. Average logged intake is ${i(t.averageCalorieIntake)} kcal/day from ${n}.`;const r=`Recent average balance: intake ${i(t.averageCalorieIntake)} - TDEE ${i(t.estimatedTdeeKcal)} = ${W(t.estimatedDailyEnergyBalanceKcal)} kcal/day.`,s=t.restingEnergyCalories!=null&&t.activeBurnKcal!=null?`TDEE = resting ${i(t.restingEnergyCalories)} + active burn ${i(t.activeBurnKcal)}.`:`TDEE is falling back to the configured plan estimate ${i(t.inferredTdee)}.`,d=t.energySourceConfidence==="healthkit_daily_active_energy"?`Active burn uses HealthKit daily active energy ${i(t.activeBurnKcal)}; workout and movement are evidence only.`:t.energySourceConfidence==="workout_movement_fallback"?`Active burn fallback = workout ${i(t.workoutEnergyKcal)} + movement ${i(t.movementCaloriesKcal)} = ${i(t.activeBurnKcal)}, so movement is not added again.`:"Active burn is not measured yet.";return`${r} ${s} ${d} Food window: ${n}. Negative means estimated deficit; this is not today's remaining calories.`}function sn(e){const t=e.energyModel,n=t.restingEnergyCalories!=null&&t.activeBurnKcal!=null,r=e.todayLedger.dateKey,s=t.recentFoodLogDayCount>0?`${t.recentFoodLogCount} recent food log${t.recentFoodLogCount===1?"":"s"} across ${t.recentFoodLogDayCount} distinct logged day${t.recentFoodLogDayCount===1?"":"s"}`:"no recent logged food days",d=t.energySourceConfidence==="healthkit_daily_active_energy"?`active burn = HealthKit daily active energy average = ${i(t.activeBurnKcal)} kcal/day`:t.energySourceConfidence==="workout_movement_fallback"?`active burn = workout average ${i(t.workoutEnergyKcal)} + movement-trip average ${i(t.movementCaloriesKcal)} = ${i(t.activeBurnKcal)} kcal/day`:"active burn is not measured; Forge falls back to plan inference",g=t.restingEnergyCalories!=null&&t.activeBurnKcal!=null?`TDEE = resting energy average ${i(t.restingEnergyCalories)} + active burn average ${i(t.activeBurnKcal)} = ${i(t.estimatedTdeeKcal)} kcal/day.`:`TDEE = ${i(t.estimatedTdeeKcal)} kcal/day from the configured plan because complete resting + active energy is not available.`,l=t.estimatedTdeeKcal!=null?`Energy gap = average logged intake - TDEE = ${i(t.averageCalorieIntake)} - ${i(t.estimatedTdeeKcal)} = ${W(t.estimatedDailyEnergyBalanceKcal)} kcal/day.`:"Energy gap cannot be computed until Forge has either measured expenditure or an inferred TDEE.",o=t.energySourceConfidence==="healthkit_daily_active_energy"?`selected active burn = HealthKit daily active energy average = ${i(t.activeBurnKcal)} kcal/day. Workout and movement are visible as evidence but are not added.`:t.energySourceConfidence==="workout_movement_fallback"?`selected active burn = workout average ${i(t.workoutEnergyKcal)} + movement-trip average ${i(t.movementCaloriesKcal)} = ${i(t.activeBurnKcal)} kcal/day. This is why movement can appear next to active burn: it is a component of active burn here, not a separate add-on.`:"selected active burn is unavailable, so TDEE falls back to the configured plan estimate.",c=t.restingEnergyCalories!=null&&t.activeBurnKcal!=null&&t.estimatedTdeeKcal!=null?t.energySourceConfidence==="healthkit_daily_active_energy"?`Arithmetic shown here: active burn ${i(t.activeBurnKcal)} = HealthKit daily active energy average; TDEE ${i(t.estimatedTdeeKcal)} = resting ${i(t.restingEnergyCalories)} + active burn ${i(t.activeBurnKcal)}; energy gap ${W(t.estimatedDailyEnergyBalanceKcal)} = intake ${i(t.averageCalorieIntake)} - TDEE ${i(t.estimatedTdeeKcal)}.`:t.energySourceConfidence==="workout_movement_fallback"?`Arithmetic shown here: active burn ${i(t.activeBurnKcal)} = workout ${i(t.workoutEnergyKcal)} + movement ${i(t.movementCaloriesKcal)}; TDEE ${i(t.estimatedTdeeKcal)} = resting ${i(t.restingEnergyCalories)} + active burn ${i(t.activeBurnKcal)}; energy gap ${W(t.estimatedDailyEnergyBalanceKcal)} = intake ${i(t.averageCalorieIntake)} - TDEE ${i(t.estimatedTdeeKcal)}.`:`Arithmetic shown here: TDEE ${i(t.estimatedTdeeKcal)} = resting ${i(t.restingEnergyCalories)} + active burn ${i(t.activeBurnKcal)}; energy gap ${W(t.estimatedDailyEnergyBalanceKcal)} = intake ${i(t.averageCalorieIntake)} - TDEE ${i(t.estimatedTdeeKcal)}.`:"Arithmetic shown here uses the available expenditure branch; some terms are unavailable because Forge does not yet have both resting and active energy evidence.",w=t.recentFoodLogDayCount>0?`Average intake = total calories in the latest ${t.recentFoodLogCount} non-discarded food log${t.recentFoodLogCount===1?"":"s"} / ${t.recentFoodLogDayCount} logged day${t.recentFoodLogDayCount===1?"":"s"}. It does not divide by silent calendar days.`:"Average logged intake is 0 because there are no recent food logs in the current window.",b=t.energySourceConfidence==="healthkit_daily_active_energy"?"Active burn is using HealthKit daily active energy first. Workout and movement values remain visible as evidence, but movement is not added again on top of HealthKit active energy.":t.energySourceConfidence==="workout_movement_fallback"?"HealthKit daily active energy is missing, so active burn falls back to workout energy plus movement-trip calories.":"No measured active-burn stream is available, so this is driven by the plan target and should be treated as low-confidence.",x=`Today is separate: today's target = baseline plan target + (today active calories - default active calories). Today active calories currently use ${va(t.todayActiveCaloriesSource)}: ${i(t.todayActiveCaloriesKcal)} kcal. Default active calories: ${i(t.baselineActiveCaloriesKcal)} kcal. Today's adjustment: ${W(t.todayTargetAdjustmentKcal)} kcal.`,m=t.energySourceConfidence==="healthkit_daily_active_energy"?"Data path: recent food logs provide intake; HealthKit daily active-energy rows provide active burn; resting-energy rows provide basal/resting expenditure.":t.energySourceConfidence==="workout_movement_fallback"?"Data path: recent food logs provide intake; HealthKit resting-energy rows provide resting expenditure; workout-session energy plus movement-trip calories provide fallback active burn.":"Data path: recent food logs provide intake; expenditure is using the configured plan inference because measured expenditure streams are incomplete.";return a.jsxs("span",{className:"grid gap-2",children:[a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"What this card means:"})," ","this is a historical energy-balance estimate, not the remaining food budget for today. Negative means estimated deficit; positive means estimated surplus."]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Formula:"})," ",l]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"TDEE:"})," ","TDEE means total daily energy expenditure: the estimated calories burned per day. Forge uses"," ",n?"measured resting energy plus the selected active-burn branch":"the configured/inferred plan estimate because measured resting plus active expenditure is incomplete",". Objective deficit or surplus is not subtracted here; that belongs to the intake target."]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Selected branch:"})," ",t.energySourceConfidence==="healthkit_daily_active_energy"?"HealthKit daily active energy exists, so active burn uses that value. Workout, movement, and step values are shown only as evidence.":t.energySourceConfidence==="workout_movement_fallback"?"HealthKit daily active energy is missing, so active burn uses workout calories plus movement-trip calories.":"Measured expenditure is incomplete, so TDEE falls back to the configured plan estimate."]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Active-burn branch:"})," ",o]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Arithmetic:"})," ",c]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Why these numbers:"})," ","The displayed movement value is therefore"," ",t.energySourceConfidence==="workout_movement_fallback"?"part of the active-burn calculation":"supporting evidence only",", and it is not the same thing as today's editable active-calorie budget."]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Current data:"})," ","intake ",i(t.averageCalorieIntake)," kcal/day; TDEE"," ",i(t.estimatedTdeeKcal)," kcal/day; resting"," ",i(t.restingEnergyCalories)," kcal/day; active burn"," ",i(t.activeBurnKcal)," kcal/day; workout"," ",i(t.workoutEnergyKcal)," kcal/day; movement"," ",i(t.movementCaloriesKcal)," kcal/day."," ",t.energySourceConfidence==="workout_movement_fallback"?"On this branch, active burn already equals workout plus movement, so movement is not an extra add-on after active burn.":"On this branch, movement is shown as evidence and is not added on top of active burn."]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Data lineage:"})," ",m]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Food window:"})," ",w," Current denominator: ",s,"."]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Expenditure:"})," ",g," ",d,". TDEE means total daily energy expenditure, the estimated calories burned per day before applying the weight-loss or weight-gain objective."]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"TDEE source:"})," ",n?"measured expenditure branch: resting energy average plus selected active-burn branch":"plan-inference branch because Forge does not yet have both resting and active expenditure streams",". TDEE is an expenditure estimate; the goal deficit or surplus is applied when planning intake targets, not when calculating historical TDEE."]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Calculation path:"})," ","Forge first tries HealthKit daily active energy for active burn. If that is missing, it uses workout energy plus movement-trip calories. TDEE is resting energy plus whichever active-burn branch was selected. The objective deficit or surplus is not part of this historical TDEE."]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Source:"})," ",tn(t.energySourceConfidence)," across"," ",t.evidenceDays," expenditure evidence day",t.evidenceDays===1?"":"s"," ending the selected day (",r,"). Available streams: ",nn(e),"."," ",b]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Movement:"})," ","movement kcal is a component of fallback active burn. If HealthKit daily active energy exists, Forge shows movement as supporting evidence but does not add it again. If HealthKit active energy is missing, fallback active burn is workout average + movement average; the displayed active burn number already includes that movement component."]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Today:"})," ",x]})]})}function on(e){const t=W(e);return t==="n/a"?t:`${t} kcal/d`}function va(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 ln(e){const[t,n,r]=e.split("-").map(Number),s=new Date(t,n-1,r),d=new Date(t,n-1,r+1);return{dayStartAt:s.toISOString(),dayEndAt:d.toISOString()}}function cn(){const e=new Date,t=new Date(e);return t.setHours(24,0,2,0),Math.max(1e3,t.getTime()-e.getTime())}function jn(){const e=Ua(),t=qa(),n=e.selectedUserIds,[r,s]=F.useState(()=>$e()),d=F.useMemo(()=>ln(r),[r]),g=F.useMemo(()=>["forge-weight-loss-view",r,...n],[r,n]),[l,o]=F.useState(!1),[c,w]=F.useState(!1),[b,x]=F.useState(!1),[m,S]=F.useState(!1),[E,M]=F.useState(!1),[_,T]=F.useState(null),[L,B]=F.useState(null),[P,H]=F.useState(""),[te,J]=F.useState(null),[O,U]=F.useState(null),[ne,re]=F.useState("search"),[oe,Z]=F.useState(void 0),[Q,V]=F.useState(()=>fe()),[ge,f]=F.useState(()=>aa()),v=za({queryKey:g,queryFn:async()=>(await st(n,{dateKey:r,...d})).weightLoss}),j=v.data;F.useEffect(()=>{const u=()=>{s(Oe=>{const Ue=$e();return Ue===Oe?Oe:Ue})},h=window.setTimeout(u,cn());return window.addEventListener("focus",u),document.addEventListener("visibilitychange",u),()=>{window.clearTimeout(h),window.removeEventListener("focus",u),document.removeEventListener("visibilitychange",u)}},[r]),F.useEffect(()=>{!j||c||l||Kt(j)||(w(!0),J(Ee(j)),T(`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.`),o(!0))},[c,j,l]),F.useEffect(()=>{j&&(H(String(Math.round(j.energyModel.todayActiveCaloriesKcal??0))),B(null))},[j==null?void 0:j.generatedAt,j==null?void 0:j.energyModel.todayActiveCaloriesKcal]);const X=()=>t.invalidateQueries({queryKey:g}),ke=q({mutationFn:async u=>(await Qa({query:u,userIds:n})).foods}),me=q({mutationFn:async u=>Va({text:u,userIds:n,commitCandidate:!1}),onSuccess:({candidate:u})=>{V(Bt(u,"chatgpt"))}}),Le=q({mutationFn:async u=>Ye(fa(u),n),onSuccess:()=>{V(fe()),x(!1),X()}}),Pe=q({mutationFn:async({foodLogId:u,draft:h})=>Ya(u,Ot(h),n),onSuccess:()=>{V(fe()),U(null),x(!1),X()}}),Ne=q({mutationFn:async u=>Ja(u.id,n),onSuccess:()=>{X()}}),we=q({mutationFn:async u=>Za({dayKey:j==null?void 0:j.todayLedger.dateKey,activeCaloriesKcal:u,notes:u==null?"":"Manual active-calorie override from the weight-loss view"},n),onSuccess:()=>{B(null),X()},onError:u=>{B(u instanceof Error?u.message:"Could not save active calories")}}),he=q({mutationFn:async u=>{const h=Number(u.currentWeightKg);await Xa(_t(u),n),Number.isFinite(h)&&await Je({weightKg:h,notes:"Updated from weight-plan setup."},n)},onSuccess:()=>{o(!1),X()}}),Re=q({mutationFn:async u=>{const h=Zt(u);await Promise.all([h.body.weightKg!==null||h.body.waistCm!==null||h.body.bodyFatPercent!==null?Je(h.body,n):Promise.resolve(),h.subjective.energy!==null||h.subjective.hunger!==null||h.subjective.cravings!==null?et(h.subjective,n):Promise.resolve(),h.gut.bloating!==null?at(h.gut,n):Promise.resolve(),h.appearance.facePuffiness!==null||h.appearance.leanness!==null?tt(h.appearance,n):Promise.resolve()])},onSuccess:()=>{f(aa()),S(!1),X()}}),pe=q({mutationFn:async u=>Ye({mealLabel:u.mealLabel??"Saved meal",source:"saved_meal",confirmationState:"confirmed",notes:u.notes??"",items:u.items.map(h=>({foodId:h.foodId,name:h.name,brand:h.brand,quantity:h.quantity,unit:h.unit,grams:h.grams,calories:h.calories,proteinGrams:h.proteinGrams,carbohydrateGrams:h.carbohydrateGrams,fatGrams:h.fatGrams,fiberGrams:h.fiberGrams,sugarGrams:h.sugarGrams,sodiumMg:h.sodiumMg,potassiumMg:h.potassiumMg,caffeineMg:h.caffeineMg,alcoholGrams:h.alcoholGrams,glycemicIndex:h.glycemicIndex,novaGroup:h.novaGroup,fermented:h.fermented,probiotic:h.probiotic,fodmapLevel:h.fodmapLevel,tags:h.tags,confidence:h.confidence??.85}))},n),onSuccess:()=>{X()}});if(v.isLoading)return a.jsx(nt,{title:"Loading weight-loss signals",description:"Combining food logs, HealthKit, movement, workouts, body check-ins, subjective state, and gut signals."});if(v.isError||!v.data)return a.jsx(rt,{error:v.error??new Error("Weight-loss view unavailable"),onRetry:()=>void v.refetch()});const C=v.data,I=C.todayLedger,We=I.totals,Ce=We.calories,Fe=I.targetCalories-Ce,ya=I.plannedTargetCalories??I.targetCalories,Be=C.energyModel.todayActiveCaloriesKcal??C.energyModel.activeBurnKcal??C.energyModel.activeEnergyCalories??C.energyModel.movementCaloriesKcal??0,ja=C.energyModel.baselineActiveCaloriesKcal??Be,Me=I.activeAdjustmentCalories??0,ka=Me===0?"no active-calorie adjustment":`${Me>0?"+":""}${Me.toFixed(0)} kcal from ${va(I.activeCaloriesSource)}`,Na=I.targetCalories>0?Math.min(140,Math.max(0,Ce/I.targetCalories*100)):0,wa=C.energyModel,He=C.weightTrend,xe=C.foodQuality,Ge=C.trainingFuel,Ca=C.subjective,Fa=C.gut,Ma=ot(C.hypotheses),Se=te??Ee(C),Ga=()=>{T(null),J(Ee(C)),o(!0)},Ke=(u="search")=>{U(null),re(u),Z(u==="custom"?"amounts":"search"),V(u==="custom"?Ht():fe()),x(!0)},qe=u=>{U(u.id),re("search"),Z("amounts"),V(Wt(u)),x(!0),M(!1)},ze=u=>{typeof window<"u"&&!window.confirm(`Delete ${u.mealLabel??"this meal"} from the food log?`)||Ne.mutate(u)},Sa=()=>{const u=Number(P);if(!Number.isFinite(u)||u<0){B("Enter a valid active-calorie value.");return}we.mutate(Math.round(u))},Ka=()=>{we.mutate(null)};return a.jsxs("div",{className:"mx-auto grid w-full max-w-[1500px] gap-5",children:[a.jsx(Oa,{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:`${I.targetCalories.toFixed(0)} kcal budget · ${C.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(mt,{ledger:I,remainingCalories:Fe,intakePercent:Na,logSavedPending:pe.isPending||Ne.isPending,onLogAgain:u=>pe.mutate(u),onEditMeal:qe,onDeleteMeal:ze}),a.jsxs("div",{className:"grid min-w-0 gap-4",children:[a.jsx(it,{view:C,onOpenPlan:Ga,onOpenFoodSearch:()=>Ke("search"),onOpenCustomFood:()=>Ke("custom"),onOpenChatGptFood:()=>Ke("chatgpt"),onOpenCheckin:()=>S(!0),onOpenHistory:()=>M(!0)}),a.jsx(dt,{view:C,draftValue:P,pending:we.isPending,error:L,onDraftChange:H,onSave:Sa,onReset:Ka})]})]}),a.jsxs("section",{className:"grid gap-4 xl:grid-cols-4",children:[a.jsx(Y,{label:"Today",value:`${Ce.toFixed(0)} kcal`,detail:`${Fe.toFixed(0)} kcal remaining against today's ${I.targetCalories.toFixed(0)} kcal target; ${ka}.`,icon:Qe,tone:Fe>=0?"green":"rose",help:`Today's target = baseline plan target + (today active calories - default active calories). Here: ${ya.toFixed(0)} + (${Be.toFixed(0)} - ${ja.toFixed(0)}) = ${I.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(Y,{label:"Protein",value:`${We.proteinGrams.toFixed(0)}g`,detail:`${C.target.proteinGramsTarget.toFixed(0)}g target. Protein anchors the plan while cutting or gaining.`,icon:Wa,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(Y,{label:"Energy gap",value:on(wa.estimatedDailyEnergyBalanceKcal),detail:rn(C),icon:Ba,tone:"amber",help:sn(C),helpMaxWidthPx:560}),a.jsx(Y,{label:"Weight trend",value:W(He.sevenDayRateKg,2),detail:`Latest ${i(He.latestWeightKg,1)} kg. Trend uses check-ins, not noisy single weigh-ins.`,icon:_e,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(xt,{view:C}),a.jsx(Ft,{view:C}),a.jsxs("section",{className:"grid gap-4 xl:grid-cols-4",children:[a.jsx(Y,{label:"Food quality",value:be(xe.qualityScore),detail:`Fiber density ${i(xe.fiberPer1000Kcal,1)}g/1000 kcal, protein density ${i(xe.proteinPer1000Kcal,1)}g/1000 kcal, ultra-processed share ${i(xe.ultraProcessedShare,0)}%.`,icon:Qe,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(Y,{label:"Training fuel",value:be(Ge.fuelingScore),detail:`Recent workout load ${i(Ge.recentTrainingLoad)} with ${i(Ge.carbsPerTrainingLoad,1)}g carbs per load unit.`,icon:ia,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(Y,{label:"Subjective",value:be(Ca.averageFocus),detail:"Focus, energy, hunger, cravings, and performance are tracked as food-effect evidence.",icon:_e,help:"Subjective signals are self-rated energy, focus, hunger, cravings, and performance. Forge uses them to discover food and timing effects."}),a.jsx(Y,{label:"Gut",value:be(Fa.averageBloating),detail:"Bloating, reflux, stool type, and suspected triggers connect food choices to comfort and look.",icon:Ha,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(ht,{hypotheses:Ma}),a.jsx(pt,{experiments:C.experiments})]}),a.jsx($t,{open:l,onOpenChange:o,view:C,value:Se,onChange:u=>{J(u),T(null)},pending:he.isPending,error:_??(he.error instanceof Error?he.error.message:null),onSubmit:async()=>{const u=Et(Se);if(u){T(u);return}await he.mutateAsync(Se)}}),a.jsx(qt,{open:b,onOpenChange:x,value:Q,onChange:V,foodResults:ke.data??[],searchPending:ke.isPending,chatGptPending:me.isPending,chatGptError:me.error instanceof Error?me.error.message:null,logPending:Le.isPending||Pe.isPending,intent:ne,initialStepId:oe,onSearch:u=>ke.mutate(u),onParseWithChatGpt:u=>me.mutateAsync(u).then(()=>{}),mode:O?"edit":"create",onSubmit:async()=>{if(O){await Pe.mutateAsync({foodLogId:O,draft:Q});return}await Le.mutateAsync(Q)}}),a.jsx(Jt,{open:m,onOpenChange:S,value:ge,onChange:f,pending:Re.isPending,onSubmit:async()=>{await Re.mutateAsync(ge)}}),a.jsx(an,{open:E,onOpenChange:M,meals:C.recentMeals,pending:pe.isPending||Ne.isPending,onLogAgain:u=>pe.mutate(u),onEdit:qe,onDelete:ze})]})}export{jn as WeightLossPage};
@@ -0,0 +1,4 @@
1
+ import{j as a,aC as j,r as w}from"./vendor-Dnkkx2co.js";import{Z as u,bq as N,cL as $}from"./index-EqQsXoat.js";function k(i){const e=[];let n,r;for(const s of i){const t=s.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(),p=t.slice(o+1).trim();if(!p)continue;const m=c.toLowerCase();if(m==="title"){n=p;continue}if(m==="summary"){r=p;continue}e.push({label:c,value:p})}return{title:n,summary:r,rows:e}}function C(i){const e=[],n=/(!?\[\[([^\]]+)\]\]|\[([^\]]+)\]\(([^)]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|\*([^*]+)\*)/g;let r=0,s=null;for(;(s=n.exec(i))!==null;){if(s.index>r&&e.push({type:"text",value:i.slice(r,s.index)}),s[1]&&s[2]){const t=s[2].trim(),o=s[1].startsWith("!"),c=t.indexOf("|"),p=c>=0?t.slice(0,c).trim():t,m=c>=0?t.slice(c+1).trim():p;if(p.toLowerCase().startsWith("forge:")){const[,g,...l]=p.split(":");e.push({type:"forge-link",entityType:g??"",entityId:l.join(":").trim(),label:m})}else e.push({type:"wiki-link",target:p,label:m,embed:o})}else s[3]&&s[4]?e.push({type:"link",label:s[3],href:s[4].trim()}):s[5]?e.push({type:"code",value:s[5]}):s[6]?e.push({type:"strong",value:s[6]}):s[7]&&e.push({type:"em",value:s[7]});r=n.lastIndex}return r<i.length&&e.push({type:"text",value:i.slice(r)}),e}function L(i){const e=i.replace(/\r/g,"").split(`
2
+ `),n=[],r=[];let s=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,n.push({type:"code",code:l.join(`
3
+ `)});continue}const p=c.match(/^:::([a-z0-9-]+)\s*$/i);if(p){const l=p[1].toLowerCase(),d=[];for(t+=1;t<e.length&&(e[t]??"").trim()!==":::";)d.push(e[t]??""),t+=1;t<e.length&&(t+=1);const y=[`:::${l}`,...d,":::"].join(`
4
+ `);r.push({kind:l,lines:d,raw:y}),l==="forge-infobox"?s=k(d):l==="note"||l==="tip"||l==="warning"||l==="danger"?n.push({type:"admonition",kind:l,lines:d}):(l==="forge-links"||l==="forge-media"||l==="forge-related")&&n.push({type:l,lines:d});continue}const m=o.match(/^(#{1,6})\s+(.*)$/);if(m){n.push({type:"heading",level:m[1].length,text:m[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;n.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;n.push({type:"list",ordered:l,items:d});continue}const g=[];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;g.push(d),t+=1}if(g.length>0){n.push({type:"paragraph",text:g.join(" ")});continue}t+=1}return{blocks:n,infobox:s,directives:r}}const x="text-[var(--ui-ink-medium)]",W="text-[var(--ui-ink-soft)]",f="text-[var(--ui-ink-faint)]",q="text-[var(--ui-ink-strong)]",b="border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)]",I="border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)]",T="rounded-sm bg-[var(--ui-surface-2)] px-1.5 py-0.5 text-[var(--ui-ink-strong)] no-underline ring-1 ring-[var(--ui-border-subtle)] transition hover:bg-[var(--ui-surface-hover)]";function M(i,e,n){return i.map((r,s)=>{const t=`${e}-${s}`;switch(r.type){case"text":return a.jsx(w.Fragment,{children:r.value},t);case"code":return a.jsx("code",{className:"rounded bg-[var(--ui-surface-2)] px-1.5 py-0.5 font-mono text-[0.92em] text-[var(--ui-ink-strong)] ring-1 ring-[var(--ui-border-subtle)]",children:r.value},t);case"strong":return a.jsx("strong",{className:"font-semibold text-[var(--ui-ink-strong)]",children:r.value},t);case"em":return a.jsx("em",{className:"italic text-[var(--ui-ink-medium)]",children:r.value},t);case"link":{const o=/^https?:\/\//i.test(r.href);return a.jsx("a",{href:r.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-[var(--ui-ink-strong)]",children:r.label},t)}case"forge-link":{const o=N(r.entityType,r.entityId),c=o?$(o):null;return c?a.jsx("a",{href:c,className:T,children:r.label},t):a.jsx("span",{className:"rounded-sm bg-[var(--ui-surface-2)] px-1.5 py-0.5 text-[var(--ui-ink-soft)] ring-1 ring-[var(--ui-border-subtle)]",children:r.label},t)}case"wiki-link":return a.jsx(j,{to:{pathname:`/wiki/page/${encodeURIComponent(r.target)}`,search:n?`?spaceId=${encodeURIComponent(n)}`:""},className:u("underline decoration-current/30 underline-offset-2 transition hover:text-[var(--ui-ink-strong)]",r.embed?"text-[var(--primary)]":"text-[var(--secondary)]"),children:r.label},t)}})}function h(i,e,n){return M(C(i),e,n)}function P(i,e){const n=i.map(r=>r.trim()).filter(Boolean);return n.length===0?null:a.jsx("ul",{className:u("space-y-1.5 pl-4 text-[13px] leading-6",x),children:n.map((r,s)=>a.jsx("li",{children:h(r,`directive-${s}`,e)},`${r}-${s}`))})}function v(i,e,n){switch(i.type){case"heading":{const r=i.level===1?"text-[1.9rem] leading-[1.08]":i.level===2?"text-[1.25rem] leading-[1.2]":i.level===3?"text-[1.05rem] leading-[1.3]":"text-[0.92rem] leading-[1.35]";return a.jsx("h2",{className:u("font-semibold tracking-[-0.02em]",q,e>0&&"mt-6",r),children:h(i.text,`heading-${e}`,n)},`heading-${e}`)}case"paragraph":return a.jsx("p",{className:u("text-[14px] leading-7",x),children:h(i.text,`paragraph-${e}`,n)},`paragraph-${e}`);case"quote":return a.jsx("blockquote",{className:u("border-l-[3px] border-[var(--ui-border-strong)] pl-4 text-[14px] leading-7",W),children:h(i.text,`quote-${e}`,n)},`quote-${e}`);case"list":{const r=i.ordered?"ol":"ul";return a.jsx(r,{className:u("space-y-1.5 pl-5 text-[14px] leading-7",x,i.ordered?"list-decimal":"list-disc"),children:i.items.map((s,t)=>a.jsx("li",{children:h(s,`list-${e}-${t}`,n)},`item-${e}-${t}`))},`list-${e}`)}case"code":return a.jsx("pre",{className:"max-w-full overflow-x-auto rounded-xl border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-code)] px-4 py-3 text-[12px] leading-6 text-[var(--ui-ink-strong)]",children:a.jsx("code",{children:i.code})},`code-${e}`);case"admonition":return a.jsxs("aside",{className:u("rounded-xl border px-4 py-3",i.kind==="warning"||i.kind==="danger"?"border-[color-mix(in_srgb,var(--warning)_32%,transparent)] bg-[var(--ui-warning-soft)]":I),children:[a.jsx("div",{className:u("mb-2 text-[11px] font-semibold uppercase tracking-[0.16em]",f),children:i.kind}),a.jsx("div",{className:u("grid gap-2 text-[13px] leading-6",x),children:i.lines.map((r,s)=>a.jsx("p",{children:h(r,`admonition-${e}-${s}`,n)},`admonition-line-${s}`))})]},`admonition-${e}`);case"forge-links":case"forge-media":case"forge-related":return a.jsxs("section",{className:u("rounded-xl border px-4 py-3",b),children:[a.jsx("div",{className:u("mb-2 text-[11px] font-semibold uppercase tracking-[0.16em]",f),children:i.type.replace("forge-","")}),P(i.lines,n)]},`${i.type}-${e}`)}}function R(i,e,n){return a.jsx("div",{className:u("text-[13px] leading-6",x),children:h(i,e,n)})}function _({infobox:i,spaceId:e,className:n}){return a.jsxs("aside",{className:u("wiki-infobox rounded-2xl border p-4",b,n),children:[i.title?a.jsx("div",{className:"text-[1rem] font-semibold leading-tight text-[var(--ui-ink-strong)]",children:i.title}):null,i.summary?a.jsx("p",{className:"mt-2 text-[13px] leading-6 text-[var(--ui-ink-soft)]",children:h(i.summary,"infobox-summary",e)}):null,a.jsx("dl",{className:"mt-3 grid gap-2",children:i.rows.map((r,s)=>a.jsxs("div",{className:"grid gap-1 border-t border-[var(--ui-border-subtle)] pt-2 first:border-t-0 first:pt-0",children:[a.jsx("dt",{className:"text-[10px] font-semibold uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:r.label}),a.jsx("dd",{children:R(r.value,`infobox-row-${s}`,e)})]},`${r.label}-${s}`))})]})}function z(i){const e=[],n=[];let r=!1;for(const s of i)!r&&s.type==="heading"&&s.level<=2&&e.length>0&&(r=!0),r?n.push(s):e.push(s);return{intro:e.length>0?e:i.slice(0,1),rest:e.length>0?n:i.slice(1)}}function A({markdown:i,spaceId:e,className:n}){const r=L(i),{intro:s,rest:t}=z(r.blocks);return a.jsxs("div",{className:u("grid gap-4",n),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:s.map((o,c)=>v(o,c,e))}),r.infobox?a.jsx(_,{infobox:r.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)=>v(o,c+s.length,e))}):null]})}export{A as W};
@@ -0,0 +1,26 @@
1
+ import{aJ as Be,b5 as Qe,cc as qe,c2 as De,r as d,j as e,cw as Ke,cx as Ve,bk as He,bX as Ue,cb as Je,aU as Xe,aR as Ye,cg as Ze,dH as Ge,dI as ea,aK as we,bl as aa}from"./vendor-Dnkkx2co.js";import{R as ye,P as Ne,O as Ce,C as Se,T as Ie,D as Te,a as $e}from"./ui-C1iwpj2-.js";import{j as sa,i as X,k as ta}from"./state-vCcAT5Hq.js";import{u as ra,c as g,g as P,fl as ia,fm as na,L as la,E as oa,a as da,B as C,Z as j,I as T,T as E,m as F,aq as ve,bY as ca,fn as ua,fo as pa}from"./index-EqQsXoat.js";import{W as xa}from"./wiki-article-markdown-Dok2uy2p.js";import"./motion-Lt5B1XuE.js";import"./forms-hB0SqEh-.js";import"./board-dIX6etHh.js";import"./graph-DDUZNRsO.js";const _="rounded-[28px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] shadow-[var(--ui-shadow-card)]",x="text-[11px] font-semibold uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",ma="w-full rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] px-3.5 py-3 text-[13px] text-[var(--ui-ink-strong)] outline-none transition focus:border-[color-mix(in_srgb,var(--primary)_40%,transparent)]",b="border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] text-[var(--ui-ink-medium)]",fe="min-w-0 rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] px-4 py-3 text-left transition hover:bg-[var(--ui-surface-hover)]";function M(t,r){return`${t}:${r}`}function ha(t){const r=t.indexOf(":");return r<=0||r>=t.length-1?null:{entityType:t.slice(0,r),entityId:t.slice(r+1)}}function Le(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function $(t){return Array.from(new Set(t.split(",").map(r=>r.trim()).filter(Boolean)))}function ga(t){if(!t.trim())return{};try{const r=JSON.parse(t);return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}catch{return{}}}function Me(){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 ba(t,r){const v=t.trim()||"Untitled";return{...Me(),title:v,slug:(r==null?void 0:r.trim())||Le(v),contentMarkdown:`# ${v}
6
+
7
+ `}}function ke(t){return{pageId:t.id,kind:t.kind,title:t.title,slug:t.slug,parentSlug:t.parentSlug,indexOrder:t.indexOrder,showInIndex:t.showInIndex,summary:t.summary,aliasesText:t.aliases.join(", "),contentMarkdown:t.contentMarkdown,author:t.author??"",tagsText:(t.tags??[]).join(", "),frontmatterText:JSON.stringify(t.frontmatter??{},null,2),linkedValues:t.links.map(r=>M(r.entityType,r.entityId))}}function L({open:t,title:r,description:v,children:W,onOpenChange:m}){return e.jsx(ye,{open:t,onOpenChange:m,children:e.jsxs(Ne,{children:[e.jsx(Ce,{className:"fixed inset-0 z-50 surface-overlay backdrop-blur-sm"}),e.jsxs(Se,{className:"fixed left-1/2 top-[12vh] z-50 w-[min(32rem,calc(100vw-1.5rem))] -translate-x-1/2 rounded-[24px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-popover)] p-4 shadow-[var(--ui-shadow-floating)] sm:p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(Ie,{className:"text-[1.05rem] font-semibold text-[var(--ui-ink-strong)]",children:r}),e.jsx(Te,{className:"mt-1 text-[13px] leading-6 text-[var(--ui-ink-soft)]",children:v})]}),e.jsx($e,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-2 text-[var(--ui-ink-soft)] transition hover:bg-[var(--ui-surface-2)] hover:text-[var(--ui-ink-strong)]","aria-label":"Close",children:e.jsx(we,{className:"size-4"})})})]}),e.jsx("div",{className:"mt-4",children:W})]})]})})}const va=ma;function je(t){return t.trim().toLowerCase()}function fa(t){const r=t.trim();return r?r.split(/\s+/).length:0}function ka({icon:t,label:r,onClick:v}){return e.jsxs("div",{className:"group relative",children:[e.jsx("button",{type:"button","aria-label":r,className:"inline-flex size-10 items-center justify-center rounded-[14px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] text-[var(--ui-ink-soft)] transition hover:bg-[var(--ui-surface-2)] hover:text-[var(--ui-ink-strong)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary)]/35",onClick:v,children:e.jsx(t,{className:"size-4"})}),e.jsx("div",{className:"pointer-events-none absolute left-1/2 top-[calc(100%+0.55rem)] z-20 -translate-x-1/2 whitespace-nowrap rounded-[12px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-popover)] px-2.5 py-1.5 text-[11px] font-medium text-[var(--ui-ink-medium)] opacity-0 shadow-[var(--ui-shadow-floating)] transition group-hover:opacity-100 group-focus-within:opacity-100",children:r})]})}function ja(t){return t.map(r=>({value:r.label,label:r.label,description:r.description,searchText:`${r.label} ${r.description}`,badge:e.jsx(g,{className:b,style:r.color?{color:r.color}:void 0,children:r.label}),menuBadge:e.jsx(g,{className:b,style:r.color?{color:r.color}:void 0,children:r.label})}))}function Ma(){var ie,ne,le,oe,de,ce,ue,pe,xe,me,he,ge;const t=ra(),r=sa(),v=Be(),W=Qe(),{pageId:m}=qe(),[A,Oe]=De(),[l,c]=d.useState(()=>Me()),[S,p]=d.useState(null),[B,Y]=d.useState(""),[f,z]=d.useState(""),[Pe,Q]=d.useState(!1),[q,Ee]=d.useState(!1),[D,K]=d.useState(""),[V,H]=d.useState(""),Z=d.useRef(null),G=d.useRef(!1),h=((ie=v.state)==null?void 0:ie.initialPage)??null,U=((ne=A.get("title"))==null?void 0:ne.trim())??"",ee=((le=A.get("slug"))==null?void 0:le.trim())??"",w=X({queryKey:["forge-wiki-settings"],queryFn:ca}),k=X({queryKey:["forge-wiki-page",m],queryFn:()=>ua(m??""),enabled:!!m}),y=A.get("spaceId")||((oe=k.data)==null?void 0:oe.page.spaceId)||(h==null?void 0:h.spaceId)||((ce=(de=w.data)==null?void 0:de.settings.spaces[0])==null?void 0:ce.id)||"",ae=((pe=(ue=w.data)==null?void 0:ue.settings.spaces.find(a=>a.id===y))==null?void 0:pe.label)??"Current space",N=X({queryKey:["forge-wiki-pages",y],queryFn:()=>pa({spaceId:y||void 0,limit:500}),enabled:!!y});d.useEffect(()=>{h&&(!m||h.id===m)&&c(ke(h))},[m,h]),d.useEffect(()=>{m||h||G.current||!U||(G.current=!0,c(ba(U,ee)))},[ee,U,m,h]),d.useEffect(()=>{var a;(a=k.data)!=null&&a.page&&c(ke(k.data.page))},[k.data]);const O=d.useMemo(()=>{var a;return(((a=N.data)==null?void 0:a.pages)??[]).filter(s=>s.id!==l.pageId).sort((s,n)=>s.title.localeCompare(n.title))},[l.pageId,(xe=N.data)==null?void 0:xe.pages]),We=d.useMemo(()=>{var s;const a=new Map;for(const n of((s=N.data)==null?void 0:s.pages)??[])for(const o of n.aliases??[]){const u=o.trim();u&&a.set(u.toLowerCase(),{value:u,label:u,description:`Alias on ${n.title}`,searchText:`${u} ${n.title} ${n.slug}`,badge:e.jsx(g,{className:b,children:u}),menuBadge:e.jsx(g,{className:b,children:u})})}for(const n of $(l.aliasesText))a.set(n.toLowerCase(),{value:n,label:n,description:"Wiki alias",searchText:n,badge:e.jsx(g,{className:b,children:n}),menuBadge:e.jsx(g,{className:b,children:n})});return Array.from(a.values()).sort((n,o)=>n.label.localeCompare(o.label))},[l.aliasesText,(me=N.data)==null?void 0:me.pages]),Ae=d.useMemo(()=>[{value:"index",label:"Home",description:"Top-level index page",searchText:"home index top level root"},...O.map(a=>({value:a.slug,label:a.title,description:a.summary||a.slug,searchText:`${a.title} ${a.slug} ${a.summary}`}))],[O]),se=d.useMemo(()=>{const a=je(D);return a?O.filter(s=>`${s.title} ${s.slug} ${s.summary}`.toLowerCase().includes(a)).slice(0,12):O.slice(0,12)},[D,O]),R=d.useMemo(()=>{const a=t.snapshot.goals.map(i=>({value:M("goal",i.id),label:i.title,description:i.description,searchText:`${i.title} ${i.description}`,kind:P("goal")??void 0})),s=t.snapshot.dashboard.projects.map(i=>({value:M("project",i.id),label:i.title,description:[i.goalTitle,i.description].filter(Boolean).join(" · "),searchText:`${i.title} ${i.goalTitle} ${i.description}`,kind:P("project")??void 0})),n=t.snapshot.tasks.map(i=>({value:M("task",i.id),label:i.title,description:i.owner||i.description,searchText:`${i.title} ${i.owner} ${i.description}`,kind:P("task")??void 0})),o=t.snapshot.strategies.map(i=>({value:M("strategy",i.id),label:i.title,description:i.overview,searchText:`${i.title} ${i.overview} ${i.endStateDescription}`,kind:P("strategy")??void 0})),u=t.snapshot.habits.map(i=>({value:M("habit",i.id),label:i.title,description:i.description,searchText:`${i.title} ${i.description}`,kind:P("habit")??void 0}));return[...a,...s,...n,...o,...u].sort((i,J)=>i.label.localeCompare(J.label))},[t.snapshot.dashboard.projects,t.snapshot.goals,t.snapshot.habits,t.snapshot.strategies,t.snapshot.tasks]),te=d.useMemo(()=>{const a=je(V);return a?R.filter(s=>`${s.label} ${s.description??""} ${s.searchText??""}`.toLowerCase().includes(a)).slice(0,12):R.slice(0,12)},[R,V]),ze=d.useMemo(()=>{const a=t.snapshot.tags.map(o=>({label:o.name,description:`Forge ${o.kind} tag`,color:o.color})),s=$(l.tagsText).map(o=>({label:o,description:"Wiki tag"})),n=new Map;return[...a,...s].forEach(o=>{n.set(o.label.toLowerCase(),o)}),ja(Array.from(n.values()).sort((o,u)=>o.label.localeCompare(u.label)))},[l.tagsText,t.snapshot.tags]);function I(a){const s=Z.current;c(n=>{const o=n.contentMarkdown;if(!s)return{...n,contentMarkdown:`${o}${o.endsWith(`
8
+ `)?"":`
9
+ `}${a}`};const u=s.selectionStart??o.length,i=s.selectionEnd??o.length,J=`${o.slice(0,u)}${a}${o.slice(i)}`;return requestAnimationFrame(()=>{s.focus();const be=u+a.length;s.setSelectionRange(be,be)}),{...n,contentMarkdown:J}})}const re=ta({mutationFn:async a=>{const s={kind:a.kind,title:a.title.trim(),slug:a.slug.trim()||Le(a.title),parentSlug:a.parentSlug&&a.parentSlug!=="none"?a.parentSlug:null,indexOrder:a.indexOrder,showInIndex:a.showInIndex,summary:a.summary.trim(),aliases:$(a.aliasesText),contentMarkdown:a.contentMarkdown.trim(),author:a.author.trim()||null,tags:$(a.tagsText),spaceId:y,frontmatter:ga(a.frontmatterText),links:a.linkedValues.map(n=>ha(n)).filter(n=>n!==null)};return a.pageId?ia(a.pageId,s):na(s)},onSuccess:async a=>{await Promise.all([r.invalidateQueries({queryKey:["forge-wiki-pages"]}),r.invalidateQueries({queryKey:["forge-wiki-page"]}),r.invalidateQueries({queryKey:["forge-wiki-home"]}),r.invalidateQueries({queryKey:["forge-wiki-page-by-slug"]}),r.invalidateQueries({queryKey:["forge-wiki-tree"]})]),W({pathname:a.page.slug==="index"?"/wiki":`/wiki/page/${encodeURIComponent(a.page.slug)}`,search:`?spaceId=${encodeURIComponent(a.page.spaceId)}`})}});if(w.isLoading||m&&k.isLoading&&!h)return e.jsx(la,{eyebrow:"Wiki editor",title:"Preparing the editor",description:"Loading the draft, hierarchy, and link helpers."});if(w.isError||k.isError||N.isError)return e.jsx(oa,{eyebrow:"Wiki editor",error:w.error??k.error??N.error,onRetry:()=>{w.refetch(),k.refetch(),N.refetch()}});if(m&&!((he=k.data)!=null&&he.page))return e.jsx(da,{eyebrow:"Wiki editor",title:"Page not found",description:"This wiki entry does not exist anymore."});const Re=[{kind:"wiki-link",icon:Je,label:"Wiki link"},{kind:"forge-link",icon:Xe,label:"Forge link"},{kind:"infobox",icon:Ye,label:"Infobox"},{kind:"admonition",icon:Ze,label:"Admonition"},{kind:"related",icon:Ge,label:"Related"},{kind:"media",icon:ea,label:"Media"}],Fe=fa(l.contentMarkdown),_e=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:j(_,"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:x,children:"Wiki editor"}),e.jsx("h1",{className:"mt-1 text-[1.25rem] font-semibold tracking-[-0.04em] text-[var(--ui-ink-strong)]",children:l.pageId?"Edit page":"New page"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(C,{variant:"secondary",size:"sm",className:"xl:hidden",onClick:()=>Ee(a=>!a),"aria-expanded":q,children:[q?e.jsx(Ke,{className:"size-3.5"}):e.jsx(Ve,{className:"size-3.5"}),"Metadata"]}),e.jsxs(C,{variant:"secondary",size:"sm",onClick:()=>W(-1),children:[e.jsx(He,{className:"size-3.5"}),"Back"]}),e.jsxs(C,{size:"sm",pending:re.isPending,pendingLabel:"Saving",disabled:!l.title.trim()||!l.contentMarkdown.trim(),onClick:()=>void re.mutateAsync(l),children:[e.jsx(Ue,{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:j("order-2 min-w-0 xl:order-1 xl:block",q?"block":"hidden"),children:e.jsxs("section",{className:j(_,"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-[var(--ui-border-subtle)] pb-3",children:[e.jsx("div",{className:x,children:"Metadata"}),e.jsx("div",{className:"min-w-0 truncate text-[11px] uppercase tracking-[0.14em] text-[var(--ui-ink-faint)]",children:ae})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:x,children:"Wiki space"}),e.jsxs("button",{type:"button",className:"flex min-h-[2.9rem] min-w-0 items-center justify-between gap-3 rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] px-3.5 text-[13px] text-[var(--ui-ink-medium)] transition hover:bg-[var(--ui-surface-2)] hover:text-[var(--ui-ink-strong)]",onClick:()=>Q(!0),children:[e.jsx("span",{className:"min-w-0 truncate",children:ae}),e.jsx("span",{className:"shrink-0 text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:"Change"})]})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:x,children:"Title"}),e.jsx(T,{value:l.title,onChange:a=>c(s=>({...s,title:a.target.value})),placeholder:"Page title"})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:x,children:"Slug"}),e.jsx(T,{value:l.slug,onChange:a=>c(s=>({...s,slug:a.target.value})),placeholder:"page-slug"})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:x,children:"Summary"}),e.jsx(E,{value:l.summary,onChange:a=>c(s=>({...s,summary:a.target.value})),rows:4,placeholder:"Short summary"})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:x,children:"Tags"}),e.jsx(F,{options:ze,selectedValues:$(l.tagsText),onChange:a=>c(s=>({...s,tagsText:a.join(", ")})),placeholder:"Search or add tags",emptyMessage:"No tags yet.",createLabel:"Add tag",onCreate:async a=>{const s=a.trim();return{value:s,label:s,description:"Wiki tag",searchText:s,badge:e.jsx(g,{className:b,children:s}),menuBadge:e.jsx(g,{className:b,children:s})}}})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:x,children:"Forge entities"}),e.jsx(F,{options:R,selectedValues:l.linkedValues,onChange:a=>c(s=>({...s,linkedValues:a})),placeholder:"Search Forge entities"})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:x,children:"Aliases"}),e.jsx(F,{options:We,selectedValues:$(l.aliasesText),onChange:a=>c(s=>({...s,aliasesText:a.join(", ")})),placeholder:"Search or add aliases",emptyMessage:"No aliases yet.",createLabel:"Add alias",onCreate:async a=>{const s=a.trim();return{value:s,label:s,description:"Wiki alias",searchText:s,badge:e.jsx(g,{className:b,children:s}),menuBadge:e.jsx(g,{className:b,children:s})}}})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsx("span",{className:x,children:"Author"}),e.jsx(T,{value:l.author,onChange:a=>c(s=>({...s,author:a.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:j("flex items-center gap-2",x),children:[e.jsx("span",{children:"Parent"}),e.jsx(ve,{content:"Choose the page that should own this page in the wiki tree.",label:"Explain parent page"})]}),e.jsx(F,{options:Ae,selectedValues:l.parentSlug?[l.parentSlug]:[],onChange:a=>c(s=>({...s,parentSlug:a[0]??null})),placeholder:"Search parent page",emptyMessage:"No matching pages."})]}),e.jsxs("label",{className:"grid gap-1.5",children:[e.jsxs("span",{className:j("flex items-center gap-2",x),children:[e.jsx("span",{children:"Order"}),e.jsx(ve,{content:"Lower numbers appear earlier within the same parent page.",label:"Explain page order"})]}),e.jsx(T,{type:"number",value:String(l.indexOrder),onChange:a=>c(s=>({...s,indexOrder:Number(a.target.value||0)}))})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] px-3.5 py-3 text-[13px] text-[var(--ui-ink-medium)]",children:[e.jsx("input",{type:"checkbox",className:"mt-0.5",checked:l.showInIndex,onChange:a=>c(s=>({...s,showInIndex:a.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:j(_,"overflow-hidden"),children:[e.jsxs("div",{className:"flex min-h-12 w-full flex-wrap items-center justify-between gap-3 border-b border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] 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:Re.map(a=>e.jsx(ka,{icon:a.icon,label:a.label,onClick:()=>{p(a.kind),Y(""),z(""),K(""),H("")}},a.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-[var(--ui-ink-faint)]",children:[e.jsxs("span",{children:[Fe.toLocaleString()," words"]}),e.jsxs("span",{children:[_e.toLocaleString()," chars"]})]})})]}),e.jsx("div",{className:"bg-[var(--ui-surface-code)]",children:e.jsx(E,{ref:Z,value:l.contentMarkdown,onChange:a=>c(s=>({...s,contentMarkdown:a.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-[var(--ui-ink-strong)] shadow-none outline-none placeholder:text-[var(--ui-ink-faint)] focus-visible:ring-0 sm:min-h-[44rem] sm:px-6",placeholder:"Write the page in Markdown"})})]}),e.jsxs("section",{className:j(_,"overflow-hidden"),children:[e.jsx("div",{className:"border-b border-[var(--ui-border-subtle)] px-4 py-3 sm:px-6",children:e.jsx("div",{className:x,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(xa,{markdown:l.contentMarkdown,spaceId:y})})})]})]})]})]})}),e.jsx(L,{open:S==="wiki-link",onOpenChange:a=>!a&&p(null),title:"Insert wiki link",description:"Search pages.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx(T,{autoFocus:!0,value:D,onChange:a=>K(a.target.value),placeholder:"Search wiki pages",className:"h-11 rounded-2xl border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] text-[14px] text-[var(--ui-ink-strong)] placeholder:text-[var(--ui-ink-faint)]"}),e.jsx("div",{className:"grid max-h-[22rem] gap-2 overflow-y-auto",children:se.length>0?se.map(a=>e.jsxs("button",{type:"button",className:fe,onClick:()=>{I(`[[${a.slug}]]`),p(null),K("")},children:[e.jsx("div",{className:"break-words text-[14px] font-semibold text-[var(--ui-ink-strong)]",children:a.title}),e.jsx("div",{className:"mt-1 break-all text-[12px] leading-5 text-[var(--ui-ink-faint)]",children:a.slug}),a.summary?e.jsx("div",{className:"mt-1 break-words text-[12px] leading-5 text-[var(--ui-ink-soft)]",children:a.summary}):null]},a.id)):e.jsx("div",{className:"rounded-[18px] border border-dashed border-[var(--ui-border-strong)] px-4 py-8 text-center text-[13px] text-[var(--ui-ink-faint)]",children:"No pages match this search."})})]})}),e.jsx(L,{open:S==="forge-link",onOpenChange:a=>!a&&p(null),title:"Insert Forge link",description:"Search Forge entities.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx(T,{autoFocus:!0,value:V,onChange:a=>H(a.target.value),placeholder:"Search Forge entities",className:"h-11 rounded-2xl border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] text-[14px] text-[var(--ui-ink-strong)] placeholder:text-[var(--ui-ink-faint)]"}),e.jsx("div",{className:"grid max-h-[22rem] gap-2 overflow-y-auto",children:te.length>0?te.map(a=>e.jsxs("button",{type:"button",className:fe,onClick:()=>{const[s,n]=a.value.split(":");I(`[[forge:${s}:${n}]]`),p(null),H("")},children:[e.jsx("div",{className:"break-words text-[14px] font-semibold text-[var(--ui-ink-strong)]",children:a.label}),a.description?e.jsx("div",{className:"mt-1 break-words text-[12px] leading-5 text-[var(--ui-ink-soft)]",children:a.description}):null]},a.value)):e.jsx("div",{className:"rounded-[18px] border border-dashed border-[var(--ui-border-strong)] px-4 py-8 text-center text-[13px] text-[var(--ui-ink-faint)]",children:"No entities match this search."})})]})}),e.jsx(L,{open:S==="infobox",onOpenChange:a=>!a&&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(C,{onClick:()=>{I(`:::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(L,{open:S==="admonition",onOpenChange:a=>!a&&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:va,value:B,onChange:a=>Y(a.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(E,{value:f,onChange:a=>z(a.target.value),rows:4,placeholder:"Admonition text"}),e.jsx(C,{disabled:!B||!f.trim(),onClick:()=>{I(`:::${B}
16
+ ${f.trim()}
17
+ :::
18
+ `),p(null)},children:"Insert admonition"})]})}),e.jsx(L,{open:S==="related",onOpenChange:a=>!a&&p(null),title:"Insert related block",description:"Add an explicit related-pages block.",children:e.jsxs("div",{className:"grid gap-3",children:[e.jsx(E,{value:f,onChange:a=>z(a.target.value),rows:5,placeholder:`[[page-one]]
19
+ [[page-two|Readable label]]`}),e.jsx(C,{disabled:!f.trim(),onClick:()=>{I(`:::forge-related
20
+ ${f.trim()}
21
+ :::
22
+ `),p(null)},children:"Insert related block"})]})}),e.jsx(L,{open:S==="media",onOpenChange:a=>!a&&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(E,{value:f,onChange:a=>z(a.target.value),rows:5,placeholder:`Image: /path/to/file.png
23
+ Caption: Inspiration frame`}),e.jsx(C,{disabled:!f.trim(),onClick:()=>{I(`:::forge-media
24
+ ${f.trim()}
25
+ :::
26
+ `),p(null)},children:"Insert media block"})]})}),e.jsx(ye,{open:Pe,onOpenChange:Q,children:e.jsxs(Ne,{children:[e.jsx(Ce,{className:"fixed inset-0 z-50 surface-overlay backdrop-blur-sm"}),e.jsxs(Se,{className:"fixed left-1/2 top-[14vh] z-50 w-[min(28rem,calc(100vw-1.5rem))] -translate-x-1/2 rounded-[28px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-popover)] p-4 shadow-[var(--ui-shadow-floating)] sm:p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(Ie,{className:"font-display text-[1.2rem] tracking-[-0.04em] text-[var(--ui-ink-strong)]",children:"Choose wiki space"}),e.jsx(Te,{className:"mt-1 text-[13px] leading-6 text-[var(--ui-ink-soft)]",children:"Save this page into a different wiki space."})]}),e.jsx($e,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-2 text-[var(--ui-ink-soft)] transition hover:bg-[var(--ui-surface-2)] hover:text-[var(--ui-ink-strong)]","aria-label":"Close space picker",children:e.jsx(we,{className:"size-4"})})})]}),e.jsx("div",{className:"mt-4 grid gap-2",children:(ge=w.data)==null?void 0:ge.settings.spaces.map(a=>{const s=a.id===y;return e.jsxs("button",{type:"button",className:j("flex min-w-0 items-center justify-between gap-3 rounded-[22px] border px-4 py-3 text-left transition",s?"border-[color-mix(in_srgb,var(--primary)_28%,transparent)] bg-[var(--ui-accent-soft)] text-[var(--ui-ink-strong)]":"border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] text-[var(--ui-ink-medium)] hover:bg-[var(--ui-surface-2)] hover:text-[var(--ui-ink-strong)]"),onClick:()=>{const n=new URLSearchParams(A);n.set("spaceId",a.id),Oe(n,{replace:!0}),Q(!1)},children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[14px] font-semibold",children:a.label}),e.jsx("span",{className:"mt-1 block break-words text-[12px] leading-5 text-[var(--ui-ink-soft)]",children:a.description||`/${a.slug}`})]}),s?e.jsx(aa,{className:"size-4 shrink-0 text-[var(--primary)]"}):null]},a.id)})})]})]})})]})}export{Ma as WikiEditorPage};
@@ -0,0 +1 @@
1
+ import{b5 as F,c2 as J,r as R,j as s,aG as D,c7 as E,b7 as Q}from"./vendor-Dnkkx2co.js";import{j as H,i as q,k as z}from"./state-vCcAT5Hq.js";import{W as A}from"./wiki-ingest-modal-DyqBEZcC.js";import{P as _}from"./page-hero-ffKzgyW3.js";import{fg as U,S as O,E as B,C as W,B as f,I as w,Z as G,a as $,bY as Y,fk as Z}from"./index-EqQsXoat.js";import"./ui-C1iwpj2-.js";import"./motion-Lt5B1XuE.js";import"./forms-hB0SqEh-.js";import"./board-dIX6etHh.js";import"./graph-DDUZNRsO.js";const V=[{value:"all",label:"All"},{value:"queued",label:"Queued"},{value:"processing",label:"Processing"},{value:"completed",label:"Completed"},{value:"failed",label:"Failed"},{value:"review",label:"Review"},{value:"reviewed",label:"Reviewed"}];function X(l){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(l))}function ee(l,o){return o==="all"?!0:l.job.status===o||l.job.phase===o}function me(){var N,y,S,C,I,P;const l=F(),o=H(),[i,m]=J(),c=i.get("spaceId")||"",j=i.get("q")||"",h=i.get("tag")||"all",g=i.get("from")||"",p=i.get("to")||"",K=i.get("ingest")==="1",k=i.get("ingestJobId"),r=q({queryKey:["forge-wiki-settings"],queryFn:Y}),d=q({queryKey:["forge-wiki-ingest-history",c],queryFn:()=>Z({spaceId:c||void 0,limit:200}),enabled:r.isSuccess}),x=z({mutationFn:e=>U(e),onSuccess:async(e,a)=>{if(await o.invalidateQueries({queryKey:["forge-wiki-ingest-history"]}),await o.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),k===a){const t=new URLSearchParams(i);t.delete("ingest"),t.delete("ingestJobId"),m(t,{replace:!0})}}}),u=(e,a)=>{const t=new URLSearchParams(i);a.trim()?t.set(e,a.trim()):t.delete(e),m(t,{replace:!0})},v=R.useMemo(()=>{var t;const e=((t=d.data)==null?void 0:t.jobs)??[],a=j.trim().toLowerCase();return e.filter(n=>{if(!ee(n,h))return!1;const L=n.job.createdAt.slice(0,10);return g&&L<g||p&&L>p?!1:a?[n.job.titleHint,n.job.latestMessage,n.job.sourceLocator,n.job.status,n.job.phase,n.job.mimeType].join(" ").toLowerCase().includes(a):!0})},[g,(N=d.data)==null?void 0:N.jobs,j,h,p]),M=c||((S=(y=r.data)==null?void 0:y.settings.spaces[0])==null?void 0:S.id)||"",b=e=>{const a=new URLSearchParams(i);a.set("ingest","1"),e?a.set("ingestJobId",e):a.delete("ingestJobId"),m(a,{replace:!0})},T=()=>{const e=new URLSearchParams(i);e.delete("ingest"),e.delete("ingestJobId"),m(e,{replace:!0})};return r.isLoading||d.isLoading?s.jsx(O,{eyebrow:"KarpaWiki",title:"Loading ingest history",description:"Gathering prior imports, statuses, and review state.",columns:1,blocks:6}):r.isError||d.isError?s.jsx(B,{eyebrow:"KarpaWiki",error:r.error??d.error,onRetry:()=>{r.refetch(),d.refetch()}}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-3 py-4 sm:px-5 lg:px-6",children:s.jsxs("div",{className:"mx-auto grid w-full max-w-[1480px] gap-5",children:[s.jsx(_,{title:"KarpaWiki Ingest History",description:"Search prior ingests, reopen a review, or clear ingest records without touching pages and entities that were already published.",badge:`${v.length} matching jobs`}),s.jsxs(W,{className:"grid gap-4",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",children:"History Filters"}),s.jsx("div",{className:"mt-2 text-sm text-[var(--ui-ink-soft)]",children:"Narrow by free text, date range, space, or status tags."})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(f,{variant:"secondary",onClick:()=>l(`/wiki${c?`?spaceId=${encodeURIComponent(c)}`:""}`),children:"Back to KarpaWiki"}),s.jsxs(f,{onClick:()=>b(),children:[s.jsx(D,{className:"size-3.5"}),"New ingest"]})]})]}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1.4fr)_minmax(0,0.8fr)_minmax(0,0.8fr)_minmax(0,0.8fr)]",children:[s.jsxs("label",{className:"grid gap-2",children:[s.jsx("span",{className:"text-sm text-[var(--ui-ink-soft)]",children:"Free text"}),s.jsx(w,{value:j,onChange:e=>u("q",e.target.value),placeholder:"title, source, status, failure message…"})]}),s.jsxs("label",{className:"grid gap-2",children:[s.jsx("span",{className:"text-sm text-[var(--ui-ink-soft)]",children:"From"}),s.jsx(w,{type:"date",value:g,onChange:e=>u("from",e.target.value)})]}),s.jsxs("label",{className:"grid gap-2",children:[s.jsx("span",{className:"text-sm text-[var(--ui-ink-soft)]",children:"To"}),s.jsx(w,{type:"date",value:p,onChange:e=>u("to",e.target.value)})]}),s.jsxs("label",{className:"grid gap-2",children:[s.jsx("span",{className:"text-sm text-[var(--ui-ink-soft)]",children:"Space"}),s.jsxs("select",{className:"h-11 rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] px-3 text-sm text-[var(--ui-ink-strong)]",value:c,onChange:e=>u("spaceId",e.target.value),children:[s.jsx("option",{value:"",children:"All spaces"}),(((C=r.data)==null?void 0:C.settings.spaces)??[]).map(e=>s.jsx("option",{value:e.id,children:e.label},e.id))]})]})]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:V.map(e=>s.jsx("button",{type:"button",className:G("rounded-full px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] transition",h===e.value?"bg-[var(--primary)]/[0.18] text-[var(--primary)]":"bg-[var(--ui-surface-1)] text-[var(--ui-ink-soft)] hover:bg-[var(--ui-surface-2)] hover:text-[var(--ui-ink-strong)]"),onClick:()=>u("tag",e.value==="all"?"":e.value),children:e.label},e.value))})]}),v.length===0?s.jsx($,{eyebrow:"KarpaWiki ingest",title:"No ingest jobs match these filters",description:"Try widening the dates or clearing a status tag."}):s.jsx("div",{className:"grid gap-3",children:v.map(e=>{const a=e.job.titleHint||e.job.latestMessage||e.job.sourceLocator||"KarpaWiki ingest",t=!["queued","processing"].includes(e.job.status);return s.jsxs(W,{className:"grid min-w-0 gap-4",children:[s.jsxs("div",{className:"grid min-w-0 gap-3 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-start",children:[s.jsxs("button",{type:"button",className:"min-w-0 max-w-full text-left",onClick:()=>b(e.job.id),children:[s.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[s.jsx("span",{className:"text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:"KarpaWiki ingest"}),s.jsx("span",{className:"rounded-full border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] px-2.5 py-1 text-[10px] uppercase tracking-[0.16em] text-[var(--ui-ink-soft)]",children:e.job.status}),s.jsx("span",{className:"rounded-full border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] px-2.5 py-1 text-[10px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:e.job.phase})]}),s.jsx("div",{className:"mt-3 break-words text-lg font-semibold text-[var(--ui-ink-strong)]",children:a}),s.jsxs("div",{className:"mt-2 flex min-w-0 flex-wrap gap-x-4 gap-y-1 text-sm text-[var(--ui-ink-soft)]",children:[s.jsxs("span",{children:[e.job.progressPercent,"% ·"," ",e.job.createdPageCount," pages ·"," ",e.job.createdEntityCount," entities"]}),s.jsx("span",{children:X(e.job.createdAt)}),e.job.sourceLocator?s.jsx("span",{className:"min-w-0 max-w-full break-all",children:e.job.sourceLocator}):null]})]}),s.jsxs("div",{className:"flex min-w-0 flex-wrap gap-2 sm:justify-end",children:[s.jsx(f,{variant:"secondary",size:"sm",className:"max-sm:flex-1",onClick:()=>b(e.job.id),children:"Open review"}),s.jsxs(f,{variant:"secondary",size:"sm",className:"max-sm:flex-1",disabled:!t||x.isPending,pending:x.isPending&&x.variables===e.job.id,pendingLabel:"Deleting",onClick:()=>{!t||!window.confirm("Delete this ingest history entry? Published pages and entities will stay, but discarded or unreviewed ingest artifacts will be removed.")||x.mutateAsync(e.job.id)},children:[s.jsx(E,{className:"size-3.5"}),"Delete"]})]})]}),e.job.errorMessage?s.jsx("div",{className:"rounded-[18px] border border-rose-400/18 bg-rose-500/[0.08] px-4 py-3 text-sm text-rose-100/86",children:e.job.errorMessage}):null,["queued","processing"].includes(e.job.status)?s.jsxs("div",{className:"inline-flex items-center gap-2 text-sm text-[var(--ui-ink-soft)]",children:[s.jsx(Q,{className:"size-4 animate-spin"}),"This ingest is still active and cannot be deleted yet."]}):null]},e.job.id)})})]})}),s.jsx(A,{open:K,onOpenChange:e=>{e||T()},spaces:((I=r.data)==null?void 0:I.settings.spaces)??[],llmProfiles:((P=r.data)==null?void 0:P.settings.llmProfiles)??[],initialSpaceId:M,selectedJobId:k,onJobSelected:e=>b(e)})]})}export{me as WikiIngestHistoryPage};
@@ -0,0 +1 @@
1
+ import{b5 as Pe,r as p,j as e,aK as se,dD as te,dE as Le,aN as Ke,dF as Fe,cg as Me,aG as G,dG as be,b7 as $e,b3 as he}from"./vendor-Dnkkx2co.js";import{R as qe,P as ze,O as De,C as Qe,T as Re,D as We,a as Ue}from"./ui-C1iwpj2-.js";import{j as Oe,i as re,k as D}from"./state-vCcAT5Hq.js";import{fb as Be,fc as Ge,fd as ye,fe as He,ff as Ve,fg as Ze,Z as c,I as je,T as Ye,B as C,b as ae,c as ie,g as Xe,fh as Je,fi as et,fj as tt}from"./index-EqQsXoat.js";const $=new Set(["queued","processing"]),Ne=15e3,j="border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)]",z="border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)]",q="border-[color-mix(in_srgb,var(--primary)_30%,transparent)] bg-[var(--ui-accent-soft)] text-[var(--ui-ink-strong)]",H="border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] text-[var(--ui-ink-medium)] hover:bg-[var(--ui-surface-2)] hover:text-[var(--ui-ink-strong)]",at=["goal","project","task","habit","strategy","psyche_value","flashcard","note"];function ke(i){return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(i))}function _(i,a){const r=i[a];return typeof r=="number"&&Number.isFinite(r)?r:null}function y(i,a){const r=i[a];return typeof r=="string"&&r.trim().length>0?r:null}function it(i,a){const r=y(i.metadata,"currentFileName")??y(i.metadata,"fileName")??"current source",b=y(i.metadata,"status")??"in_progress",o=_(i.metadata,"chunkIndex"),x=_(i.metadata,"chunkCount"),N=_(i.metadata,"currentFileIndex"),f=_(i.metadata,"currentFileTotal"),k=N!==null&&f!==null?`${r} (${N}/${f})`:r,u=o!==null&&x!==null&&x>1?` · chunk ${o}/${x}`:"";return`Waiting for OpenAI on ${k}${u}. ${a} polls · ${b}.`}function st(i){const a=[];for(const r of i){const b=y(r.metadata,"scope"),x=y(r.metadata,"eventKey")==="llm_compile_background_polled",N=y(r.metadata,"currentFileName")??y(r.metadata,"fileName"),f=_(r.metadata,"chunkIndex"),k=_(r.metadata,"chunkCount"),u=x?["poll",b??"",N??"",f??"",k??""].join(":"):null,m=a[a.length-1],A=m&&y(m.metadata,"eventKey"),w=m&&(y(m.metadata,"currentFileName")??y(m.metadata,"fileName")),E=m&&_(m.metadata,"chunkIndex"),h=m&&_(m.metadata,"chunkCount"),P=m&&A==="llm_compile_background_polled"?["poll",y(m.metadata,"scope")??"",w??"",E??"",h??""].join(":"):null;if(x&&m&&P===u){a[a.length-1]={...r,repetitionCount:m.repetitionCount+1,metadata:{...r.metadata,aggregatedPollCount:m.repetitionCount+1}};continue}a.push({...r,repetitionCount:1})}return a}function V(i){return Xe(i)}function we(i){return typeof i=="string"&&at.includes(i)}function rt(i,a){return typeof a.title=="string"&&a.title.trim().length>0?a.title:typeof a.displayName=="string"&&a.displayName.trim().length>0?a.displayName:typeof a.statement=="string"&&a.statement.trim().length>0?a.statement:`${i}:${String(a.id??"")}`}function nt(i,a){const b=[a.description,a.summary,a.overview,a.valuedDirection,a.whyItMatters,a.originNote].find(o=>typeof o=="string"&&o.trim().length>0);return b||(i==="note"&&typeof a.kind=="string"?a.kind:"")}function lt({candidate:i,decision:a,onDecisionChange:r,spaceId:b}){const o=we(i.payload.entityType)?i.payload.entityType:null,[x,N]=p.useState(a.mappedEntityLabel||i.title||""),[f,k]=p.useState(a.targetNoteLabel||i.title||""),u=typeof i.payload.contentMarkdown=="string"?i.payload.contentMarkdown:typeof i.payload.patchSummary=="string"?i.payload.patchSummary:typeof i.payload.rationale=="string"?i.payload.rationale:i.summary,m=re({queryKey:["forge-wiki-ingest-map-search",o,x.trim()],enabled:i.candidateType==="entity"&&a.action==="map_existing"&&o!==null&&x.trim().length>0,queryFn:async()=>{var F;const v=(await Je({searches:[{entityTypes:o?[o]:void 0,query:x.trim(),limit:8}]})).results[0];return((F=v==null?void 0:v.matches)==null?void 0:F.filter(g=>!!(g&&we(g.entityType)&&typeof g.id=="string"&&g.entity&&typeof g.entity=="object")).map(g=>({entityType:g.entityType,entityId:g.id,label:rt(g.entityType,g.entity),description:nt(g.entityType,g.entity),kind:V(g.entityType)})))??[]}}),A=m.data??[],w=re({queryKey:["forge-wiki-ingest-merge-search",b,f.trim()],enabled:i.candidateType==="page"&&a.action==="merge_existing"&&f.trim().length>0,queryFn:async()=>(await et({spaceId:b,kind:"wiki",mode:"text",query:f.trim(),limit:8})).results.map(v=>({noteId:v.page.id,title:v.page.title,slug:v.page.slug,summary:v.page.summary}))}),E=w.data??[],h=a.mappedEntityId&&a.mappedEntityType?A.find(s=>s.entityId===a.mappedEntityId&&s.entityType===a.mappedEntityType)??(a.mappedEntityLabel?{entityId:a.mappedEntityId,entityType:a.mappedEntityType,label:a.mappedEntityLabel,kind:V(a.mappedEntityType)}:null):null,P=a.targetNoteId?E.find(s=>s.noteId===a.targetNoteId)??(a.targetNoteLabel?{noteId:a.targetNoteId,title:a.targetNoteLabel}:null):null;return e.jsxs("div",{className:c("rounded-[24px] border p-4",j),children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:i.candidateType.replaceAll("_"," ")}),e.jsx("div",{className:"mt-2 text-base font-semibold text-[var(--ui-ink-strong)]",children:i.title||i.targetKey||"Untitled candidate"}),o?e.jsx("div",{className:"mt-2",children:V(o)?e.jsx(ae,{kind:V(o),label:o.replaceAll("_"," "),compact:!0,gradient:!1}):e.jsx(ie,{className:"bg-[var(--ui-surface-2)] text-[var(--ui-ink-medium)]",children:o.replaceAll("_"," ")})}):null,i.summary?e.jsx("div",{className:"mt-1 text-sm leading-6 text-[var(--ui-ink-soft)]",children:i.summary}):null]}),e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-1",children:[e.jsx("button",{type:"button",className:c("rounded-full px-3 py-1.5 text-xs font-medium transition",a.action==="keep"?"bg-[var(--ui-accent-soft)] text-[var(--ui-ink-strong)]":"text-[var(--ui-ink-soft)] hover:text-[var(--ui-ink-strong)]"),onClick:()=>r({...a,action:"keep"}),children:"Keep"}),i.candidateType==="entity"&&o?e.jsx("button",{type:"button",className:c("rounded-full px-3 py-1.5 text-xs font-medium transition",a.action==="map_existing"?"bg-[var(--ui-info-soft)] text-[var(--ui-ink-strong)]":"text-[var(--ui-ink-soft)] hover:text-[var(--ui-ink-strong)]"),onClick:()=>r({...a,action:"map_existing",mappedEntityType:o}),children:"Map existing"}):null,i.candidateType==="page"?e.jsx("button",{type:"button",className:c("rounded-full px-3 py-1.5 text-xs font-medium transition",a.action==="merge_existing"?"bg-[var(--ui-info-soft)] text-[var(--ui-ink-strong)]":"text-[var(--ui-ink-soft)] hover:text-[var(--ui-ink-strong)]"),onClick:()=>r({...a,action:"merge_existing"}),children:"Merge existing"}):null,e.jsx("button",{type:"button",className:c("rounded-full px-3 py-1.5 text-xs font-medium transition",a.action==="discard"?"bg-[var(--ui-surface-2)] text-[var(--ui-ink-strong)]":"text-[var(--ui-ink-soft)] hover:text-[var(--ui-ink-strong)]"),onClick:()=>r({...a,action:"discard"}),children:"Discard"})]})]}),i.candidateType==="entity"&&o&&a.action==="map_existing"?e.jsxs("div",{className:c("mt-4 grid gap-3 rounded-[18px] border p-4",z),children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:["Map to existing ",o.replaceAll("_"," ")]}),h?e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-2.5 py-1.5",children:[h.kind?e.jsx(ae,{kind:h.kind,label:h.label,compact:!0,gradient:!1,className:"max-w-[20rem]"}):e.jsx(ie,{className:"bg-[var(--ui-surface-2)] text-[var(--ui-ink-medium)]",children:h.label}),e.jsx("button",{type:"button",className:"rounded-full text-[var(--ui-ink-faint)] transition hover:text-[var(--ui-ink-strong)]",onClick:()=>r({...a,mappedEntityId:void 0,mappedEntityLabel:void 0}),"aria-label":"Clear mapped entity",children:e.jsx(se,{className:"size-3.5"})})]})}):null,e.jsxs("div",{className:c("flex items-center gap-3 rounded-[20px] border px-4 py-3",j),children:[e.jsx(he,{className:"size-4 text-[var(--ui-ink-faint)]"}),e.jsx("input",{value:x,onChange:s=>{N(s.target.value),a.mappedEntityId&&r({...a,mappedEntityId:void 0,mappedEntityLabel:void 0})},placeholder:`Search existing ${o.replaceAll("_"," ")}`,className:"min-w-0 flex-1 bg-transparent text-sm text-[var(--ui-ink-strong)] placeholder:text-[var(--ui-ink-faint)] focus:outline-none"})]}),e.jsx("div",{className:"grid gap-2",children:m.isPending?e.jsx("div",{className:c("rounded-[16px] border px-3 py-3 text-sm text-[var(--ui-ink-faint)]",j),children:"Searching Forge…"}):A.length===0?e.jsxs("div",{className:"rounded-[16px] border border-dashed border-[var(--ui-border-subtle)] px-3 py-3 text-sm text-[var(--ui-ink-faint)]",children:["No existing ",o.replaceAll("_"," ")," matches yet."]}):A.map(s=>{const v=a.mappedEntityType===s.entityType&&a.mappedEntityId===s.entityId;return e.jsx("button",{type:"button",className:c("flex w-full items-start justify-between gap-3 rounded-[18px] border px-3 py-3 text-left transition",v?q:"border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] text-[var(--ui-ink-medium)] hover:bg-[var(--ui-surface-2)] hover:text-[var(--ui-ink-strong)]"),onClick:()=>r({action:"map_existing",mappedEntityType:s.entityType,mappedEntityId:s.entityId,mappedEntityLabel:s.label}),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:s.kind?e.jsx(ae,{kind:s.kind,label:s.label,compact:!0,gradient:!1}):s.label}),s.description?e.jsx("div",{className:"mt-1 text-xs leading-5 text-[var(--ui-ink-faint)]",children:s.description}):null]})},`${s.entityType}:${s.entityId}`)})})]}):null,i.candidateType==="page"&&a.action==="merge_existing"?e.jsxs("div",{className:c("mt-4 grid gap-3 rounded-[18px] border p-4",z),children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:"Merge into existing page"}),P?e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-2.5 py-1.5",children:[e.jsx(ie,{className:"bg-[var(--ui-surface-2)] text-[var(--ui-ink-medium)]",children:P.title}),e.jsx("button",{type:"button",className:"rounded-full text-[var(--ui-ink-faint)] transition hover:text-[var(--ui-ink-strong)]",onClick:()=>r({...a,targetNoteId:void 0,targetNoteLabel:void 0}),"aria-label":"Clear merge target",children:e.jsx(se,{className:"size-3.5"})})]})}):null,e.jsxs("div",{className:c("flex items-center gap-3 rounded-[20px] border px-4 py-3",j),children:[e.jsx(he,{className:"size-4 text-[var(--ui-ink-faint)]"}),e.jsx("input",{value:f,onChange:s=>{k(s.target.value),a.targetNoteId&&r({...a,targetNoteId:void 0,targetNoteLabel:void 0})},placeholder:"Search existing wiki pages",className:"min-w-0 flex-1 bg-transparent text-sm text-[var(--ui-ink-strong)] placeholder:text-[var(--ui-ink-faint)] focus:outline-none"})]}),e.jsx("div",{className:"grid gap-2",children:w.isPending?e.jsx("div",{className:c("rounded-[16px] border px-3 py-3 text-sm text-[var(--ui-ink-faint)]",j),children:"Searching Forge…"}):E.length===0?e.jsx("div",{className:"rounded-[16px] border border-dashed border-[var(--ui-border-subtle)] px-3 py-3 text-sm text-[var(--ui-ink-faint)]",children:"No existing wiki pages match yet."}):E.map(s=>{const v=a.targetNoteId===s.noteId;return e.jsx("button",{type:"button",className:c("flex w-full items-start justify-between gap-3 rounded-[18px] border px-3 py-3 text-left transition",v?q:"border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] text-[var(--ui-ink-medium)] hover:bg-[var(--ui-surface-2)] hover:text-[var(--ui-ink-strong)]"),onClick:()=>r({action:"merge_existing",targetNoteId:s.noteId,targetNoteLabel:s.title}),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:s.title}),e.jsxs("div",{className:"mt-1 text-xs leading-5 text-[var(--ui-ink-faint)]",children:[s.slug?`${s.slug}`:"",s.summary?`${s.slug?" · ":""}${s.summary}`:""]})]})},s.noteId)})})]}):null,u?e.jsx("div",{className:c("mt-4 rounded-[18px] border px-4 py-3 text-sm leading-6 text-[var(--ui-ink-medium)]",z),children:e.jsx("pre",{className:"whitespace-pre-wrap font-sans",children:u})}):null]})}function pt({open:i,onOpenChange:a,spaces:r,llmProfiles:b,initialSpaceId:o,selectedJobId:x,onJobSelected:N,linkedEntityHints:f=[]}){var ge;const k=Pe(),u=Oe(),[m,A]=p.useState("files"),[w,E]=p.useState(o),[h,P]=p.useState(""),[s,v]=p.useState(""),[F,g]=p.useState(""),[Q,Z]=p.useState([]),[Ee,R]=p.useState(!1),[Ie,Se]=p.useState(!1),I=p.useMemo(()=>b.filter(t=>t.enabled&&!!t.secretId),[b]),[W,ne]=p.useState(((ge=I[0])==null?void 0:ge.id)??""),[U,Te]=p.useState("auto"),[Y,le]=p.useState({}),[O,S]=p.useState(null),[B,T]=p.useState(null),oe=p.useRef({});p.useEffect(()=>{o&&E(o)},[o]),p.useEffect(()=>{var t;!W&&((t=I[0])!=null&&t.id)&&ne(I[0].id)},[W,I]);const M=I.find(t=>t.id===W)??I[0]??null,L=re({queryKey:["forge-wiki-ingest-job",x],queryFn:()=>tt(x),enabled:i&&!!x,refetchInterval:t=>{const d=t.state.data;return d&&$.has(d.job.status)?2e3:!1}});p.useEffect(()=>{const t=L.data;t&&le(d=>{const l={};for(const K of t.candidates)l[K.id]=d[K.id]??(K.status==="rejected"?{action:"discard"}:{action:"keep"});return l})},[L.data]),p.useEffect(()=>{B&&T(null)},[Y,B]);const X=D({mutationFn:async t=>Be(t),onSuccess:(t,d)=>{t.job&&u.setQueryData(["forge-wiki-ingest-job",d],t.job),u.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),u.invalidateQueries({queryKey:["forge-wiki-ingest-history"]})}});p.useEffect(()=>{const t=L.data;if(!t||!$.has(t.job.status))return;const d=t.logs.reduce((ve,Ae)=>{const fe=Number(new Date(Ae.createdAt));return Number.isFinite(fe)?Math.max(ve,fe):ve},0),l=Number(new Date(t.job.updatedAt)),K=Math.max(Number.isFinite(l)?l:0,d);if(!Number.isFinite(K)||K<=0)return;const ee=Date.now();if(!(ee-K>=Ne)||X.isPending)return;const _e=oe.current[t.job.id]??0;ee-_e<Ne||(oe.current[t.job.id]=ee,X.mutate(t.job.id))},[L.data,X]);const de=D({mutationFn:async()=>{if(!M)throw new Error("Set up an OpenAI wiki ingest profile first. Forge now requires an LLM profile before auto-ingest can turn source material into draft pages and entities.");if(m==="files"){if(Q.length===0)throw new Error("Select at least one file to ingest.");return Ge({files:Q,spaceId:w||void 0,titleHint:h.trim()||void 0,llmProfileId:M.id,parseStrategy:U,createAsKind:"wiki",linkedEntityHints:f})}if(m==="url"){if(!s.trim())throw new Error("Enter a URL to ingest.");return ye({spaceId:w||void 0,titleHint:h.trim()||void 0,sourceKind:"url",sourceUrl:s.trim(),llmProfileId:M.id,parseStrategy:U,createAsKind:"wiki",linkedEntityHints:f})}if(!F.trim())throw new Error("Paste some text to ingest.");return ye({spaceId:w||void 0,titleHint:h.trim()||void 0,sourceKind:"raw_text",sourceText:F,mimeType:"text/plain",llmProfileId:M.id,parseStrategy:U,createAsKind:"wiki",linkedEntityHints:f})},onSuccess:async t=>{var l;const d=((l=t.job)==null?void 0:l.job.id)??null;await u.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),await u.invalidateQueries({queryKey:["forge-wiki-ingest-history"]}),d&&N(d),S(null),T(null)},onError:t=>{S(t instanceof Error?t.message:"Unable to start ingest.")}}),ce=D({mutationFn:async()=>{if(!x||!L.data)throw new Error("Choose an ingest job first.");const t=L.data.candidates.map(d=>{const l=Y[d.id]??{action:"keep"};if(l.action==="map_existing"&&(!l.mappedEntityType||!l.mappedEntityId))throw new Error(`Choose an existing ${String(d.payload.entityType??"entity").replaceAll("_"," ")} before publishing the review.`);if(l.action==="merge_existing"&&!l.targetNoteId)throw new Error(`Choose an existing wiki page before publishing the review for ${d.title||"this page candidate"}.`);return l.action==="map_existing"?{candidateId:d.id,action:"map_existing",mappedEntityType:l.mappedEntityType,mappedEntityId:l.mappedEntityId}:l.action==="merge_existing"?{candidateId:d.id,action:"merge_existing",targetNoteId:l.targetNoteId}:{candidateId:d.id,action:l.action}});return He({jobId:x,decisions:t})},onSuccess:async t=>{T(null),u.setQueryData(["forge-wiki-ingest-job",t.job.job.id],t.job),await Promise.all([u.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),u.invalidateQueries({queryKey:["forge-wiki-ingest-history"]}),u.invalidateQueries({queryKey:["forge-wiki-ingest-job",t.job.job.id]}),u.invalidateQueries({queryKey:["forge-wiki-home"]}),u.invalidateQueries({queryKey:["forge-wiki-page-by-slug"]}),u.invalidateQueries({queryKey:["forge-wiki-tree"]})])},onError:t=>{T(t instanceof Error?t.message:"Unable to publish review.")}}),ue=D({mutationFn:async()=>{if(!x)throw new Error("Choose an ingest job first.");return Ve(x)},onSuccess:async t=>{var l;const d=((l=t.job)==null?void 0:l.job.id)??null;await Promise.all([u.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),u.invalidateQueries({queryKey:["forge-wiki-ingest-history"]}),u.invalidateQueries({queryKey:["forge-wiki-ingest-job",x]})]),d&&N(d),S(null),T(null)},onError:t=>{S(t instanceof Error?t.message:"Unable to rerun ingest.")}}),me=D({mutationFn:async()=>{if(!x)throw new Error("Choose an ingest job first.");return Ze(x)},onSuccess:async()=>{await Promise.all([u.invalidateQueries({queryKey:["forge-wiki-ingest-jobs"]}),u.invalidateQueries({queryKey:["forge-wiki-ingest-history"]}),u.invalidateQueries({queryKey:["forge-wiki-ingest-job",x]})]),xe(),S(null),T(null)},onError:t=>{S(t instanceof Error?t.message:"Unable to delete ingest.")}}),n=L.data??null,Ce=n&&!$.has(n.job.status),J=p.useMemo(()=>(n==null?void 0:n.candidates.filter(t=>["suggested","rejected","failed"].includes(t.status)))??[],[n]),pe=p.useMemo(()=>st((n==null?void 0:n.logs)??[]),[n==null?void 0:n.logs]),xe=()=>{N(null),Z([]),v(""),g(""),P(""),S(null),T(null)};return e.jsx(qe,{open:i,onOpenChange:t=>{a(t),t||(S(null),T(null))},children:e.jsxs(ze,{children:[e.jsx(De,{className:"fixed inset-0 z-50 surface-overlay backdrop-blur-sm"}),e.jsxs(Qe,{className:"fixed inset-x-4 bottom-4 top-4 z-50 mx-auto flex max-w-[min(74rem,calc(100vw-2rem))] flex-col overflow-hidden rounded-[32px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-popover)] shadow-[var(--ui-shadow-floating)]",children:[e.jsx("div",{className:"border-b border-[var(--ui-border-subtle)] px-5 py-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",children:"KarpaWiki Ingest"}),e.jsx(Re,{className:"mt-2 font-display text-[1.5rem] tracking-[-0.04em] text-[var(--ui-ink-strong)]",children:n?"Ingest review and progress":"Build KarpaWiki memory from source files"}),e.jsx(We,{className:"mt-2 max-w-3xl text-sm leading-6 text-[var(--ui-ink-soft)]",children:"Upload notes, media, ZIP archives, links, or pasted text. Forge will process them in the background, propose pages and entities, and let you keep only what belongs."})]}),e.jsx(Ue,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded-full border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] p-2 text-[var(--ui-ink-soft)] transition hover:bg-[var(--ui-surface-2)] hover:text-[var(--ui-ink-strong)]","aria-label":"Close ingest modal",children:e.jsx(se,{className:"size-4"})})})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto px-5 py-5",children:n?e.jsxs("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:c("rounded-[28px] border p-4 sm:p-5",j),children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:["Job ",n.job.id]}),e.jsx("div",{className:"mt-2 text-xl font-semibold text-[var(--ui-ink-strong)]",children:n.job.latestMessage||"Ingest job"}),e.jsxs("div",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:[n.job.status," · ",n.job.phase," · started ",ke(n.job.createdAt)]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(C,{variant:"secondary",size:"sm",onClick:xe,children:"New ingest"}),Ce?e.jsxs(e.Fragment,{children:[e.jsxs(C,{variant:"secondary",size:"sm",pending:ue.isPending,pendingLabel:"Rerunning",onClick:()=>void ue.mutateAsync(),children:[e.jsx(G,{className:"size-3.5"}),"Rerun"]}),e.jsx(C,{variant:"ghost",size:"sm",className:"border border-rose-300/18 bg-rose-400/10 text-rose-100 hover:bg-rose-400/16",pending:me.isPending,pendingLabel:"Deleting",onClick:()=>{window.confirm("Delete this ingest history entry? Published pages or entities will stay, but discarded or unreviewed ingest data will be removed.")&&me.mutateAsync()},children:"Delete"})]}):null]})]}),e.jsx("div",{className:"mt-5 grid gap-3 sm:grid-cols-4",children:[{label:"Progress",value:`${n.job.progressPercent}%`},{label:"Files",value:`${n.job.processedFiles}/${n.job.totalFiles}`},{label:"Pages",value:String(n.job.createdPageCount)},{label:"Entities",value:String(n.job.createdEntityCount)}].map(t=>e.jsxs("div",{className:c("rounded-[22px] border px-4 py-3",z),children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:t.label}),e.jsx("div",{className:"mt-2 text-lg font-semibold text-[var(--ui-ink-strong)]",children:t.value})]},t.label))}),e.jsx("div",{className:"mt-5",children:e.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-[var(--ui-surface-2)]",children:e.jsx("div",{className:"h-full rounded-full bg-[var(--primary)] transition-all duration-300",style:{width:`${n.job.progressPercent}%`}})})}),O?e.jsx("div",{className:"mt-4 rounded-[20px] border border-rose-300/22 bg-rose-400/10 px-4 py-3 text-sm text-rose-100",children:O}):null]}),e.jsxs("div",{className:c("rounded-[28px] border p-4 sm:p-5",j),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:"Rich log"}),e.jsx(C,{variant:"secondary",size:"sm",onClick:()=>k(`/settings/logs?jobId=${encodeURIComponent(n.job.id)}`),children:"Open full logs"})]}),e.jsx("div",{className:"mt-4 grid max-h-[28rem] gap-2 overflow-y-auto",children:pe.length===0?e.jsx("div",{className:"rounded-[18px] border border-dashed border-[var(--ui-border-subtle)] px-4 py-4 text-sm text-[var(--ui-ink-faint)]",children:"Waiting for the backend to emit progress."}):pe.map(t=>e.jsx("div",{className:c("rounded-[18px] border px-4 py-3",z),children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"rounded-full border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-[var(--ui-ink-soft)]",children:t.level}),typeof t.metadata.scope=="string"?e.jsx("span",{className:"rounded-full border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-[var(--ui-ink-faint)]",children:t.metadata.scope}):null,typeof t.metadata.eventKey=="string"?e.jsx("span",{className:"rounded-full border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-[var(--ui-ink-faint)]",children:t.metadata.eventKey}):null]}),e.jsx("div",{className:"mt-2 text-sm text-[var(--ui-ink-strong)]",children:y(t.metadata,"eventKey")==="llm_compile_background_polled"?it(t,t.repetitionCount):t.message}),t.repetitionCount>1?e.jsxs("div",{className:"mt-2 text-xs text-[var(--ui-ink-faint)]",children:["Combined ",t.repetitionCount," repeated polling updates."]}):null,Object.keys(t.metadata).length>0?e.jsxs("details",{className:"mt-3",children:[e.jsx("summary",{className:"cursor-pointer text-xs text-[var(--ui-ink-faint)]",children:"View metadata"}),e.jsx("pre",{className:"mt-2 max-w-full overflow-x-auto whitespace-pre-wrap rounded-[14px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-code)] px-3 py-3 text-[11px] leading-5 text-[var(--ui-ink-soft)]",children:JSON.stringify(t.metadata,null,2)})]}):null]}),e.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-[var(--ui-ink-faint)]",children:ke(t.createdAt)})]})},t.id))})]})]}),e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:c("rounded-[28px] border p-4 sm:p-5",j),children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:"Source files"}),e.jsx("div",{className:"mt-4 grid gap-2",children:n.assets.map(t=>e.jsxs("div",{className:c("flex min-w-0 items-center justify-between gap-3 rounded-[18px] border px-4 py-3",z),children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium text-[var(--ui-ink-strong)]",children:t.fileName||t.sourceLocator||"Source"}),e.jsx("div",{className:"mt-1 text-xs text-[var(--ui-ink-faint)]",children:t.mimeType||t.sourceKind})]}),e.jsx("div",{className:"shrink-0 text-[11px] uppercase tracking-[0.14em] text-[var(--ui-ink-faint)]",children:t.status})]},t.id))})]}),e.jsxs("div",{className:c("rounded-[28px] border p-4 sm:p-5",j),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:"Review"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:"Keep the candidates that belong in Forge and discard the rest."})]}),$.has(n.job.status)?e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-3 py-2 text-xs text-[var(--ui-ink-soft)]",children:[e.jsx($e,{className:"size-3.5 animate-spin"}),"Processing"]}):null]}),e.jsx("div",{className:"mt-4 grid gap-3",children:J.length===0?e.jsx("div",{className:"rounded-[18px] border border-dashed border-[var(--ui-border-subtle)] px-4 py-4 text-sm text-[var(--ui-ink-faint)]",children:$.has(n.job.status)?"Candidates will appear here while the job progresses.":"This job has no reviewable candidates left."}):J.map(t=>e.jsx(lt,{candidate:t,spaceId:n.job.spaceId,decision:Y[t.id]??{action:"keep"},onDecisionChange:d=>le(l=>({...l,[t.id]:d}))},t.id))}),B?e.jsx("div",{className:"mt-4 rounded-[20px] border border-rose-300/22 bg-rose-400/10 px-4 py-3 text-sm text-rose-100",children:B}):null,J.length>0&&!$.has(n.job.status)?e.jsx("div",{className:"mt-5",children:e.jsxs(C,{className:"min-h-12",pending:ce.isPending,pendingLabel:"Publishing review",onClick:()=>void ce.mutateAsync(),children:[e.jsx(be,{className:"size-4"}),"Publish kept candidates"]})}):null]})]})]}):e.jsxs("div",{className:"grid gap-5 lg:grid-cols-[minmax(0,1.15fr)_minmax(18rem,0.85fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:[{id:"files",label:"Files and ZIP",detail:"Drag many files or one archive.",icon:te},{id:"url",label:"URL",detail:"Pull a webpage or remote file.",icon:Le},{id:"text",label:"Paste text",detail:"Turn notes or transcripts into pages.",icon:Ke}].map(t=>{const d=t.icon,l=t.id===m;return e.jsxs("button",{type:"button",className:c("rounded-[24px] border px-4 py-4 text-left transition",l?q:H),onClick:()=>A(t.id),children:[e.jsx(d,{className:"size-4 text-[var(--secondary)]"}),e.jsx("div",{className:"mt-3 text-sm font-semibold",children:t.label}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-[var(--ui-ink-faint)]",children:t.detail})]},t.id)})}),e.jsx("div",{className:c("rounded-[28px] border p-4 sm:p-5",j),children:e.jsxs("div",{className:"grid gap-4",children:[e.jsx(je,{value:h,onChange:t=>P(t.target.value),placeholder:"Optional title hint"}),m==="files"?e.jsxs("div",{className:c("rounded-[28px] border-2 border-dashed px-5 py-8 text-center transition",Ee?"border-[color-mix(in_srgb,var(--primary)_36%,transparent)] bg-[var(--ui-accent-soft)]":j),onDragEnter:t=>{t.preventDefault(),R(!0)},onDragLeave:t=>{t.preventDefault(),R(!1)},onDragOver:t=>{t.preventDefault(),R(!0)},onDrop:t=>{t.preventDefault(),R(!1);const d=Array.from(t.dataTransfer.files);Z(l=>[...l,...d])},children:[e.jsx("div",{className:"mx-auto flex size-14 items-center justify-center rounded-full border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)]",children:e.jsx(te,{className:"size-5 text-[var(--ui-ink-medium)]"})}),e.jsx("div",{className:"mt-4 text-base font-semibold text-[var(--ui-ink-strong)]",children:"Drop files, media, notes, or ZIP archives here"}),e.jsx("div",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-faint)]",children:"Forge accepts many files at once and queues the ingest in the background so the UI stays responsive."}),e.jsxs("label",{className:"mt-5 inline-flex cursor-pointer items-center gap-2 rounded-full border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-2 text-sm text-[var(--ui-ink-medium)] transition hover:bg-[var(--ui-surface-2)] hover:text-[var(--ui-ink-strong)]",children:[e.jsx(te,{className:"size-4"}),"Choose files",e.jsx("input",{type:"file",multiple:!0,className:"hidden",onChange:t=>Z(Array.from(t.target.files??[]))})]}),Q.length>0?e.jsx("div",{className:"mt-5 grid gap-2 text-left",children:Q.map(t=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[18px] border ${INGEST_PANEL_CLASS} px-4 py-3 text-sm text-[var(--ui-ink-medium)]",children:[e.jsx("span",{className:"truncate",children:t.name}),e.jsx("span",{className:"shrink-0 text-xs text-[var(--ui-ink-faint)]",children:t.name.toLowerCase().endsWith(".zip")?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Fe,{className:"size-3.5"}),"ZIP"]}):`${Math.max(1,Math.round(t.size/1024))} KB`})]},`${t.name}-${t.size}-${t.lastModified}`))}):null]}):null,m==="url"?e.jsx(je,{value:s,onChange:t=>v(t.target.value),placeholder:"https://example.com/source"}):null,m==="text"?e.jsx(Ye,{value:F,onChange:t=>g(t.target.value),placeholder:"Paste notes, transcripts, meeting writeups, or source material here…",className:"min-h-[18rem]"}):null]})})]}),e.jsxs("aside",{className:"grid h-fit gap-4",children:[M?null:e.jsxs("div",{className:"rounded-[30px] border border-[color-mix(in_srgb,var(--warning)_30%,transparent)] bg-[var(--ui-warning-soft)] p-5 shadow-[var(--ui-shadow-card)]",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 flex size-10 shrink-0 items-center justify-center rounded-full border border-amber-200/20 bg-amber-300/12 text-amber-100",children:e.jsx(Me,{className:"size-4.5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-amber-100/62",children:"OpenAI setup required for smart ingest"}),e.jsx("div",{className:"mt-2 text-lg font-semibold text-[var(--ui-ink-strong)]",children:"Forge can only do a raw import without OpenAI"}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-[var(--ui-ink-medium)]",children:"Without an OpenAI ingest profile, Forge cannot extract key insights, split the source into draft wiki pages, or propose Forge entities. The fallback is just a direct text import or media reference with no structured synthesis."}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-[var(--ui-ink-soft)]",children:"Set up the API key, model, thinking, and verbosity first, then come back here to build real draft pages and reviewable entity proposals."})]})]}),e.jsxs("div",{className:"mt-5 grid gap-3 sm:grid-cols-2",children:[e.jsxs(C,{className:"w-full",onClick:()=>{a(!1),k("/settings/wiki?setupLlm=1")},children:[e.jsx(G,{className:"size-4"}),"Open OpenAI setup"]}),e.jsx(C,{variant:"secondary",className:"w-full",onClick:()=>{a(!1),k("/settings/wiki")},children:"Open KarpaWiki settings"})]})]}),e.jsxs("div",{className:"rounded-[28px] border ${INGEST_PANEL_CLASS} p-4",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 text-left",onClick:()=>Se(t=>!t),children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:"Advanced"}),e.jsx("div",{className:"mt-2 text-sm text-[var(--ui-ink-medium)]",children:"Model, parse, and target controls."})]}),e.jsx(G,{className:"size-4 text-[var(--ui-ink-soft)]"})]}),Ie?e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"mb-2 text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:"Space"}),e.jsx("div",{className:"grid gap-2",children:r.map(t=>e.jsxs("button",{type:"button",className:c("rounded-[18px] border px-3 py-3 text-left text-sm transition",w===t.id?q:H),onClick:()=>E(t.id),children:[e.jsx("div",{children:t.label}),e.jsx("div",{className:"mt-1 text-xs text-[var(--ui-ink-faint)]",children:t.description||`/${t.slug}`})]},t.id))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-2 text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:"LLM profile"}),e.jsxs("div",{className:"grid gap-2",children:[I.map(t=>e.jsxs("button",{type:"button",className:c("rounded-[18px] border px-3 py-3 text-left text-sm transition",W===t.id?q:H),onClick:()=>ne(t.id),children:[e.jsx("div",{children:t.label}),e.jsx("div",{className:"mt-1 text-xs text-[var(--ui-ink-faint)]",children:t.model})]},t.id)),I.length===0?e.jsx("div",{className:"rounded-[18px] border border-dashed border-[var(--ui-border-subtle)] px-4 py-4 text-sm text-[var(--ui-ink-faint)]",children:"No enabled profile with a saved key yet."}):null]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-2 text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:"Parse mode"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-3",children:[{id:"auto",label:"Auto"},{id:"multimodal",label:"Multimodal"},{id:"text_only",label:"Text only"}].map(t=>e.jsx("button",{type:"button",className:c("rounded-[18px] border px-3 py-3 text-sm transition",U===t.id?q:H),onClick:()=>Te(t.id),children:t.label},t.id))})]})]}):null]}),e.jsxs("div",{className:"rounded-[28px] border border-[color-mix(in_srgb,var(--primary)_24%,transparent)] bg-[var(--ui-accent-soft)] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[var(--ui-ink-strong)]",children:[e.jsx(be,{className:"size-4 text-[var(--secondary)]"}),e.jsx("span",{className:"text-sm font-semibold",children:"Publish only what belongs"})]}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-[var(--ui-ink-soft)]",children:"Forge stages candidate pages, proposed entity records, and page updates first. You review the output before anything is committed to the live memory graph."})]}),O?e.jsx("div",{className:"rounded-[20px] border border-rose-300/22 bg-rose-400/10 px-4 py-3 text-sm text-rose-100",children:O}):null,e.jsxs(C,{className:"min-h-12",pending:de.isPending,pendingLabel:"Starting ingest",disabled:!M,onClick:()=>void de.mutateAsync(),children:[e.jsx(G,{className:"size-4"}),"Start background ingest"]})]})]})})]})]})})}export{pt as W};