forge-openclaw-plugin 0.3.2 → 0.3.3

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 (213) hide show
  1. package/dist/assets/action-bar-5Ii4UzHa.js +1 -0
  2. package/dist/assets/activity-page-CWjTKFY3.js +1 -0
  3. package/dist/assets/ai-surface-workspace-Dd2FSRom.js +1 -0
  4. package/dist/assets/{atlas-panel-G3wGxjYf.js → atlas-panel-Dinteouh.js} +1 -1
  5. package/dist/assets/{board-dIX6etHh.js → board-CLOHbg6t.js} +1 -1
  6. package/dist/assets/calendar-page-BWkXhzDf.js +1 -0
  7. package/dist/assets/calendar-rules-CjyuTu2I.js +1 -0
  8. package/dist/assets/{calendar-week-toolbar-CWSK5hJl.js → calendar-week-toolbar-D-nd9tkk.js} +1 -1
  9. package/dist/assets/{charts-DFnEuIMB.js → charts-DwTguE_x.js} +1 -1
  10. package/dist/assets/companion-sync-lab-page-G0t1TqqZ.js +1 -0
  11. package/dist/assets/daily-metrics-dashboard-DpIAdzFX.js +1 -0
  12. package/dist/assets/define-workbench-box-BIOZopF2.js +1 -0
  13. package/dist/assets/entity-link-multiselect-DZZjpL_d.js +1 -0
  14. package/dist/assets/{entity-note-count-link-ef3ZOpKM.js → entity-note-count-link-CmRRdXAr.js} +1 -1
  15. package/dist/assets/entity-notes-surface-8MPDscsu.js +1 -0
  16. package/dist/assets/execution-board-Bi8gi8J6.js +1 -0
  17. package/dist/assets/{faceted-token-search-CZmtyJTT.js → faceted-token-search-BGs4TqxT.js} +1 -1
  18. package/dist/assets/{flagship-signal-deck-DxRfmfpN.js → flagship-signal-deck-jLxHEHvb.js} +1 -1
  19. package/dist/assets/{floating-action-menu-cKjNsPYD.js → floating-action-menu-Itpm7T2_.js} +1 -1
  20. package/dist/assets/{forms-hB0SqEh-.js → forms-C5d5hTf2.js} +1 -1
  21. package/dist/assets/generic-node-view-KePoUF3Z.js +10 -0
  22. package/dist/assets/goal-detail-page-a1lEswpJ.js +1 -0
  23. package/dist/assets/goal-dialog-CYgRzl4y.js +1 -0
  24. package/dist/assets/goals-page-JY_EJq9U.js +1 -0
  25. package/dist/assets/{graph-DDUZNRsO.js → graph-Cd5WF3lw.js} +1 -1
  26. package/dist/assets/habits-page-BRI8AoaQ.js +1 -0
  27. package/dist/assets/health-boxes-DZJOFTOI.js +1 -0
  28. package/dist/assets/index-wEZUnRh0.js +2 -0
  29. package/dist/assets/inline-note-fields-CUVRzQkI.js +1 -0
  30. package/dist/assets/insight-flow-dialog-By73oG1H.js +1 -0
  31. package/dist/assets/{insights-page-DHG-o9P_.js → insights-page-DLyN-9yz.js} +3 -3
  32. package/dist/assets/kanban-boxes-M71CejV4.js +1 -0
  33. package/dist/assets/kanban-page-InKHhJQD.js +1 -0
  34. package/dist/assets/knowledge-graph-page-C-GEQGRY.js +1 -0
  35. package/dist/assets/life-force-page-Dq88NzNp.js +1 -0
  36. package/dist/assets/{life-force-workspace-sszLD-Yn.js → life-force-workspace-Bl_0slZi.js} +1 -1
  37. package/dist/assets/{maps-C-yOWiDN.js → maps-D0Mm6WPG.js} +1 -1
  38. package/dist/assets/{metric-tile-B-tDTcBt.js → metric-tile-yQJgjYrN.js} +1 -1
  39. package/dist/assets/{motion-Lt5B1XuE.js → motion-DwjmC9aq.js} +1 -1
  40. package/dist/assets/movement-boxes-C-rc3N8Z.js +1 -0
  41. package/dist/assets/movement-page-DK-d1uYa.js +1 -0
  42. package/dist/assets/{note-markdown-CCyyE85h.js → note-markdown-7czv-KMH.js} +1 -1
  43. package/dist/assets/note-tags-input-CkgkqiT3.js +1 -0
  44. package/dist/assets/notes-boxes-BQuR1MiB.js +1 -0
  45. package/dist/assets/notes-page-ec9g1mPh.js +1 -0
  46. package/dist/assets/{open-in-graph-button-CMjJZX7G.js → open-in-graph-button-B_4fdm4l.js} +1 -1
  47. package/dist/assets/{orbit-map-v2Pv9RU_.js → orbit-map-DPQNBqS-.js} +1 -1
  48. package/dist/assets/overview-page-CZjMab2o.js +1 -0
  49. package/dist/assets/page-hero-BRcqE3a4.js +1 -0
  50. package/dist/assets/pill-cluster-dy6jG_dV.js +1 -0
  51. package/dist/assets/{preference-entity-handoff-button-CKDxCnbl.js → preference-entity-handoff-button-DOV-_2Vm.js} +1 -1
  52. package/dist/assets/preferences-page-Co8w5hzp.js +1 -0
  53. package/dist/assets/{project-collections-NBwk6yV-.js → project-collections-DNgKleDl.js} +1 -1
  54. package/dist/assets/project-detail-page-C-Ib1x8w.js +1 -0
  55. package/dist/assets/project-dialog-D_hgOdB9.js +1 -0
  56. package/dist/assets/project-management-hierarchy-page-asf61KSz.js +1 -0
  57. package/dist/assets/project-management-section-nav-DAZA1oXG.js +1 -0
  58. package/dist/assets/projects-boxes-CHLr1Bs-.js +1 -0
  59. package/dist/assets/projects-page-BsM8yCqQ.js +1 -0
  60. package/dist/assets/psyche-behaviors-page-COSZeP4J.js +5 -0
  61. package/dist/assets/psyche-flashcards-page-CJmgGL9x.js +1 -0
  62. package/dist/assets/psyche-goal-map-page-avrWNSs9.js +1 -0
  63. package/dist/assets/psyche-graph-BmwbnNBY.js +1 -0
  64. package/dist/assets/psyche-metrics-page-CY0J_aMx.js +1 -0
  65. package/dist/assets/psyche-mode-guide-page-COcswIHZ.js +1 -0
  66. package/dist/assets/psyche-modes-page-BXF_GZoP.js +1 -0
  67. package/dist/assets/psyche-page-VsMBNG1F.js +1 -0
  68. package/dist/assets/psyche-patterns-page-DVoIro0Q.js +5 -0
  69. package/dist/assets/psyche-questionnaire-builder-page-CahcrbQj.js +1 -0
  70. package/dist/assets/psyche-questionnaire-detail-page-CYSgADAD.js +1 -0
  71. package/dist/assets/psyche-questionnaire-run-detail-page-D5q5URTu.js +1 -0
  72. package/dist/assets/psyche-questionnaire-run-page-DUoA-VSs.js +1 -0
  73. package/dist/assets/psyche-questionnaires-page-dbQlqbKh.js +1 -0
  74. package/dist/assets/{psyche-report-detail-page-Ci14mNUK.js → psyche-report-detail-page-D_Mmlf2D.js} +3 -3
  75. package/dist/assets/psyche-reports-page-CO3J4Js3.js +1 -0
  76. package/dist/assets/{psyche-schemas-Dxj554nU.js → psyche-schemas-Dtskzvv1.js} +1 -1
  77. package/dist/assets/psyche-schemas-beliefs-page-BUNGL4zW.js +9 -0
  78. package/dist/assets/psyche-screen-time-page-Bm18uHDg.js +1 -0
  79. package/dist/assets/psyche-self-observation-page-VdPMBuK4.js +1 -0
  80. package/dist/assets/psyche-values-page-DivSQodJ.js +5 -0
  81. package/dist/assets/question-flow-dialog-Dsnsc8be.js +2 -0
  82. package/dist/assets/{report-chain-fields-CbkT7WOO.js → report-chain-fields-Bf-WCSJQ.js} +1 -1
  83. package/dist/assets/rewards-page-CI53Cp0i.js +1 -0
  84. package/dist/assets/{scheduling-rules-editor-BUGnZJ0g.js → scheduling-rules-editor-Bg3QU_qt.js} +1 -1
  85. package/dist/assets/{schema-badge-CLAA4p-b.js → schema-badge-CRThEDqP.js} +1 -1
  86. package/dist/assets/schemas-B8-kIOFQ.js +1 -0
  87. package/dist/assets/{select-menu-Cqs5t3ng.js → select-menu-rT3Qd5t5.js} +1 -1
  88. package/dist/assets/{settings-agents-page-pmkVrOO8.js → settings-agents-page-VDUv2WuO.js} +4 -4
  89. package/dist/assets/settings-bin-page-DfuGJVqc.js +1 -0
  90. package/dist/assets/{settings-calendar-page-BBjAMOCf.js → settings-calendar-page-ex7eHB1y.js} +3 -3
  91. package/dist/assets/settings-data-page-BPWyPVGo.js +1 -0
  92. package/dist/assets/settings-logs-page-CwTT4n63.js +1 -0
  93. package/dist/assets/settings-mobile-page-B6sVk872.js +1 -0
  94. package/dist/assets/settings-models-page-Dq5XViZd.js +1 -0
  95. package/dist/assets/settings-page-BRxdAxbS.js +1 -0
  96. package/dist/assets/settings-rewards-page-DRvxTwv3.js +1 -0
  97. package/dist/assets/{settings-section-nav-Co0AaDG-.js → settings-section-nav-D_vKvOWd.js} +1 -1
  98. package/dist/assets/settings-users-page-B6oSpOaV.js +1 -0
  99. package/dist/assets/settings-wiki-page-Bkv-SS3J.js +1 -0
  100. package/dist/assets/sleep-page-DELXxo6j.js +1 -0
  101. package/dist/assets/sports-page-ByWQL0Gf.js +1 -0
  102. package/dist/assets/{state-vCcAT5Hq.js → state-BtwEvpO6.js} +1 -1
  103. package/dist/assets/strategies-page-PuUHsaSJ.js +1 -0
  104. package/dist/assets/strategy-detail-page-CSyVdv29.js +1 -0
  105. package/dist/assets/strategy-dialog-Fgpc0z1M.js +1 -0
  106. package/dist/assets/{surface-CyWI7e1R.js → surface-DzVqQDmf.js} +1 -1
  107. package/dist/assets/{table-BNqMG3_S.js → table-BuONJH1s.js} +1 -1
  108. package/dist/assets/task-detail-page-BoLvJ_4F.js +1 -0
  109. package/dist/assets/task-dialog-B2cGkhLk.js +6 -0
  110. package/dist/assets/timebox-planning-dialog-BjiC2jh0.js +1 -0
  111. package/dist/assets/today-boxes-B4f4sBXg.js +1 -0
  112. package/dist/assets/today-page-Cusp2JI8.js +1 -0
  113. package/dist/assets/training-load-page-CsZbK6rY.js +1 -0
  114. package/dist/assets/{ui-C1iwpj2-.js → ui-B9O-eUim.js} +1 -1
  115. package/dist/assets/use-anchored-overlay-position-BrQ4cqKn.js +1 -0
  116. package/dist/assets/{use-psyche-focus-target-Ct-acS9G.js → use-psyche-focus-target-Cuxni3SK.js} +1 -1
  117. package/dist/assets/user-badge-CQygGKVs.js +1 -0
  118. package/dist/assets/user-ownership-DJGl4rAj.js +1 -0
  119. package/dist/assets/user-select-field-BNqv8-wd.js +1 -0
  120. package/dist/assets/utility-widgets-DRESNarT.js +3 -0
  121. package/dist/assets/{vendor-Dnkkx2co.js → vendor-Cpmju3nw.js} +1 -1
  122. package/dist/assets/vitals-page-BlTZ4f78.js +1 -0
  123. package/dist/assets/weekly-review-page-3Pk3NeGE.js +1 -0
  124. package/dist/assets/weight-loss-page-CRCtv1fX.js +5 -0
  125. package/dist/assets/{wiki-article-markdown-Bi02AsVt.js → wiki-article-markdown-D0PWvioX.js} +2 -2
  126. package/dist/assets/{wiki-editor-page-OZf9l4Tg.js → wiki-editor-page-OZMYUgFo.js} +5 -5
  127. package/dist/assets/wiki-ingest-history-page-DXZHzAqU.js +1 -0
  128. package/dist/assets/wiki-ingest-modal-Ro0V4UMB.js +1 -0
  129. package/dist/assets/wiki-page-B1g3Rfxy.js +1 -0
  130. package/dist/assets/workbench-flow-page-qh5nItU6.js +5 -0
  131. package/dist/assets/workbench-page-CFWfAYMV.js +1 -0
  132. package/dist/assets/workout-detail-page-Cw6t6Xj9.js +2 -0
  133. package/dist/index.html +7 -9
  134. package/dist/server/server/src/app.js +10 -0
  135. package/dist/server/server/src/health-weight-loss.js +11 -3
  136. package/dist/server/server/src/services/dashboard.js +4 -4
  137. package/dist/server/server/src/services/gamification.js +71 -32
  138. package/openclaw.plugin.json +1 -1
  139. package/package.json +1 -1
  140. package/dist/assets/activity-page-DRRbpVK-.js +0 -1
  141. package/dist/assets/ai-surface-workspace-DJPt-OaW.js +0 -1
  142. package/dist/assets/calendar-page-y8G1ige8.js +0 -1
  143. package/dist/assets/calendar-rules-CRhXqGQu.js +0 -1
  144. package/dist/assets/companion-sync-lab-page-kEgOF3c6.js +0 -1
  145. package/dist/assets/daily-metrics-dashboard-BJjUIZVA.js +0 -1
  146. package/dist/assets/entity-notes-surface-CaCjjUaq.js +0 -1
  147. package/dist/assets/execution-board-RRWm2srb.js +0 -1
  148. package/dist/assets/goal-detail-page-BgQlK7yT.js +0 -1
  149. package/dist/assets/goals-page-Cz2i3pVy.js +0 -1
  150. package/dist/assets/habits-page-BmEmWCGv.js +0 -1
  151. package/dist/assets/index-QJkjKYzZ.js +0 -19
  152. package/dist/assets/insight-flow-dialog-CdYMHwMP.js +0 -1
  153. package/dist/assets/kanban-page-C6S_fJRc.js +0 -1
  154. package/dist/assets/knowledge-graph-page-juA9QCy0.js +0 -1
  155. package/dist/assets/life-force-page-ChTIA4mV.js +0 -1
  156. package/dist/assets/movement-page-Dx3T3HrG.js +0 -1
  157. package/dist/assets/note-tags-input-BS14YXHn.js +0 -1
  158. package/dist/assets/notes-page-D3yGl8TN.js +0 -1
  159. package/dist/assets/overview-page-DSOpBpHf.js +0 -1
  160. package/dist/assets/page-hero-CONuJu5J.js +0 -1
  161. package/dist/assets/pill-cluster-W2fY48OM.js +0 -1
  162. package/dist/assets/preferences-page-Br3zrLlH.js +0 -1
  163. package/dist/assets/project-detail-page-BIU9_TRN.js +0 -1
  164. package/dist/assets/project-management-hierarchy-page-C2H620xD.js +0 -1
  165. package/dist/assets/project-management-section-nav-DRPVS1Eh.js +0 -1
  166. package/dist/assets/projects-page-w7a_L2-z.js +0 -1
  167. package/dist/assets/psyche-behaviors-page-Dt4CMC-q.js +0 -5
  168. package/dist/assets/psyche-flashcards-page-rXz06dqO.js +0 -1
  169. package/dist/assets/psyche-goal-map-page-BCcD6Jkl.js +0 -1
  170. package/dist/assets/psyche-graph-CXlAj4ED.js +0 -1
  171. package/dist/assets/psyche-metrics-page-B1otiir6.js +0 -1
  172. package/dist/assets/psyche-mode-guide-page-C6AdVIAv.js +0 -1
  173. package/dist/assets/psyche-modes-page-DoUqz2mR.js +0 -1
  174. package/dist/assets/psyche-page-BJNLQn8W.js +0 -1
  175. package/dist/assets/psyche-patterns-page-CzpMSAPu.js +0 -5
  176. package/dist/assets/psyche-questionnaire-builder-page-DjzatGVZ.js +0 -1
  177. package/dist/assets/psyche-questionnaire-detail-page-B0Qfowfg.js +0 -1
  178. package/dist/assets/psyche-questionnaire-run-detail-page-B2dNj4jJ.js +0 -1
  179. package/dist/assets/psyche-questionnaire-run-page-DyD9Ui-g.js +0 -1
  180. package/dist/assets/psyche-questionnaires-page-BxfKcoi3.js +0 -1
  181. package/dist/assets/psyche-reports-page-ALhNueiV.js +0 -1
  182. package/dist/assets/psyche-schemas-beliefs-page-C0P2Vw6-.js +0 -9
  183. package/dist/assets/psyche-screen-time-page-BYnaT3cb.js +0 -1
  184. package/dist/assets/psyche-self-observation-page-eM9vpwIB.js +0 -1
  185. package/dist/assets/psyche-values-page-BqrGIDok.js +0 -5
  186. package/dist/assets/rewards-page-DpAJ8IxE.js +0 -1
  187. package/dist/assets/settings-bin-page-BwtLrweW.js +0 -1
  188. package/dist/assets/settings-data-page-Bqy5SukM.js +0 -1
  189. package/dist/assets/settings-logs-page-8khtrf4T.js +0 -1
  190. package/dist/assets/settings-mobile-page-BcyRjEU_.js +0 -1
  191. package/dist/assets/settings-models-page-DlSnO9WX.js +0 -1
  192. package/dist/assets/settings-page-CyBQ2qcB.js +0 -1
  193. package/dist/assets/settings-rewards-page-BBX2WtVM.js +0 -1
  194. package/dist/assets/settings-users-page-JSnfFFPu.js +0 -1
  195. package/dist/assets/settings-wiki-page--nT23Fdy.js +0 -1
  196. package/dist/assets/sleep-page-CGMi3MtV.js +0 -1
  197. package/dist/assets/sports-page-Kv5bBoLr.js +0 -1
  198. package/dist/assets/strategies-page-Br7RdUJO.js +0 -1
  199. package/dist/assets/strategy-detail-page-CBWXjUhC.js +0 -1
  200. package/dist/assets/strategy-dialog-BTwkaSxI.js +0 -1
  201. package/dist/assets/task-detail-page-Qis9354n.js +0 -1
  202. package/dist/assets/timebox-planning-dialog-DB8snOBD.js +0 -1
  203. package/dist/assets/today-page-D9A5PU0S.js +0 -1
  204. package/dist/assets/training-load-page-Bpd4DQAh.js +0 -1
  205. package/dist/assets/vitals-page-CVYC-4RG.js +0 -1
  206. package/dist/assets/weekly-review-page-BP7N3fNB.js +0 -1
  207. package/dist/assets/weight-loss-page-_fX3N1UK.js +0 -5
  208. package/dist/assets/wiki-ingest-history-page-CzeNSL7N.js +0 -1
  209. package/dist/assets/wiki-ingest-modal-Ig_xnyc6.js +0 -1
  210. package/dist/assets/wiki-page-B4xuNgY4.js +0 -1
  211. package/dist/assets/workbench-flow-page-BhRJCALC.js +0 -5
  212. package/dist/assets/workbench-page-DxVs2AOY.js +0 -1
  213. package/dist/assets/workout-detail-page-D4wfkE98.js +0 -2
@@ -0,0 +1,5 @@
1
+ import{j as a,bX as Be,aG as ua,b7 as ga,cg as Ba,dx as Ha,cB as za,bB as Ie,cm as qa,cF as ma,c8 as Oa,c1 as ha,dy as Ua,dz as Qa,bq as pa,dA as Va,dB as Ya,r as K,d8 as Ja,bt as ea,dC as Za,br as Xa,bd as et}from"./vendor-Cpmju3nw.js";import{j as at,i as tt,k as U}from"./state-BtwEvpO6.js";import{P as nt}from"./page-hero-BRcqE3a4.js";import{C as V,B as D,a4 as me,I as w,c as Pe,k as E,T as ke,d as rt,L as st,e as it,e8 as aa,e9 as ot,ea as lt,eb as ct,ec as ta,ed as dt,ee as ut,ef as gt,eg as mt,eh as ht,ei as pt,ej as bt}from"./index-wEZUnRh0.js";import{S as I,a as M}from"./surface-DzVqQDmf.js";import{Q as Ce,F as j,a as na}from"./question-flow-dialog-Dsnsc8be.js";import{f as We}from"./date-keys-Cj1G3TOn.js";import"./motion-DwjmC9aq.js";import"./ui-B9O-eUim.js";import"./board-CLOHbg6t.js";import"./forms-C5d5hTf2.js";function xt({view:e,onOpenPlan:t,onOpenFoodSearch:n,onOpenCustomFood:r,onOpenChatGptFood:s,onOpenCheckin:d,onOpenHistory:g}){return a.jsxs(V,{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(D,{type:"button",onClick:r,children:[a.jsx(Be,{className:"size-4"}),"Custom food"]}),a.jsxs(D,{type:"button",variant:"secondary",onClick:s,children:[a.jsx(ua,{className:"size-4"}),"Ask ChatGPT"]}),a.jsxs(D,{type:"button",variant:"secondary",onClick:n,children:[a.jsx(ga,{className:"size-4"}),"Search food"]}),a.jsxs(D,{type:"button",variant:"secondary",onClick:t,children:[a.jsx(Ba,{className:"size-4"}),"Plan settings"]}),a.jsxs(D,{type:"button",variant:"secondary",onClick:d,children:[a.jsx(Ha,{className:"size-4"}),"Add measure"]}),a.jsxs(D,{type:"button",variant:"secondary",onClick:g,children:[a.jsx(za,{className:"size-4"}),"Food history"]})]})]})}function _(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function oe(e){return typeof e=="string"&&e.trim()?e:null}function i(e,t=0){const n=_(e);return n===null?"n/a":n.toFixed(t)}function H(e,t=0){const n=_(e);return n===null?"n/a":`${n>0?"+":""}${n.toFixed(t)}`}function ye(e){const t=_(e);return t===null?"n/a":`${t.toFixed(1)}/10`}function ft(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&!Array.isArray(t)):[]}function vt(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"Past-week active baseline"}}function yt(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 baseline.";case"today_workout_movement_energy":return"Using today's workout and movement calories instead of the baseline.";case"today_workout_movement_step_energy":return"Using today's workouts, movement, and steps instead of the baseline.";case"today_workout_step_energy":return"Using today's workouts and steps instead of the baseline.";case"today_movement_step_energy":return"Using today's movement and steps instead of the baseline.";case"today_workout_energy":return"Using today's workout calories instead of the baseline.";case"today_movement_trip_calories":return"Using today's movement calories instead of the baseline.";case"today_step_estimate":return"Using today's step estimate because it is above the baseline.";default:return"No meaningful same-day active evidence yet, so the past-week active baseline is used."}}function jt(e){return`${e>=0?"+":""}${e.toFixed(0)} kcal`}function kt(e){return e.trim()===""?"0":e}function Nt({view:e,draftValue:t,pending:n,error:r,onDraftChange:s,onSave:d,onReset:g}){const l=e.energyModel,o=e.todayLedger,u=l.todayActiveOverride,C=l.todayActiveCaloriesSource,A=`${o.plannedTargetCalories.toFixed(0)} ${jt(l.todayTargetAdjustmentKcal)} = ${o.targetCalories.toFixed(0)} kcal`;return a.jsxs(V,{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(me,{label:"Explain active calories",content:`Today target = baseline food target plus the day-specific active adjustment. ${A}. Automatic same-day activity can only add ${Math.round(l.activityEatBackFraction*100)}% of the positive surplus above the baseline day. A manual edit overrides today only and can raise or lower the target.`})]}),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(Ie,{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:yt(C)}),a.jsxs("div",{children:["Baseline ",l.baselineActiveCaloriesKcal.toFixed(0)," kcal"," · ","observed"," ",l.todayObservedActiveCaloriesKcal!=null?`${l.todayObservedActiveCaloriesKcal.toFixed(0)} kcal`:"n/a"]}),a.jsxs("div",{className:"break-words",children:["Source: ",vt(C)]})]}),a.jsxs("div",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)_auto] gap-2",children:[a.jsx(w,{inputMode:"decimal",value:t,onChange:f=>s(kt(f.target.value)),"aria-label":"Today active calories",className:"py-2.5"}),a.jsxs(D,{type:"button",onClick:d,pending:n,pendingLabel:"Applying",children:[a.jsx(qa,{className:"size-4"}),"Apply"]})]}),a.jsxs(D,{type:"button",variant:"secondary",onClick:g,disabled:!u||n,children:[a.jsx(ma,{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 wt={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 Z({label:e,value:t,detail:n,icon:r,tone:s="default",help:d,helpMaxWidthPx:g}){return a.jsxs(V,{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:Pe("rounded-2xl p-2.5",wt[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(me,{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 Ct({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(u=>{const C=Number.isFinite(u.quantity)&&u.quantity>0?Number.isInteger(u.quantity)?String(u.quantity):u.quantity.toFixed(2).replace(/\.?0+$/,""):null,A=u.unit??"serving",f=u.grams!=null?`${u.grams.toFixed(0)}g`:null;return[C,A,f?`(${f})`:null].filter(Boolean).join(" ")}).filter(Boolean).join(" · ");return a.jsxs(I,{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(E,{tone:"meta",children:e.mealLabel}):null,a.jsxs(E,{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(D,{type:"button",size:"sm",variant:"secondary",onClick:()=>n(e),children:[a.jsx(Oa,{className:"size-4"}),"Edit"]}):null,r?a.jsxs(D,{type:"button",size:"sm",variant:"ghost",pending:s,onClick:()=>r(e),children:[a.jsx(ha,{className:"size-4"}),"Delete"]}):null,t?a.jsxs(D,{type:"button",size:"sm",variant:"ghost",pending:s,onClick:()=>t(e),children:[a.jsx(ma,{className:"size-4"}),"Log again"]}):null]})]})}function He({children:e}){return a.jsx(I,{className:"border-dashed border-[var(--ui-border-strong)] p-5 text-sm text-[var(--ui-ink-soft)]",children:e})}function Ne(e){return`${e.toFixed(0)} kcal`}function Mt(e){return e>=0?"Kcal left":"Over target"}function Ft(e){return e>=0?Ne(e):Ne(Math.abs(e))}function Kt({ledger:e,remainingCalories:t,intakePercent:n,logSavedPending:r,onLogAgain:s,onEditMeal:d,onDeleteMeal:g}){const l=e.totals;return a.jsxs(V,{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(me,{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(E,{tone:"meta",children:[e.meals.length," meals"]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"mb-4 grid gap-3 sm:grid-cols-3",children:[a.jsxs("div",{className:"min-w-0 rounded-[8px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] p-3",children:[a.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-[var(--ui-ink-faint)]",children:"Eaten today"}),a.jsx("div",{className:"mt-1 text-2xl font-semibold text-[var(--ui-ink-strong)]",children:Ne(l.calories)})]}),a.jsxs("div",{className:"min-w-0 rounded-[8px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] p-3",children:[a.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-[var(--ui-ink-faint)]",children:"Target today"}),a.jsx("div",{className:"mt-1 text-2xl font-semibold text-[var(--ui-ink-strong)]",children:Ne(e.targetCalories)})]}),a.jsxs("div",{className:Pe("min-w-0 rounded-[8px] border p-3",t>=0?"border-[color-mix(in_srgb,var(--success)_34%,var(--ui-border-subtle)_66%)] bg-[var(--ui-success-soft)]":"border-[color-mix(in_srgb,var(--danger)_34%,var(--ui-border-subtle)_66%)] bg-[var(--ui-danger-soft)]"),children:[a.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-[var(--ui-ink-faint)]",children:Mt(t)}),a.jsx("div",{className:"mt-1 text-2xl font-semibold text-[var(--ui-ink-strong)]",children:Ft(t)})]})]}),a.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-[var(--ui-surface-2)]",children:a.jsx("div",{className:Pe("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(Ct,{meal:o,pending:r,onLogAgain:s,onEdit:d,onDelete:g},o.id)):a.jsx(He,{children:"No meals logged today yet."})})]})}function At({hypotheses:e}){return a.jsxs(V,{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(I,{children:[a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsx(E,{tone:"signal",children:oe(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:oe(t.label)??"Candidate pattern"}),a.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:oe(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(He,{children:"Log meals plus energy, gut, and look check-ins for a few days to generate pattern candidates."})})})]})}function Gt({experiments:e}){return a.jsxs(V,{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(Ua,{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(I,{children:[a.jsx("div",{className:"text-sm font-medium text-[var(--ui-ink-strong)]",children:oe(t.title)??"Nutrition experiment"}),a.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:oe(t.hypothesis)??oe(t.intervention)??"No hypothesis recorded."})]},String(t.id??n))),e.length===0?a.jsx(He,{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 St({view:e}){const t=e.dataQuality,n=e.todayLedger;return a.jsxs(V,{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(E,{tone:"meta",children:[e.summary.dataQualityScore.toFixed(0),"% coverage"]})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[a.jsx(Dt,{label:"Source confidence",value:t.sourceConfidence,children:"Food parsing stays candidate-based until accepted; wearable burn is treated as a trend input."}),a.jsxs(I,{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(E,{tone:"signal",children:r},r)):a.jsx("span",{className:"text-sm text-[var(--ui-ink-soft)]",children:"Core evidence loop is covered."})})]}),a.jsxs(I,{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 Dt({label:e,value:t,children:n}){return a.jsxs(I,{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})]})}const Q={id:"hall_niddk_linearized_adult_12w",label:"Hall/NIDDK linearized adult model",defaultPlanningHorizonDays:84,steadyStateKcalPerKgPerDay:10/.45359237,timeConstantDays:365,staticEnergyDensityKcalPerKg:7700};function $e(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:null}function ba(e={}){const t=$e(e.planningHorizonDays)??Q.defaultPlanningHorizonDays,n=$e(e.timeConstantDays)??Q.timeConstantDays,r=$e(e.steadyStateKcalPerKgPerDay)??Q.steadyStateKcalPerKgPerDay,s=1-Math.exp(-t/n);return{planningHorizonDays:t,timeConstantDays:n,steadyStateKcalPerKgPerDay:r,responseFraction:s}}function xa(e,t={}){if(typeof e!="number"||!Number.isFinite(e))return null;if(e===0)return 0;const n=ba(t);return n.responseFraction<=0?null:e*(n.planningHorizonDays/7)*n.steadyStateKcalPerKgPerDay/n.responseFraction}function _t(e,t={}){if(typeof e!="number"||!Number.isFinite(e))return null;if(e===0)return 0;const n=ba(t);return e/n.steadyStateKcalPerKgPerDay*n.responseFraction/(n.planningHorizonDays/7)}function Et(e){return typeof e!="number"||!Number.isFinite(e)?null:e*Q.staticEnergyDensityKcalPerKg/7}function B(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 fa({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(me,{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 the formula resting baseline plus active calories. Complete HealthKit basal energy is calibration evidence, not the silent baseline."}),a.jsxs("ol",{className:"grid gap-2",children:[B("Mifflin-St Jeor resting baseline",`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.`),B("Resting calories","Mifflin-St Jeor formula baseline; HealthKit basal is complete-day evidence only",`Using: ${i(e==null?void 0:e.restingKcal)} kcal/day${e!=null&&e.restingSource?` (${e.restingSource})`:""}.`),B("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.`),B("Objective adjustment","Hall/NIDDK linearized adult model, inverted over the planning horizon",`Weekly rate ${H(e==null?void 0:e.weeklyRateKg,2)} kg/week gives ${H(e==null?void 0:e.dailyAdjustmentKcal)} kcal/day${e!=null&&e.rateModel?` with ${e.rateModel}`:""}${e!=null&&e.rateModelHorizonDays?` over ${e.rateModelHorizonDays} days`:""}.`),B("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.`),B("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.`),B("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.`),B("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.`),B("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.`),B("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 va(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 ge(e,t){const n=typeof e=="string"?Number(e):_(e);return typeof n=="number"&&Number.isFinite(n)?n:t}function $t(e){return va(e.target.notes,"sex")==="female"?"female":"male"}function Tt(e){return ge(va(e.target.notes,"age_years"),35)}function h(e,t,n,r,s,d){return{id:e,label:t,target:typeof n=="number"?Re(n):n,unit:r,note:s,source:d}}function Re(e){return Number.isFinite(e)?Math.abs(e)>=100?e.toFixed(0):e.toFixed(1).replace(/\.0$/,""):"n/a"}function se(e,t){return`${Re(e)}-${Re(t)}`}function Lt(e,t,n,r){const s=Math.round(n/1e3*14);return r>0?r:s}function It({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 Pt(e,t){return e==="male"?t>=51?14:17:t>=51?11:12}function Wt(e,t){const n=t>70,r=t>=51;return[h("vitamin_a","Vitamin A",e==="male"?900:700,"ug RAE","Retinol activity equivalent target.","NASEM DRI"),h("vitamin_c","Vitamin C",e==="male"?90:75,"mg","Adult RDA.","NASEM DRI"),h("vitamin_d","Vitamin D",n?20:15,"ug","Assumes limited sun exposure; older adults need more.","NASEM DRI"),h("vitamin_e","Vitamin E",15,"mg alpha-tocopherol","Adult RDA.","NASEM DRI"),h("vitamin_k","Vitamin K",e==="male"?120:90,"ug","Adult AI.","NASEM DRI"),h("thiamin_b1","Thiamin B1",e==="male"?1.2:1.1,"mg","Adult RDA.","NASEM DRI"),h("riboflavin_b2","Riboflavin B2",e==="male"?1.3:1.1,"mg","Adult RDA.","NASEM DRI"),h("niacin_b3","Niacin B3",e==="male"?16:14,"mg NE","Adult RDA.","NASEM DRI"),h("vitamin_b6","Vitamin B6",r?e==="male"?1.7:1.5:1.3,"mg","RDA rises after 50.","NASEM DRI"),h("folate","Folate",400,"ug DFE","Adult RDA.","NASEM DRI"),h("vitamin_b12","Vitamin B12",2.4,"ug","Adult RDA.","NASEM DRI"),h("pantothenic_acid","Pantothenic acid",5,"mg","Adult AI.","NASEM DRI"),h("biotin","Biotin",30,"ug","Adult AI.","NASEM DRI"),h("choline","Choline",e==="male"?550:425,"mg","Adult AI.","NASEM DRI")]}function Rt(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[h("calcium","Calcium",n,"mg","Bone and muscle target; higher for older adults and women 51+.","NASEM DRI"),h("iron","Iron",e==="female"&&t<=50?18:8,"mg","Menstruating-age female target is higher.","NASEM DRI"),h("magnesium","Magnesium",r,"mg","Adult RDA.","NASEM DRI"),h("phosphorus","Phosphorus",700,"mg","Adult RDA.","NASEM DRI"),h("zinc","Zinc",e==="male"?11:8,"mg","Adult RDA.","NASEM DRI"),h("iodine","Iodine",150,"ug","Adult RDA.","NASEM DRI"),h("selenium","Selenium",55,"ug","Adult RDA.","NASEM DRI"),h("copper","Copper",.9,"mg","Adult RDA.","NASEM DRI"),h("manganese","Manganese",e==="male"?2.3:1.8,"mg","Adult AI.","NASEM DRI"),h("chromium","Chromium",s,"ug","Adult AI.","NASEM DRI"),h("molybdenum","Molybdenum",45,"ug","Adult RDA.","NASEM DRI"),h("fluoride","Fluoride",e==="male"?4:3,"mg","Adult AI.","NASEM DRI"),h("chloride","Chloride",d,"mg","Adult AI.","NASEM DRI"),h("potassium","Potassium",e==="male"?3400:2600,"mg","Current adult AI for non-pregnant adults.","NASEM DRI"),h("sodium_limit","Sodium ceiling",2300,"mg max","Default daily ceiling unless medically individualized.","U.S. Dietary Guidelines")]}function Bt(e){const t=$t(e),n=Tt(e),r=ge(e.weightTrend.latestWeightKg,80),s=Math.max(1,ge(e.target.calorieTarget,2200)),d=ge(e.target.proteinGramsTarget,r*1.8),{carbs:g,fat:l}=It({calorieTarget:s,currentWeightKg:r,protein:d,savedFat:_(e.target.fatGramsTarget)}),o=Lt(t,n,s,ge(e.target.fiberGramsTarget,0)),u=_(e.energyModel.activeBurnKcal)??_(e.energyModel.activeEnergyCalories)??null,C=_(e.energyModel.movementCaloriesKcal),A=_(e.energyModel.restingEnergyCalories);return ya({sex:t,ageYears:n,currentWeightKg:r,calorieTarget:s,proteinGramsTarget:d,carbohydrateGramsTarget:g,fatGramsTarget:l,fiberGramsTarget:o,activeBurnKcal:u,movementCaloriesKcal:C,restingEnergyKcal:A})}function ya(e){const{sex:t,ageYears:n,currentWeightKg:r,calorieTarget:s,proteinGramsTarget:d,carbohydrateGramsTarget:g,fatGramsTarget:l,fiberGramsTarget:o,activeBurnKcal:u,movementCaloriesKcal:C,restingEnergyKcal:A}=e,f=u!=null?Math.min(4,Math.max(.1,u/500)):null,b=f!=null?f*.4:null,p=f!=null?f*.8:null,y=b!=null?b*500:null,k=p!=null?p*1e3:null,$=b!=null?b*78:null,T=p!=null?p*312:null,P=u!=null?_t(u):null;return{profile:{sex:t,ageYears:n,currentWeightKg:r,calorieTarget:s,activeBurnKcal:u,movementCaloriesKcal:C,restingEnergyKcal:A},macros:[h("calories","Calories",s,"kcal","Plan target from BMR, active burn, and chosen weekly rate.","Forge plan"),h("protein","Protein",d,"g","Higher than the population RDA to preserve lean mass during weight change.","ISSN + Forge plan"),h("carbohydrate","Carbohydrate",g,"g","Remaining fuel after protein and fat. It may sit below the 130g/day adult DRI reference when needed to preserve the calorie target.","NASEM DRI + Forge plan"),h("fat","Total fat",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"),h("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"),h("saturated_fat","Saturated fat",s*.1/9,"g max","Keep below 10% of energy.","U.S. Dietary Guidelines"),h("added_sugar","Added sugar",s*.1/4,"g max","Keep below 10% of energy; lower is better when feasible.","U.S. Dietary Guidelines"),h("linoleic_acid","Linoleic acid",Pt(t,n),"g","Essential n-6 fatty acid AI.","NASEM DRI"),h("ala","ALA omega-3",t==="male"?1.6:1.1,"g","Essential n-3 fatty acid AI.","NASEM DRI"),h("water","Total water",t==="male"?3.7:2.7,"L","All beverages and food water before extra training replacement.","NASEM DRI")],vitamins:Wt(t,n),minerals:Rt(t,n),sportLosses:[h("training_time","Estimated training time",f??"n/a","h/day","Derived from active burn at roughly 500 kcal/h.","Forge sport-loss model"),h("sweat_fluid","Expected sweat fluid",b!=null&&p!=null?se(b,p):"n/a","L/day","Planning range uses 0.4-0.8 L/h; measure body mass change to calibrate.","ACSM"),h("sweat_sodium","Expected sweat sodium",y!=null&&k!=null?se(y,k):"n/a","mg/day","Sodium varies widely; this uses a conservative range around common sweat sodium values.","ACSM + Sports Medicine review"),h("sweat_potassium","Expected sweat potassium",$!=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"),h("gross_sport_equivalent","Gross sport burn equivalent",P??"n/a","kg/week","Energy equivalent if the active burn were not eaten back; the plan may already include it.","Hall/NIDDK dynamic model")],sportSummary:{trainingHours:f,fluidLossLiters:b!=null&&p!=null?se(b,p):"n/a",sodiumLossMg:y!=null&&k!=null?se(y,k):"n/a",potassiumLossMg:$!=null&&T!=null?se($,T):"n/a",grossSportWeightEquivalentKgPerWeek:P}}}function Te({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(E,{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(E,{tone:"meta",children:n.source})})]},n.id))})]})})})]})}function ue({title:e,description:t,children:n}){return a.jsxs(I,{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 Ht({view:e}){const t=Bt(e),n=e.target.weeklyRateGoalKg??null,r=n!=null&&Number.isFinite(n)?xa(n):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,u=b=>{var k;const p=(k=t.macros.find($=>$.id===b))==null?void 0:k.target,y=Number(p);return Number.isFinite(y)?y:null},C=t.profile.sex==="male"?t.profile.ageYears>=51?30:38:t.profile.ageYears>=51?21:25,A=Math.round(t.profile.calorieTarget/1e3*14),f=t.sportSummary.grossSportWeightEquivalentKgPerWeek!=null?`${t.sportSummary.grossSportWeightEquivalentKgPerWeek.toFixed(2)} kg/week`:"n/a";return a.jsx("section",{className:"grid gap-4",children:a.jsxs(V,{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(Qa,{className:"size-4 text-[var(--ui-accent)]"}),"Macro And Micronutrient Targets",a.jsx(fa,{values:{sex:t.profile.sex,ageYears:t.profile.ageYears,currentWeightKg:t.profile.currentWeightKg,bmrKcal:null,restingKcal:s,restingSource:s!=null?"formula baseline; HealthKit complete-day evidence is calibration":null,activeKcal:d,maintenanceKcal:g,weeklyRateKg:n,dailyAdjustmentKcal:r,rateModel:Q.label,rateModelHorizonDays:Q.defaultPlanningHorizonDays,calorieTarget:t.profile.calorieTarget,calorieFloor:t.profile.sex==="male"?1500:1200,proteinReferenceWeightKg:null,proteinFactor:o,proteinGrams:u("protein"),fatGrams:u("fat"),carbohydrateGrams:u("carbohydrate"),fiberGrams:u("fiber"),fiberEnergyAdjustedGrams:A,fiberDriGrams:C}})]}),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(E,{tone:"signal",children:[t.profile.calorieTarget.toFixed(0)," kcal"]}),a.jsxs(E,{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(ue,{title:"All macro targets",description:"Calories, protein, carbs, fat, fiber, sugar ceiling, saturated fat ceiling, essential fats, and water.",children:a.jsx(Te,{rows:t.macros,compact:!0})}),a.jsx(ue,{title:"Vitamins",description:"Adult daily vitamin targets from DRI values, adjusted for sex and age where the reference differs.",children:a.jsx(Te,{rows:t.vitamins})})]}),a.jsxs("div",{className:"grid content-start gap-4",children:[a.jsxs(ue,{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(M,{label:"Active burn",value:t.profile.activeBurnKcal!=null?`${t.profile.activeBurnKcal.toFixed(0)} kcal`:"n/a"}),a.jsx(M,{label:"Sport equivalent",value:f}),a.jsx(M,{label:"Sweat fluid",value:`${t.sportSummary.fluidLossLiters} L`}),a.jsx(M,{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(pa,{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(ue,{title:"Minerals & oligoelements",description:"Daily mineral and trace-element targets including sodium ceiling and potassium AI.",children:a.jsx(Te,{rows:t.minerals,compact:!0})}),a.jsx(ue,{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(b=>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:[b.id==="sweat_fluid"?a.jsx(Va,{className:"size-4 text-[var(--ui-accent)]"}):a.jsx(Ya,{className:"size-4 text-[var(--ui-accent)]"}),b.label]}),a.jsx("p",{className:"mt-1 text-xs text-[var(--ui-ink-faint)]",children:b.note})]}),a.jsxs("div",{className:"shrink-0 text-right text-sm font-semibold text-[var(--ui-ink)]",children:[b.target,a.jsx("div",{className:"text-xs font-normal text-[var(--ui-ink-faint)]",children:b.unit})]})]},b.id))})})]})]})]})})}function ie(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 z(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>0?t:null}function ja(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 ka(e,t){return t==="gain"?e*1.03:t==="maintain"?e:e*.95}function Na(e){return e.toFixed(1)}function zt(e,t){return e==="male"?t>=51?30:38:t>=51?21:25}function qt(e){if(e.ageYears==null||e.ageYears<=0||e.heightCm==null||e.heightCm<=0||e.weightKg==null||e.weightKg<=0)return null;const t=e.sex==="male"?5:-161;return 10*e.weightKg+6.25*e.heightCm-5*e.ageYears+t}function ra(e,t){const n=e/100;return n>0?t*n*n:null}function Ot(e){const t=e.goalMode==="lose"&&e.goalWeightKg!=null?Math.min(e.currentWeightKg,e.goalWeightKg):e.currentWeightKg,n=ra(e.heightCm,30),r=ra(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 Ut(e,t){const n=z(e.currentWeightKg)??80;return{...e,goalMode:t,goalWeightKg:Na(ka(n,t)),weeklyRateKg:ja(n,t).toFixed(2)}}function Le(e){const t=_(e.weightTrend.latestWeightKg),n=e.target,r=ie(n.notes,"sex"),s=ie(n.notes,"age_years"),d=ie(n.notes,"height_cm"),g=_(e.energyModel.activeBurnKcal)??_(e.energyModel.activeEnergyCalories)??_(e.energyModel.movementCaloriesKcal)??z(ie(n.notes,"activity_kcal"))??0,l=n.bodyGoal??"",o=l.includes("gain")?"gain":l.includes("maintain")?"maintain":"lose",u=n.weightGoalKg??n.goalBodyWeightKg??null,C=t??80;return{goalMode:o,sex:r==="female"?"female":"male",ageYears:z(s)?String(s):"",heightCm:z(d)?String(d):"",currentWeightKg:t?t.toFixed(1):"",goalWeightKg:u?String(u):Na(ka(C,o)),weeklyRateKg:n.weeklyRateGoalKg!==null&&n.weeklyRateGoalKg!==void 0?String(Math.abs(n.weeklyRateGoalKg)):ja(C,o).toFixed(2),activeCaloriesKcal:g.toFixed(0),restingCaloriesKcal:_(e.energyModel.formulaRestingKcal)!=null?String(_(e.energyModel.formulaRestingKcal)):"",dietStyle:n.dietStyle??""}}function Qt(e){const t=z(ie(e.target.notes,"age_years"))!=null,n=z(ie(e.target.notes,"height_cm"))!=null,r=_(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 Vt(e){const t=e.energyModel,n=t.activeBaselineEvidenceDays>0?`Forge is averaging ${t.activeBaselineEvidenceDays} measured prior day${t.activeBaselineEvidenceDays===1?"":"s"} inside the past ${t.activeBaselineWindowDays} days, excluding today and ignoring missing sync days instead of counting them as zero.`:`Forge has no measured prior-day active evidence in the past ${t.activeBaselineWindowDays} days, so it is falling back to the saved plan estimate.`,r=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 saved plan estimate.";return`This is the baseline active allowance used when today has no same-day workout, movement, step, or active-energy evidence. ${n} ${r} 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 wa(e){const t=Number(e.currentWeightKg)||80,n=Number(e.heightCm)||178,r=Number(e.ageYears)||35,s=z(e.goalWeightKg),d=Math.max(0,Number(e.activeCaloriesKcal)||0),g=qt({sex:e.sex,ageYears:r,heightCm:n,weightKg:t})??10*t+6.25*n-5*r+5,l=g,o=l+d,u=Math.abs(Number(e.weeklyRateKg)||0),C=e.goalMode==="lose"?-u:e.goalMode==="gain"?u:0,A=xa(C)??0,f=Et(C)??0,b=e.sex==="male"?1500:1200,p=Math.round(o+A),y=Math.max(b,p),k=Ot({currentWeightKg:t,goalWeightKg:s,heightCm:n,goalMode:e.goalMode}),$=e.goalMode==="lose"?2:e.goalMode==="gain"?1.8:1.6,T=Math.round(k*$),P=Math.floor(y*.45/4),W=Math.max(1,Math.min(T,P)),q=k*.6,R=y*.25/9,te=Math.max(0,(y-W*4)/9),Y=Math.max(0,Math.floor(Math.min(te,y*.35/9,Math.max(q,R)))),X=Math.max(0,Math.floor((y-W*4-Y*9)/4)),O=Math.round(y/1e3*14),le=zt(e.sex,r),ne=O,ce=Math.round(y*.1/9),ee=Math.round(y*.1/4);return{bmr:Math.round(g),restingCalories:Math.round(l),restingSource:"Mifflin-St Jeor baseline",activeCalories:Math.round(d),maintenanceCalories:Math.round(o),plannedCalorieTarget:p,minimumCalorieFloor:b,weeklyRateGoalKg:C,dailyEnergyAdjustment:Math.round(A),staticDailyEnergyAdjustment:Math.round(f),rateModel:Q.id,rateModelLabel:Q.label,rateModelPlanningHorizonDays:Q.defaultPlanningHorizonDays,calorieTarget:y,proteinReferenceWeight:Math.round(k*10)/10,proteinGramsTarget:W,carbohydrateGramsTarget:X,fatGramsTarget:Y,fiberGramsTarget:ne,fiberEnergyAdjustedGrams:O,fiberDriGrams:le,saturatedFatLimitGrams:ce,addedSugarLimitGrams:ee}}function Yt(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("- Formula resting baseline should stay in a plausible daily range."),t.length>0?t.join(`
2
+ `):null}function Jt(e){const t=wa(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}`,"eat_back_fraction=0.5",`maintenance_kcal=${t.maintenanceCalories}`,`rate_model=${t.rateModel}`,`rate_model_horizon_days=${t.rateModelPlanningHorizonDays}`,`static_7700_adjustment_kcal=${t.staticDailyEnergyAdjustment}`].join("; ")}}function Zt({open:e,onOpenChange:t,view:n,value:r,onChange:s,onSubmit:d,pending:g,error:l}){const o=K.useMemo(()=>wa(r),[r]),u=z(r.ageYears)!=null&&z(r.heightCm)!=null&&z(r.currentWeightKg)!=null,C=u?String(o.bmr):"",A=u?`Forge uses Mifflin-St Jeor as the stable target baseline. Complete HealthKit basal energy stays evidence/calibration, not the silent default. Current formula value: ${o.bmr} kcal.`:"Forge will calculate this from real age, height, sex, and current weight. Complete HealthKit basal energy stays evidence/calibration, not the silent default.",f=K.useMemo(()=>ya({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:_(n.energyModel.movementCaloriesKcal),restingEnergyKcal:o.restingCalories}),[o,r,n.energyModel.movementCaloriesKcal]),b=[{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:(p,y)=>a.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[a.jsx(j,{label:"Sex",children:a.jsx(na,{value:p.sex,onChange:k=>y({sex:k}),options:[{value:"male",label:"Male"},{value:"female",label:"Female"}]})}),a.jsx(j,{label:"Age",children:a.jsx(w,{inputMode:"numeric",value:p.ageYears,onChange:k=>y({ageYears:k.target.value}),placeholder:"35"})}),a.jsx(j,{label:"Height cm",children:a.jsx(w,{inputMode:"decimal",value:p.heightCm,onChange:k=>y({heightCm:k.target.value}),placeholder:"178"})}),a.jsx(j,{label:"Current weight kg",children:a.jsx(w,{inputMode:"decimal",value:p.currentWeightKg,onChange:k=>y({currentWeightKg:k.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:(p,y)=>a.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[a.jsx("div",{className:"md:col-span-2",children:a.jsx(na,{columns:3,value:p.goalMode,onChange:k=>y(Ut(p,k)),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(j,{label:"Target weight kg",hint:"Filled from the objective; change it anytime.",children:a.jsx(w,{inputMode:"decimal",value:p.goalWeightKg,onChange:k=>y({goalWeightKg:k.target.value}),placeholder:"75.0"})}),a.jsx(j,{label:"Weekly change kg",hint:"Loss/gain rate is converted to kcal/day with the Hall/NIDDK adult dynamic model over Forge's 12-week planning horizon.",children:a.jsx(w,{inputMode:"decimal",value:p.weeklyRateKg,onChange:k=>y({weeklyRateKg:k.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:(p,y)=>a.jsxs("div",{className:"grid gap-4",children:[a.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[a.jsx(j,{label:"Formula resting baseline/day",hint:A,children:a.jsx(w,{inputMode:"decimal",value:C,readOnly:!0,placeholder:"Calculated from profile"})}),a.jsx(j,{label:"Average active calories/day",hint:Vt(n),children:a.jsx(w,{inputMode:"decimal",value:p.activeCaloriesKcal,onChange:k=>y({activeCaloriesKcal:k.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(M,{label:o.restingSource,value:`${o.restingCalories} kcal`}),a.jsx(M,{label:"Maintenance",value:`${o.maintenanceCalories} kcal`}),a.jsx(M,{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:(p,y)=>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(fa,{values:{sex:p.sex,ageYears:Number(p.ageYears)||null,currentWeightKg:Number(p.currentWeightKg)||null,heightCm:Number(p.heightCm)||null,bmrKcal:o.bmr,restingKcal:o.restingCalories,restingSource:o.restingSource,activeKcal:o.activeCalories,maintenanceKcal:o.maintenanceCalories,weeklyRateKg:o.weeklyRateGoalKg,dailyAdjustmentKcal:o.dailyEnergyAdjustment,rateModel:o.rateModelLabel,rateModelHorizonDays:o.rateModelPlanningHorizonDays,calorieTarget:o.calorieTarget,calorieFloor:o.minimumCalorieFloor,proteinReferenceWeightKg:o.proteinReferenceWeight,proteinFactor:p.goalMode==="lose"?2:p.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(M,{label:"Calories",value:`${o.calorieTarget}`}),a.jsx(M,{label:"Protein",value:`${o.proteinGramsTarget}g`}),a.jsx(M,{label:"Carbs",value:`${o.carbohydrateGramsTarget}g`}),a.jsx(M,{label:"Fat",value:`${o.fatGramsTarget}g`}),a.jsx(M,{label:"Fiber",value:`${o.fiberGramsTarget}g`}),a.jsx(M,{label:"Sat fat max",value:`${o.saturatedFatLimitGrams}g`}),a.jsx(M,{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(E,{tone:"meta",children:[f.vitamins.length," vitamins"]}),a.jsxs(E,{tone:"meta",children:[f.minerals.length," minerals"]}),a.jsxs(E,{tone:"signal",children:[f.sportSummary.fluidLossLiters," L sweat"]})]})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[a.jsx(M,{label:"Sport sodium loss",value:`${f.sportSummary.sodiumLossMg} mg`}),a.jsx(M,{label:"Sport potassium loss",value:`${f.sportSummary.potassiumLossMg} mg`}),a.jsx(M,{label:"Water baseline",value:r.sex==="male"?"3.7 L":"2.7 L"}),a.jsx(M,{label:"Essential fats",value:r.sex==="male"?"17g LA / 1.6g ALA":"12g LA / 1.1g ALA"})]})]}),a.jsx(j,{label:"Diet style or constraints",children:a.jsx(ke,{value:p.dietStyle,onChange:k=>y({dietStyle:k.target.value}),placeholder:"Mediterranean, high protein, no lactose, low FODMAP trial..."})})]})}];return a.jsx(Ce,{open:e,onOpenChange:t,eyebrow:"Weight plan",title:"Set weight objective",description:"Build an editable calorie and macro plan.",value:r,onChange:s,steps:b,onSubmit:d,submitLabel:"Save plan",pending:g,pendingLabel:"Saving plan",error:l,draftPersistenceKey:"weight-loss-plan"})}const Xt={tsp:5,tbsp:15,cup:240};function je(){return{mealLabel:"Meal",notes:"",source:"search",selectedItems:[]}}function G(e,t,n){return typeof e!="number"||!Number.isFinite(e)?null:Ma(n)==="grams"?e:t>0?Math.round(e/t*10)/10:e}function en(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 an(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 tn(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 he(e){return typeof e.servingGrams=="number"&&Number.isFinite(e.servingGrams)&&e.servingGrams>0?e.servingGrams:tn(e.servingLabel)}function nn(e){const t=he(e);return t!=null?`${i(t)} g`:e.servingLabel??"serving"}function Ca(e){const t=Number(e.amount)||0;if(t<=0)return null;const n=he(e.food);return e.unit==="grams"?t:e.unit==="tsp"||e.unit==="tbsp"||e.unit==="cup"?t*Xt[e.unit]:n!=null?t*n:null}function sa(e){return!(e.unit==="grams"||e.unit==="tsp"||e.unit==="tbsp"||e.unit==="cup")||he(e.food)!=null?null:"Add base grams before using grams or household measures. Without a denominator, Forge will not guess a ratio."}function Ma(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 rn(e){switch(e){case"manual":case"search":case"barcode":case"chatgpt":case"photo":case"saved_meal":return e;default:return"manual"}}function sn(e){return{mealLabel:e.mealLabel??"Meal",notes:e.notes??"",loggedAt:e.loggedAt,dayKey:e.dayKey,source:rn(e.source),selectedItems:e.items.map(t=>({localId:t.id,food:en(t),amount:String(t.quantity||1),unit:t.unit??"serving"}))}}function on(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:an(n,r,t),amount:String(n.quantity||1),unit:Ma(n.unit)}))}}function Fa(){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 ln(){return{mealLabel:"Meal",notes:"",source:"manual",selectedItems:[{localId:`custom-${Date.now()}`,food:Fa(),amount:"100",unit:"grams"}]}}function cn({open:e,onOpenChange:t,value:n,onChange:r,foodResults:s,searchPending:d,chatGptPending:g=!1,chatGptError:l=null,logPending:o,onSearch:u,onParseWithChatGpt:C,onSubmit:A,mode:f="create",intent:b="search",initialStepId:p}){const[y,k]=K.useState(""),[$,T]=K.useState(""),[P,W]=K.useState(null),q=K.useMemo(()=>pn(n.selectedItems),[n.selectedItems]),R=x=>r({...n,...x}),te=x=>{R({selectedItems:[...n.selectedItems,{localId:`${x.id}-${Date.now()}`,food:x,amount:"1",unit:"serving"}]}),W(null)},Y=()=>{te(Fa())},X=async()=>{const x=$.trim();!x||!C||(await C(x),T(""))},O=(x,v)=>{R({selectedItems:n.selectedItems.map(N=>N.localId===x?{...N,...v}:N)})},le=(x,v)=>{R({selectedItems:n.selectedItems.map(N=>N.localId===x?{...N,food:{...N.food,...v}}:N)})},ne=x=>{R({selectedItems:n.selectedItems.filter(v=>v.localId!==x)})},ce=async()=>{n.selectedItems.length!==0&&await A()},ee=a.jsxs(I,{className:"grid gap-3",children:[a.jsx(j,{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(ke,{value:$,onChange:x=>T(x.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(D,{type:"button",variant:b==="chatgpt"?"primary":"secondary",pending:g,pendingLabel:"Parsing",disabled:!$.trim()||!C,onClick:()=>void X(),children:[a.jsx(ua,{className:"size-4"}),"Parse with ChatGPT"]})]}),re=a.jsx(I,{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(D,{type:"button",size:"sm",onClick:Y,children:[a.jsx(Be,{className:"size-4"}),"Add custom"]})]})}),J=b==="chatgpt"?[ee,re]:[re,ee],pe=[{id:"search",eyebrow:b==="chatgpt"?"ChatGPT food parser":"Food",title:b==="chatgpt"?"Describe the meal, then review every item":"Search, create, or ask ChatGPT",description:b==="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(j,{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(w,{value:y,onChange:x=>k(x.target.value),placeholder:"Search eggs, yogurt, sourdough..."})}),a.jsxs(D,{type:"button",variant:"secondary",pending:d,disabled:!y.trim(),onClick:()=>u(y),children:[a.jsx(ga,{className:"size-4"}),"Search"]})]}),a.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:J.map((x,v)=>a.jsx("div",{children:x},`${b}-assistant-panel-${v}`))}),P?a.jsx(hn,{food:P,onAdd:()=>te(P)}):null,a.jsx("div",{className:"grid gap-3",children:s.map(x=>a.jsx(I,{interactive:!0,className:"p-0",children:a.jsx("button",{type:"button",className:"block w-full rounded-[22px] p-4 text-left",onClick:()=>W(x),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:x.name}),a.jsx("div",{className:"mt-1 truncate text-xs text-[var(--ui-ink-faint)]",children:[x.brand,x.servingLabel,x.source].filter(Boolean).join(" · ")})]}),a.jsxs(E,{tone:"meta",children:[i(x.calories)," kcal"]})]})})},x.id))})]})},{id:"amounts",eyebrow:b==="custom"?"Custom food":"Quantity",title:b==="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:x=>a.jsxs("div",{className:"grid gap-4",children:[x.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,x.selectedItems.map(v=>a.jsxs(I,{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"," ",nn(v.food)]})]}),a.jsxs(D,{type:"button",size:"sm",variant:"ghost",onClick:()=>ne(v.localId),children:[a.jsx(ha,{className:"size-4"}),"Remove"]})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto]",children:[a.jsx(j,{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(w,{inputMode:"decimal",value:v.amount,onChange:N=>O(v.localId,{amount:N.target.value}),placeholder:"1"})}),a.jsx(j,{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:N=>O(v.localId,{unit:N.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(E,{tone:"signal",children:[i(we(v).calories)," kcal"]})]}),sa(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:sa(v)}):a.jsxs("div",{className:"text-xs text-[var(--ui-ink-faint)]",children:[i(Number(v.amount)||0)," ",v.unit," ="," ",i(Ca(v))," g eaten; ratio ="," ",i(we(v).scale),"x the base nutrition."]}),a.jsx(mn,{item:v,onChange:N=>le(v.localId,N)})]},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(M,{label:"Calories",value:i(q.calories)}),a.jsx(M,{label:"Protein",value:`${i(q.proteinGrams)}g`}),a.jsx(M,{label:"Carbs",value:`${i(q.carbohydrateGrams)}g`}),a.jsx(M,{label:"Fat",value:`${i(q.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:(x,v)=>a.jsxs("div",{className:"grid gap-4",children:[a.jsx(j,{label:"Meal label",labelHelp:"The label groups the edited items as breakfast, lunch, snack, dinner, or any personal meal name.",children:a.jsx(w,{value:x.mealLabel,onChange:N=>v({mealLabel:N.target.value}),placeholder:"Breakfast"})}),a.jsx(j,{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(ke,{value:x.notes,onChange:N=>v({notes:N.target.value}),placeholder:"Energy, cravings, gut comfort, training effect..."})})]})}];return a.jsx(Ce,{open:e,onOpenChange:t,eyebrow:"Food log",title:f==="edit"?"Edit food":"Add food",description:"Search, inspect, scale, edit nutrition parameters, and save meal items.",value:n,onChange:r,steps:pe,initialStepId:p,onSubmit:ce,submitLabel:f==="edit"?"Update meal":"Save meal",pending:o,pendingLabel:"Saving meal",resolveError:x=>x!=="search"&&n.selectedItems.length===0?"Select at least one food before saving.":null,draftPersistenceKey:`weight-loss-food-log.${f}.${b}`})}function Ka(e){return{loggedAt:e.loggedAt,dayKey:e.dayKey??We(),mealLabel:ia(e.mealLabel,"Meal"),source:e.source??"search",confirmationState:"confirmed",notes:ia(e.notes),items:e.selectedItems.map(t=>{const n=we(t);return{foodId:dn(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 ia(e,t=""){return typeof e=="string"?e:t}function dn(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 un(e){return Ka(e)}function gn(e){const t=Number(e);return Number.isFinite(t)?t:null}function mn({item:e,onChange:t}){const n=e.food,r=(s,d)=>t({[s]:gn(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(me,{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(j,{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(w,{value:n.servingLabel??"",onChange:s=>t({servingLabel:s.target.value||null}),placeholder:"100 g"})}),a.jsx(j,{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(w,{inputMode:"decimal",value:n.servingGrams??"",onChange:s=>r("servingGrams",s.target.value),placeholder:"100"})}),a.jsx(j,{label:"Food name",labelHelp:"Rename the item when the database result is too generic or wrong.",children:a.jsx(w,{value:n.name,onChange:s=>t({name:s.target.value})})}),a.jsx(j,{label:"Brand",labelHelp:"Optional brand or preparation source, useful when the same food has different nutrition.",children:a.jsx(w,{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(j,{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(w,{inputMode:"decimal",value:n.calories??"",onChange:s=>r("calories",s.target.value)})}),a.jsx(j,{label:"Protein g",labelHelp:"Protein grams for the base amount above. This is scaled by the same gram ratio as calories.",children:a.jsx(w,{inputMode:"decimal",value:n.proteinGrams??"",onChange:s=>r("proteinGrams",s.target.value)})}),a.jsx(j,{label:"Carbs g",labelHelp:"Carbohydrate grams for the base amount above. Carbs are training fuel after protein and fat are allocated.",children:a.jsx(w,{inputMode:"decimal",value:n.carbohydrateGrams??"",onChange:s=>r("carbohydrateGrams",s.target.value)})}),a.jsx(j,{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(w,{inputMode:"decimal",value:n.fatGrams??"",onChange:s=>r("fatGrams",s.target.value)})}),a.jsx(j,{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(w,{inputMode:"decimal",value:n.fiberGrams??"",onChange:s=>r("fiberGrams",s.target.value)})}),a.jsx(j,{label:"Sugar g",labelHelp:"Sugar grams for the base amount above. Added sugar is tracked as a ceiling, not a goal.",children:a.jsx(w,{inputMode:"decimal",value:n.sugarGrams??"",onChange:s=>r("sugarGrams",s.target.value)})}),a.jsx(j,{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(w,{inputMode:"decimal",value:n.sodiumMg??"",onChange:s=>r("sodiumMg",s.target.value)})})]})]})}function hn({food:e,onAdd:t}){return a.jsxs(V,{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(D,{type:"button",onClick:t,children:[a.jsx(Be,{className:"size-4"}),"Add"]})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[a.jsx(M,{label:"Calories",value:i(e.calories)}),a.jsx(M,{label:"Protein",value:`${i(e.proteinGrams)}g`}),a.jsx(M,{label:"Carbs",value:`${i(e.carbohydrateGrams)}g`}),a.jsx(M,{label:"Fat",value:`${i(e.fatGrams)}g`}),a.jsx(M,{label:"Fiber",value:`${i(e.fiberGrams)}g`}),a.jsx(M,{label:"Sugar",value:`${i(e.sugarGrams)}g`}),a.jsx(M,{label:"Sodium",value:`${i(e.sodiumMg)}mg`}),a.jsx(M,{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(Ja,{className:"size-4"}),"Base grams: ",i(he(e)),". Adjust exact intake in the next step."]})]})}function we(e){const t=Number(e.amount)||0,n=he(e.food),r=Ca(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 pn(e){return e.reduce((t,n)=>{const r=we(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 oa(){return{weightKg:"",waistCm:"",bodyFatPercent:"",energy:"",hunger:"",cravings:"",bloating:"",facePuffiness:"",leanness:"",notes:""}}function bn({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(j,{label:"Weight kg",children:a.jsx(w,{inputMode:"decimal",value:l.weightKg,onChange:u=>o({weightKg:u.target.value})})}),a.jsx(j,{label:"Waist cm",children:a.jsx(w,{inputMode:"decimal",value:l.waistCm,onChange:u=>o({waistCm:u.target.value})})}),a.jsx(j,{label:"Body fat %",children:a.jsx(w,{inputMode:"decimal",value:l.bodyFatPercent,onChange:u=>o({bodyFatPercent:u.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(j,{label:"Energy 0-10",children:a.jsx(w,{inputMode:"decimal",value:l.energy,onChange:u=>o({energy:u.target.value})})}),a.jsx(j,{label:"Hunger 0-10",children:a.jsx(w,{inputMode:"decimal",value:l.hunger,onChange:u=>o({hunger:u.target.value})})}),a.jsx(j,{label:"Cravings 0-10",children:a.jsx(w,{inputMode:"decimal",value:l.cravings,onChange:u=>o({cravings:u.target.value})})}),a.jsx(j,{label:"Bloating 0-10",children:a.jsx(w,{inputMode:"decimal",value:l.bloating,onChange:u=>o({bloating:u.target.value})})}),a.jsx(j,{label:"Face puffiness 0-10",children:a.jsx(w,{inputMode:"decimal",value:l.facePuffiness,onChange:u=>o({facePuffiness:u.target.value})})}),a.jsx(j,{label:"Leanness 0-10",children:a.jsx(w,{inputMode:"decimal",value:l.leanness,onChange:u=>o({leanness:u.target.value})})})]})},{id:"notes",eyebrow:"Context",title:"Notes",description:"Capture anything that explains the signal.",render:(l,o)=>a.jsx(j,{label:"Notes",children:a.jsx(ke,{value:l.notes,onChange:u=>o({notes:u.target.value}),placeholder:"Sleep, sodium, workout soreness, stressful day..."})})}];return a.jsx(Ce,{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 xn(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 fn(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 vn(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 yn({open:e,onOpenChange:t,meals:n,onLogAgain:r,onEdit:s,onDelete:d,pending:g}){return a.jsx(Ce,{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(I,{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:fn(l)}),a.jsxs("div",{className:"mt-1 text-xs text-[var(--ui-ink-faint)]",children:[l.loggedAt.slice(0,10)," ·"," ",vn(l)||l.mealLabel||"No quantity recorded"]})]}),a.jsxs(E,{tone:"meta",children:[l.totals.calories.toFixed(0)," kcal"]})]}),a.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.jsx(D,{type:"button",size:"sm",variant:"secondary",onClick:()=>s(l),children:"Edit"}),a.jsx(D,{type:"button",size:"sm",variant:"ghost",pending:g,onClick:()=>d(l),children:"Delete"}),a.jsx(D,{type:"button",size:"sm",variant:"secondary",pending:g,onClick:()=>r(l),children:"Log again"})]})]},l.id))})}],onSubmit:async()=>t(!1),submitLabel:"Done"})}function jn(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 kn(e){const t=e.energyModel,n=t.sourceAvailability,r=[n.healthKitDailyEnergy?"HealthKit active energy":null,t.formulaRestingKcal!=null?"formula resting baseline":null,t.wearableRestingKcal!=null?"complete-day HealthKit resting evidence":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 Nn(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)} = ${H(t.estimatedDailyEnergyBalanceKcal)} kcal/day.`,s=t.restingEnergyCalories!=null&&t.activeBurnKcal!=null?`TDEE = formula resting baseline ${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 wn(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 = formula resting baseline ${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)} = ${H(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.",u=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)} = formula resting baseline ${i(t.restingEnergyCalories)} + active burn ${i(t.activeBurnKcal)}; energy gap ${H(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)} = formula resting baseline ${i(t.restingEnergyCalories)} + active burn ${i(t.activeBurnKcal)}; energy gap ${H(t.estimatedDailyEnergyBalanceKcal)} = intake ${i(t.averageCalorieIntake)} - TDEE ${i(t.estimatedTdeeKcal)}.`:`Arithmetic shown here: TDEE ${i(t.estimatedTdeeKcal)} = formula resting baseline ${i(t.restingEnergyCalories)} + active burn ${i(t.activeBurnKcal)}; energy gap ${H(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.",C=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.",A=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.",f=`Today is separate: today's target = baseline plan target plus the day-specific active adjustment. Today active evidence currently uses ${Aa(t.todayActiveCaloriesSource)}: ${i(t.todayActiveCaloriesKcal)} kcal. Default active calories: ${i(t.baselineActiveCaloriesKcal)} kcal. Eat-back fraction ${i(t.activityEatBackFraction*100,0)}%; target adjustment ${H(t.todayTargetAdjustmentKcal)} kcal. Automatic low or early same-day activity cannot reduce the target; a manual override can raise or lower it for this date.`,b=t.energySourceConfidence==="healthkit_daily_active_energy"?"Data path: recent food logs provide intake; HealthKit daily active-energy rows provide active burn; Mifflin-St Jeor provides the stable resting baseline. Complete HealthKit basal rows are shown as calibration evidence.":t.energySourceConfidence==="workout_movement_fallback"?"Data path: recent food logs provide intake; Mifflin-St Jeor provides the stable resting baseline; 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?"the formula resting baseline plus the selected active-burn branch":"the configured/inferred plan estimate because formula 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:"})," ",u]}),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; formula 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:"})," ",b]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Food window:"})," ",C," 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?"formula resting baseline 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:"})," ",jn(t.energySourceConfidence)," across"," ",t.evidenceDays," expenditure evidence day",t.evidenceDays===1?"":"s"," ending the selected day (",r,"). Available streams: ",kn(e),"."," ",A]}),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:"})," ",f]})]})}function Cn(e){const t=H(e);return t==="n/a"?t:`${t} kcal/d`}function Aa(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 la(e){return`${e>=0?"+":""}${e.toFixed(0)} kcal`}function Mn(e){return e>=0?`${e.toFixed(0)} kcal left`:`${Math.abs(e).toFixed(0)} kcal over`}function ca(e){return e.trim()===""?"0":e}function da(e,t,n){const r=e.energyModel.baselineActiveCaloriesKcal??e.energyModel.todayActiveCaloriesKcal??0,s=e.energyModel.activityEatBackFraction??0,d=t-r,g=Math.round(d*s),l=e.energyModel.todayTargetAdjustmentKcal??0,o=e.todayLedger.plannedTargetCalories??e.todayLedger.targetCalories-l,u=Math.max(0,Math.round(o+g)),C=Math.round(e.todayLedger.totals.calories-u),A=Math.round(u-e.todayLedger.totals.calories),f=Math.max(0,d),b=Math.round(f*s);return{...e,summary:{...e.summary,targetCalories:u,todayCalorieDelta:C,remainingCalories:A},todayLedger:{...e.todayLedger,plannedTargetCalories:o,targetCalories:u,activeAdjustmentCalories:g,activeCaloriesSource:"user_override",calorieDelta:C,remainingCalories:A},energyModel:{...e.energyModel,todayActiveCaloriesKcal:t,todayActiveCaloriesSource:"user_override",todayTargetAdjustmentKcal:g,todayActiveDeltaKcal:Math.round(d),todayActiveSurplusKcal:Math.round(f),todayActivityBufferKcal:b,todayActiveOverride:n}}}function Fn(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 Kn(){const e=new Date,t=new Date(e);return t.setHours(24,0,2,0),Math.max(1e3,t.getTime()-e.getTime())}function Wn(){const e=rt(),t=at(),n=e.selectedUserIds,[r,s]=K.useState(()=>We()),d=K.useMemo(()=>Fn(r),[r]),g=K.useMemo(()=>["forge-weight-loss-view",r,...n],[r,n]),[l,o]=K.useState(!1),[u,C]=K.useState(!1),[A,f]=K.useState(!1),[b,p]=K.useState(!1),[y,k]=K.useState(!1),[$,T]=K.useState(null),[P,W]=K.useState(null),[q,R]=K.useState(""),[te,Y]=K.useState(null),[X,O]=K.useState(null),[le,ne]=K.useState("search"),[ce,ee]=K.useState(void 0),[re,J]=K.useState(()=>je()),[pe,x]=K.useState(()=>oa()),v=tt({queryKey:g,queryFn:async()=>(await bt(n,{dateKey:r,...d})).weightLoss}),N=v.data;K.useEffect(()=>{const c=()=>{s(S=>{const de=We();return de===S?S:de})},m=window.setTimeout(c,Kn());return window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.clearTimeout(m),window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[r]),K.useEffect(()=>{!N||u||l||Qt(N)||(C(!0),Y(Le(N)),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))},[u,N,l]),K.useEffect(()=>{N&&(R(String(Math.round(N.energyModel.todayActiveCaloriesKcal??0))),W(null))},[N==null?void 0:N.generatedAt,N==null?void 0:N.energyModel.todayActiveCaloriesKcal]);const ae=()=>t.invalidateQueries({queryKey:g}),Ga=c=>{R(ca(c))},Me=U({mutationFn:async c=>(await gt({query:c,userIds:n})).foods}),be=U({mutationFn:async c=>ut({text:c,userIds:n,commitCandidate:!1}),onSuccess:({candidate:c})=>{J(on(c,"chatgpt"))}}),ze=U({mutationFn:async c=>aa(Ka(c),n),onSuccess:()=>{J(je()),f(!1),ae()}}),qe=U({mutationFn:async({foodLogId:c,draft:m})=>dt(c,un(m),n),onSuccess:()=>{J(je()),O(null),f(!1),ae()}}),Fe=U({mutationFn:async c=>ot(c.id,n),onSuccess:()=>{ae()}}),Ke=U({mutationFn:async c=>lt({dayKey:N==null?void 0:N.todayLedger.dateKey,activeCaloriesKcal:c,notes:c==null?"":"Manual active-calorie override from the weight-loss view"},n),onMutate:c=>{if(c==null)return null;const m=t.getQueryData(g);return t.setQueryData(g,S=>{var Ze,Xe;if(!S)return S;const de=new Date().toISOString();return da(S,c,{id:((Ze=S.energyModel.todayActiveOverride)==null?void 0:Ze.id)??"optimistic",userId:S.userId,dayKey:S.todayLedger.dateKey,activeCaloriesKcal:c,notes:"Manual active-calorie override from the weight-loss view",createdAt:((Xe=S.energyModel.todayActiveOverride)==null?void 0:Xe.createdAt)??de,updatedAt:de})}),m?{previous:m}:null},onSuccess:(c,m)=>{W(null),m!=null&&t.setQueryData(g,S=>S&&da(S,m,c.override)),ae()},onError:(c,m,S)=>{S!=null&&S.previous&&t.setQueryData(g,S.previous),W(c instanceof Error?c.message:"Could not save active calories")}}),xe=U({mutationFn:async c=>{const m=Number(c.currentWeightKg);await ct(Jt(c),n),Number.isFinite(m)&&await ta({weightKg:m,notes:"Updated from weight-plan setup."},n)},onSuccess:()=>{o(!1),ae()}}),Oe=U({mutationFn:async c=>{const m=xn(c);await Promise.all([m.body.weightKg!==null||m.body.waistCm!==null||m.body.bodyFatPercent!==null?ta(m.body,n):Promise.resolve(),m.subjective.energy!==null||m.subjective.hunger!==null||m.subjective.cravings!==null?mt(m.subjective,n):Promise.resolve(),m.gut.bloating!==null?ht(m.gut,n):Promise.resolve(),m.appearance.facePuffiness!==null||m.appearance.leanness!==null?pt(m.appearance,n):Promise.resolve()])},onSuccess:()=>{x(oa()),p(!1),ae()}}),fe=U({mutationFn:async c=>aa({mealLabel:c.mealLabel??"Saved meal",source:"saved_meal",confirmationState:"confirmed",notes:c.notes??"",items:c.items.map(m=>({foodId:m.foodId,name:m.name,brand:m.brand,quantity:m.quantity,unit:m.unit,grams:m.grams,calories:m.calories,proteinGrams:m.proteinGrams,carbohydrateGrams:m.carbohydrateGrams,fatGrams:m.fatGrams,fiberGrams:m.fiberGrams,sugarGrams:m.sugarGrams,sodiumMg:m.sodiumMg,potassiumMg:m.potassiumMg,caffeineMg:m.caffeineMg,alcoholGrams:m.alcoholGrams,glycemicIndex:m.glycemicIndex,novaGroup:m.novaGroup,fermented:m.fermented,probiotic:m.probiotic,fodmapLevel:m.fodmapLevel,tags:m.tags,confidence:m.confidence??.85}))},n),onSuccess:()=>{ae()}});if(v.isLoading)return a.jsx(st,{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(it,{error:v.error??new Error("Weight-loss view unavailable"),onRetry:()=>void v.refetch()});const F=v.data,L=F.todayLedger,Ue=L.totals,Ae=Ue.calories,Ge=Number.isFinite(L.remainingCalories)?L.remainingCalories:L.targetCalories-Ae,Sa=L.plannedTargetCalories??L.targetCalories,Se=F.energyModel.todayActiveCaloriesKcal??F.energyModel.activeBurnKcal??F.energyModel.activeEnergyCalories??F.energyModel.movementCaloriesKcal??0,Da=F.energyModel.baselineActiveCaloriesKcal??Se,Qe=L.activeAdjustmentCalories??0,_a=Qe===0?"no day-specific active adjustment":`${la(Qe)} active adjustment from ${Aa(L.activeCaloriesSource)}`,Ea=L.targetCalories>0?Math.min(140,Math.max(0,Ae/L.targetCalories*100)):0,$a=F.energyModel,Ve=F.weightTrend,ve=F.foodQuality,De=F.trainingFuel,Ta=F.subjective,La=F.gut,Ia=ft(F.hypotheses),_e=te??Le(F),Pa=()=>{T(null),Y(Le(F)),o(!0)},Ee=(c="search")=>{O(null),ne(c),ee(c==="custom"?"amounts":"search"),J(c==="custom"?ln():je()),f(!0)},Ye=c=>{O(c.id),ne("search"),ee("amounts"),J(sn(c)),f(!0),k(!1)},Je=c=>{typeof window<"u"&&!window.confirm(`Delete ${c.mealLabel??"this meal"} from the food log?`)||Fe.mutate(c)},Wa=()=>{const c=ca(q);R(c);const m=Number(c);if(!Number.isFinite(m)||m<0){W("Enter a valid active-calorie value.");return}Ke.mutate(Math.round(m))},Ra=()=>{Ke.mutate(null)};return a.jsxs("div",{className:"mx-auto grid w-full max-w-[1500px] gap-5",children:[a.jsx(nt,{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:`${L.targetCalories.toFixed(0)} kcal budget · ${F.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(Kt,{ledger:L,remainingCalories:Ge,intakePercent:Ea,logSavedPending:fe.isPending||Fe.isPending,onLogAgain:c=>fe.mutate(c),onEditMeal:Ye,onDeleteMeal:Je}),a.jsxs("div",{className:"grid min-w-0 gap-4",children:[a.jsx(xt,{view:F,onOpenPlan:Pa,onOpenFoodSearch:()=>Ee("search"),onOpenCustomFood:()=>Ee("custom"),onOpenChatGptFood:()=>Ee("chatgpt"),onOpenCheckin:()=>p(!0),onOpenHistory:()=>k(!0)}),a.jsx(Nt,{view:F,draftValue:q,pending:Ke.isPending,error:P,onDraftChange:Ga,onSave:Wa,onReset:Ra})]})]}),a.jsxs("section",{className:"grid gap-4 xl:grid-cols-4",children:[a.jsx(Z,{label:"Today",value:`${Ae.toFixed(0)} / ${L.targetCalories.toFixed(0)} kcal`,detail:`${Mn(Ge)}. Target uses ${Se.toFixed(0)} active kcal today; ${_a}.`,icon:ea,tone:Ge>=0?"green":"rose",help:`Today's target = baseline plan target plus the day-specific active adjustment. Here: ${Sa.toFixed(0)} ${la(F.energyModel.todayTargetAdjustmentKcal)} = ${L.targetCalories.toFixed(0)} kcal. Same-day evidence is ${Se.toFixed(0)} kcal versus default ${Da.toFixed(0)} kcal. Automatic partial evidence can only add above the baseline; a manual override can raise or lower today's target for this date.`}),a.jsx(Z,{label:"Protein",value:`${Ue.proteinGrams.toFixed(0)}g`,detail:`${F.target.proteinGramsTarget.toFixed(0)}g target. Protein anchors the plan while cutting or gaining.`,icon:Za,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(Z,{label:"Energy gap",value:Cn($a.estimatedDailyEnergyBalanceKcal),detail:Nn(F),icon:Xa,tone:"amber",help:wn(F),helpMaxWidthPx:560}),a.jsx(Z,{label:"Weight trend",value:H(Ve.sevenDayRateKg,2),detail:`Latest ${i(Ve.latestWeightKg,1)} kg. Trend uses check-ins, not noisy single weigh-ins.`,icon:Ie,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(St,{view:F}),a.jsx(Ht,{view:F}),a.jsxs("section",{className:"grid gap-4 xl:grid-cols-4",children:[a.jsx(Z,{label:"Food quality",value:ye(ve.qualityScore),detail:`Fiber density ${i(ve.fiberPer1000Kcal,1)}g/1000 kcal, protein density ${i(ve.proteinPer1000Kcal,1)}g/1000 kcal, ultra-processed share ${i(ve.ultraProcessedShare,0)}%.`,icon:ea,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(Z,{label:"Training fuel",value:ye(De.fuelingScore),detail:`Recent workout load ${i(De.recentTrainingLoad)} with ${i(De.carbsPerTrainingLoad,1)}g carbs per load unit.`,icon:pa,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(Z,{label:"Subjective",value:ye(Ta.averageFocus),detail:"Focus, energy, hunger, cravings, and performance are tracked as food-effect evidence.",icon:Ie,help:"Subjective signals are self-rated energy, focus, hunger, cravings, and performance. Forge uses them to discover food and timing effects."}),a.jsx(Z,{label:"Gut",value:ye(La.averageBloating),detail:"Bloating, reflux, stool type, and suspected triggers connect food choices to comfort and look.",icon:et,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(At,{hypotheses:Ia}),a.jsx(Gt,{experiments:F.experiments})]}),a.jsx(Zt,{open:l,onOpenChange:o,view:F,value:_e,onChange:c=>{Y(c),T(null)},pending:xe.isPending,error:$??(xe.error instanceof Error?xe.error.message:null),onSubmit:async()=>{const c=Yt(_e);if(c){T(c);return}await xe.mutateAsync(_e)}}),a.jsx(cn,{open:A,onOpenChange:f,value:re,onChange:J,foodResults:Me.data??[],searchPending:Me.isPending,chatGptPending:be.isPending,chatGptError:be.error instanceof Error?be.error.message:null,logPending:ze.isPending||qe.isPending,intent:le,initialStepId:ce,onSearch:c=>Me.mutate(c),onParseWithChatGpt:c=>be.mutateAsync(c).then(()=>{}),mode:X?"edit":"create",onSubmit:async()=>{if(X){await qe.mutateAsync({foodLogId:X,draft:re});return}await ze.mutateAsync(re)}}),a.jsx(bn,{open:b,onOpenChange:p,value:pe,onChange:x,pending:Oe.isPending,onSubmit:async()=>{await Oe.mutateAsync(pe)}}),a.jsx(yn,{open:y,onOpenChange:k,meals:F.recentMeals,pending:fe.isPending||Fe.isPending,onLogAgain:c=>fe.mutate(c),onEdit:Ye,onDelete:Je})]})}export{Wn as WeightLossPage};
@@ -1,4 +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-QJkjKYzZ.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(`
1
+ import{j as a,aC as j,r as w}from"./vendor-Cpmju3nw.js";import{c as u,a_ as N,c8 as $}from"./index-wEZUnRh0.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
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
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};
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)]",I="text-[var(--ui-ink-strong)]",b="border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)]",T="border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)]",q="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:q,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 _(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]",I,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)]":T),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-","")}),_(i.lines,n)]},`${i.type}-${e}`)}}function P(i,e,n){return a.jsx("div",{className:u("text-[13px] leading-6",x),children:h(i,e,n)})}function R({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:P(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(R,{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};
@@ -1,18 +1,18 @@
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-QJkjKYzZ.js";import{W as xa}from"./wiki-article-markdown-Bi02AsVt.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
1
+ import{aJ as Be,b6 as Qe,c6 as De,bY as Ke,r as d,j as e,cr as Ve,cs as qe,cL as He,cm as Ue,c5 as Je,aU as Ye,aR as Ge,ca as Xe,dH as Ze,dI as ea,aK as we,bG as aa}from"./vendor-Cpmju3nw.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-B9O-eUim.js";import{j as sa,i as Y,k as ta}from"./state-BtwEvpO6.js";import{E as F}from"./entity-link-multiselect-DZZjpL_d.js";import{d as ra,k as g,g as P,L as ia,e as na,h as la,B as C,c as j,I as T,T as E,a4 as ve,ey as oa,cl as da,bn as ca,ez as ua,eA as pa}from"./index-wEZUnRh0.js";import{W as xa}from"./wiki-article-markdown-D0PWvioX.js";import"./use-anchored-overlay-position-BrQ4cqKn.js";import"./motion-DwjmC9aq.js";import"./board-CLOHbg6t.js";import"./forms-C5d5hTf2.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
2
 
3
3
  `,author:"",tagsText:"",frontmatterText:`{
4
4
  "status": "draft"
5
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
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(`
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 Oa(){var ie,ne,le,oe,de,ce,ue,pe,xe,me,he,ge;const t=ra(),r=sa(),v=Be(),W=Qe(),{pageId:m}=De(),[A,Oe]=Ke(),[l,c]=d.useState(()=>Me()),[S,p]=d.useState(null),[B,G]=d.useState(""),[f,z]=d.useState(""),[Pe,Q]=d.useState(!1),[D,Ee]=d.useState(!1),[K,V]=d.useState(""),[q,H]=d.useState(""),X=d.useRef(null),Z=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=Y({queryKey:["forge-wiki-settings"],queryFn:ca}),k=Y({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=Y({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||Z.current||!U||(Z.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(K);return a?O.filter(s=>`${s.title} ${s.slug} ${s.summary}`.toLowerCase().includes(a)).slice(0,12):O.slice(0,12)},[K,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(q);return a?R.filter(s=>`${s.label} ${s.description??""} ${s.searchText??""}`.toLowerCase().includes(a)).slice(0,12):R.slice(0,12)},[R,q]),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=X.current;c(n=>{const o=n.contentMarkdown;if(!s)return{...n,contentMarkdown:`${o}${o.endsWith(`
8
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
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?oa(a.pageId,s):da(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(ia,{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(na,{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(la,{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:Ye,label:"Forge link"},{kind:"infobox",icon:Ge,label:"Infobox"},{kind:"admonition",icon:Xe,label:"Admonition"},{kind:"related",icon:Ze,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":D,children:[D?e.jsx(Ve,{className:"size-3.5"}):e.jsx(qe,{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",D?"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),G(""),z(""),V(""),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:X,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:K,onChange:a=>V(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),V("")},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:q,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
10
  Title: ${l.title||"Article title"}
11
11
  Summary: ${l.summary||"Short summary"}
12
12
  Tags: ${l.tagsText||"tag-one, tag-two"}
13
13
  Related: [[index|Home]]
14
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}
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=>G(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
16
  ${f.trim()}
17
17
  :::
18
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]]
@@ -23,4 +23,4 @@ ${f.trim()}
23
23
  Caption: Inspiration frame`}),e.jsx(C,{disabled:!f.trim(),onClick:()=>{I(`:::forge-media
24
24
  ${f.trim()}
25
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};
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{Oa as WikiEditorPage};
@@ -0,0 +1 @@
1
+ import{b6 as F,bY as J,r as R,j as s,aG as D,c1 as Q,bV as E}from"./vendor-Cpmju3nw.js";import{j as H,i as q,k as z}from"./state-BtwEvpO6.js";import{W as A}from"./wiki-ingest-modal-Ro0V4UMB.js";import{P as _}from"./page-hero-BRcqE3a4.js";import{S as U,e as O,C as W,B as f,I as w,c as B,h as G,eu as $,bn as Y,ex as V}from"./index-wEZUnRh0.js";import"./ui-B9O-eUim.js";import"./motion-DwjmC9aq.js";import"./board-CLOHbg6t.js";import"./forms-C5d5hTf2.js";const X=[{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 Z(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 ue(){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:()=>V({spaceId:c||void 0,limit:200}),enabled:r.isSuccess}),x=z({mutationFn:e=>$(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(U,{eyebrow:"KarpaWiki",title:"Loading ingest history",description:"Gathering prior imports, statuses, and review state.",columns:1,blocks:6}):r.isError||d.isError?s.jsx(O,{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:X.map(e=>s.jsx("button",{type:"button",className:B("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(G,{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:Z(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(Q,{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(E,{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{ue as WikiIngestHistoryPage};