forge-openclaw-plugin 0.3.17 → 0.3.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{action-bar-D3CEYlj4.js → action-bar-BAZevCEA.js} +1 -1
- package/dist/assets/{activity-page-Ce1pHIu5.js → activity-page-CnT_hnCU.js} +1 -1
- package/dist/assets/{ai-surface-workspace-DEliwOjF.js → ai-surface-workspace-GPZzIIut.js} +1 -1
- package/dist/assets/artifacts-page-Bqjp0L-L.js +2 -0
- package/dist/assets/{atlas-panel-VZOnJa1c.js → atlas-panel-B95nrYpZ.js} +1 -1
- package/dist/assets/{board-DprRipIG.js → board-CGgOvBP9.js} +1 -1
- package/dist/assets/{calendar-page-Zstsn4uG.js → calendar-page-mlr94wIS.js} +1 -1
- package/dist/assets/{calendar-rules-BGIBuEDk.js → calendar-rules-DdxPmBZJ.js} +1 -1
- package/dist/assets/{calendar-week-toolbar-DXFkMkbq.js → calendar-week-toolbar-Cu8V6zv1.js} +1 -1
- package/dist/assets/{charts-C5S0-BL7.js → charts-Cdtn55ol.js} +1 -1
- package/dist/assets/{companion-sync-lab-page-DIPPLFKt.js → companion-sync-lab-page-CJI5jf8W.js} +1 -1
- package/dist/assets/{daily-metrics-dashboard-CG-OOCJz.js → daily-metrics-dashboard-CXESx7bU.js} +1 -1
- package/dist/assets/{define-workbench-box-BEEdtBkQ.js → define-workbench-box-Dbl9W7oE.js} +1 -1
- package/dist/assets/{entity-link-multiselect-BfDAROHB.js → entity-link-multiselect-DZ_jAjs4.js} +1 -1
- package/dist/assets/{entity-note-count-link-BGOiaash.js → entity-note-count-link-FOK_qhcC.js} +1 -1
- package/dist/assets/{entity-notes-surface-DPsJwqQa.js → entity-notes-surface-Dq9dFKjD.js} +1 -1
- package/dist/assets/{execution-board-Dg-2GSKv.js → execution-board-D9hkXKC2.js} +1 -1
- package/dist/assets/{faceted-token-search-DV7MSVYb.js → faceted-token-search-BeShxjkc.js} +1 -1
- package/dist/assets/{flagship-signal-deck-D3wVL3bC.js → flagship-signal-deck-DZx_HEH9.js} +1 -1
- package/dist/assets/{floating-action-menu-BUs382px.js → floating-action-menu-CFrgvQJi.js} +1 -1
- package/dist/assets/{forms-ByKjodjN.js → forms-DhEGHkFR.js} +1 -1
- package/dist/assets/{generic-node-view-BY5dbPXJ.js → generic-node-view-C1kLClIm.js} +1 -1
- package/dist/assets/{goal-detail-page-MYr6j2B4.js → goal-detail-page-BhMrnVQs.js} +1 -1
- package/dist/assets/{goal-dialog-nkdME5Uy.js → goal-dialog-BlZHh3dw.js} +1 -1
- package/dist/assets/{goals-page-BsFeBzU1.js → goals-page-CesC8IkZ.js} +1 -1
- package/dist/assets/{graph-CHVj0Z7n.js → graph-U1J6VkbG.js} +1 -1
- package/dist/assets/{habits-page-wO461EVU.js → habits-page-DHxZSThT.js} +1 -1
- package/dist/assets/{health-boxes-BphMeSJj.js → health-boxes-BZjIqiiG.js} +1 -1
- package/dist/assets/index-CHbe1sy1.css +1 -0
- package/dist/assets/{index-gmPaoLN-.js → index-Dj8q65se.js} +2 -2
- package/dist/assets/{inline-note-fields-BvQwmMAv.js → inline-note-fields-DpmCMAJf.js} +1 -1
- package/dist/assets/{insight-flow-dialog-H_eaOmst.js → insight-flow-dialog-DNIe0sts.js} +1 -1
- package/dist/assets/{insights-page-DINYe3cB.js → insights-page-D_N_MWGu.js} +1 -1
- package/dist/assets/{kanban-boxes-oACOTDYG.js → kanban-boxes-DTDG5UEJ.js} +1 -1
- package/dist/assets/{kanban-page-BGLXH91f.js → kanban-page-DEvIY5IW.js} +1 -1
- package/dist/assets/{knowledge-graph-page-VfMvw5jL.js → knowledge-graph-page-CvXSnnG5.js} +1 -1
- package/dist/assets/{life-force-page-DQPb6UL-.js → life-force-page-CgvUrqQb.js} +1 -1
- package/dist/assets/{life-force-workspace-BJ1aI3JE.js → life-force-workspace-BNeMbRHf.js} +1 -1
- package/dist/assets/{maps-CvEHVkBk.js → maps-Dk9tZqTA.js} +1 -1
- package/dist/assets/{metric-tile-CbEe19Gd.js → metric-tile-DAhX60rg.js} +1 -1
- package/dist/assets/{motion-BibSzp57.js → motion-DeJZhOSA.js} +1 -1
- package/dist/assets/{movement-boxes-dtDYhw5c.js → movement-boxes-BOqU18NH.js} +1 -1
- package/dist/assets/{movement-page-BhmwCHjs.js → movement-page-DCDeUynh.js} +1 -1
- package/dist/assets/{note-markdown-CG8u2d6p.js → note-markdown-Cxj84-0j.js} +1 -1
- package/dist/assets/{note-tags-input-D_conqDO.js → note-tags-input-CP0-EPpE.js} +1 -1
- package/dist/assets/{notes-boxes-BLKucFqW.js → notes-boxes-C7WPT7mf.js} +1 -1
- package/dist/assets/{notes-page-CafVxWjb.js → notes-page-Dll8PIks.js} +1 -1
- package/dist/assets/{open-in-graph-button-DFQ4r6SN.js → open-in-graph-button-BHl16hJP.js} +1 -1
- package/dist/assets/{orbit-map-DsEl3ori.js → orbit-map-De0qpMpY.js} +1 -1
- package/dist/assets/{overview-page-BffcX-pM.js → overview-page-C1RX7dcq.js} +1 -1
- package/dist/assets/{page-hero-U603l9rQ.js → page-hero-DYmFM6-q.js} +1 -1
- package/dist/assets/pill-cluster-ClkmFVFT.js +1 -0
- package/dist/assets/{preference-entity-handoff-button-cPrTpHsV.js → preference-entity-handoff-button-1XXtBsUF.js} +1 -1
- package/dist/assets/{preferences-page-DQjFIOmt.js → preferences-page-OwfPIQwe.js} +1 -1
- package/dist/assets/{project-collections-B9OGHGqm.js → project-collections-DfmkBk9d.js} +1 -1
- package/dist/assets/{project-detail-page-r1Sw2kcO.js → project-detail-page-BC_MNaca.js} +1 -1
- package/dist/assets/{project-dialog-B2_PcXAf.js → project-dialog-BuZdXECa.js} +1 -1
- package/dist/assets/{project-management-hierarchy-page-qLNG8hsh.js → project-management-hierarchy-page-AhEHe60K.js} +1 -1
- package/dist/assets/{project-management-section-nav-DFUlmMEB.js → project-management-section-nav-CnaseOqL.js} +1 -1
- package/dist/assets/{projects-boxes-BA7_XaqX.js → projects-boxes-D0zM8PfY.js} +1 -1
- package/dist/assets/{projects-page-B6ggXWFw.js → projects-page-ltrWfLrA.js} +1 -1
- package/dist/assets/{psyche-behaviors-page-ByWpXlLq.js → psyche-behaviors-page-CPurgDg6.js} +1 -1
- package/dist/assets/{psyche-flashcards-page-B9nSc0mk.js → psyche-flashcards-page-DnUSe-bb.js} +1 -1
- package/dist/assets/{psyche-goal-map-page-BQU7qI88.js → psyche-goal-map-page-uWocO7kZ.js} +1 -1
- package/dist/assets/{psyche-graph-DCeP7r2b.js → psyche-graph-BDszV3UN.js} +1 -1
- package/dist/assets/{psyche-metrics-page-DD2lOP-J.js → psyche-metrics-page-CIJLJTPy.js} +1 -1
- package/dist/assets/{psyche-mode-guide-page-DbtZgnjr.js → psyche-mode-guide-page-uC8L4WvH.js} +1 -1
- package/dist/assets/{psyche-modes-page-3zFJWFQf.js → psyche-modes-page-CtBeRA_3.js} +1 -1
- package/dist/assets/{psyche-page-D5vXYkfB.js → psyche-page-Ds3QDsin.js} +1 -1
- package/dist/assets/{psyche-patterns-page-BneAAeKS.js → psyche-patterns-page-Cvq5WshW.js} +1 -1
- package/dist/assets/{psyche-questionnaire-builder-page-BH1la5C9.js → psyche-questionnaire-builder-page-Cg5Upe6z.js} +1 -1
- package/dist/assets/{psyche-questionnaire-detail-page-DYav634P.js → psyche-questionnaire-detail-page-D4jEnNoh.js} +1 -1
- package/dist/assets/{psyche-questionnaire-run-detail-page-9VaijhJm.js → psyche-questionnaire-run-detail-page-CWoZEY31.js} +1 -1
- package/dist/assets/{psyche-questionnaire-run-page-e1T6k_dS.js → psyche-questionnaire-run-page-Yg_VG2vq.js} +1 -1
- package/dist/assets/{psyche-questionnaires-page-Dyv367z9.js → psyche-questionnaires-page-BqeOJRj7.js} +1 -1
- package/dist/assets/{psyche-report-detail-page-hqxHIXw2.js → psyche-report-detail-page-BtcMQ7mk.js} +1 -1
- package/dist/assets/{psyche-reports-page-DhIfcGbt.js → psyche-reports-page-tagvW0To.js} +1 -1
- package/dist/assets/{psyche-schemas-Cg51Ztxz.js → psyche-schemas-CvRSkI_u.js} +1 -1
- package/dist/assets/{psyche-schemas-beliefs-page-Dgb5o9vx.js → psyche-schemas-beliefs-page-4NL3415v.js} +1 -1
- package/dist/assets/{psyche-screen-time-page-D6MnJGNa.js → psyche-screen-time-page-Bc5AwZHQ.js} +1 -1
- package/dist/assets/{psyche-self-observation-page-C1Vyezbv.js → psyche-self-observation-page-CUrUYbQ_.js} +1 -1
- package/dist/assets/{psyche-values-page-B_JWVw1Q.js → psyche-values-page-BshT2sXE.js} +1 -1
- package/dist/assets/{question-flow-dialog-yMYVk998.js → question-flow-dialog-CPyXCqA-.js} +1 -1
- package/dist/assets/{report-chain-fields-D4NM9a6I.js → report-chain-fields-C0UMLpze.js} +1 -1
- package/dist/assets/{rewards-page-B5-bcL4R.js → rewards-page-D9BzsNPW.js} +1 -1
- package/dist/assets/{scheduling-rules-editor-De72IUax.js → scheduling-rules-editor-DiA6KkQ4.js} +1 -1
- package/dist/assets/{schema-badge-jX28kUa6.js → schema-badge-DURw2eYH.js} +1 -1
- package/dist/assets/{schemas-BlFy-uPR.js → schemas-D_z2C8l1.js} +1 -1
- package/dist/assets/{select-menu-BXv1rsVc.js → select-menu-BUB8__Nx.js} +1 -1
- package/dist/assets/{settings-agents-page-DN_np10S.js → settings-agents-page-Kk98Whcf.js} +1 -1
- package/dist/assets/{settings-bin-page-BM5BpK_i.js → settings-bin-page-BnJ-mgy2.js} +1 -1
- package/dist/assets/{settings-calendar-page-Cg0gSSFs.js → settings-calendar-page-CdhlUnUW.js} +3 -3
- package/dist/assets/{settings-data-page-Dwmp2rLy.js → settings-data-page-BvvuZNbb.js} +1 -1
- package/dist/assets/{settings-logs-page-DQNM21Re.js → settings-logs-page-CrzkXxtZ.js} +1 -1
- package/dist/assets/{settings-mobile-page-DQdiRa-a.js → settings-mobile-page-Dl582NK6.js} +1 -1
- package/dist/assets/{settings-models-page-CAEPpuHF.js → settings-models-page-COoBw28S.js} +1 -1
- package/dist/assets/{settings-page-Cl2KiCFg.js → settings-page-DqnlOCgo.js} +1 -1
- package/dist/assets/{settings-rewards-page-DoIUumhe.js → settings-rewards-page-Cw5QSTjy.js} +1 -1
- package/dist/assets/{settings-section-nav-D_N87IG0.js → settings-section-nav-C1NcWveT.js} +1 -1
- package/dist/assets/{settings-users-page-CPesR62N.js → settings-users-page-0opvepcM.js} +1 -1
- package/dist/assets/{settings-wiki-page-BxMQM5Vi.js → settings-wiki-page-CkpnUkiZ.js} +1 -1
- package/dist/assets/{sleep-page-DUYmQKrg.js → sleep-page-DrS1zs3B.js} +1 -1
- package/dist/assets/{sports-page-Bzi5TF9T.js → sports-page-EVnB_zjB.js} +1 -1
- package/dist/assets/{state-BFyKSULP.js → state-DWw8Jay_.js} +1 -1
- package/dist/assets/{strategies-page-C-T2MZx4.js → strategies-page-COhyv_SH.js} +1 -1
- package/dist/assets/{strategy-detail-page-3tYuSZu-.js → strategy-detail-page-BaCVkvIu.js} +1 -1
- package/dist/assets/{strategy-dialog-BWm4slo4.js → strategy-dialog-DvlPo9WV.js} +1 -1
- package/dist/assets/{surface-BJObZeRw.js → surface-Dg5fauKP.js} +1 -1
- package/dist/assets/{table-CTLroJKN.js → table-CWVROEBP.js} +1 -1
- package/dist/assets/{task-detail-page-ZZOXSpSF.js → task-detail-page-3IeMYIXl.js} +1 -1
- package/dist/assets/{task-dialog-2wy0xI7f.js → task-dialog-B7ZT4KE5.js} +1 -1
- package/dist/assets/{timebox-planning-dialog-C6h0Hp71.js → timebox-planning-dialog-DoZzpEBp.js} +1 -1
- package/dist/assets/{today-boxes-B_TdgSDz.js → today-boxes-BbUNpb16.js} +1 -1
- package/dist/assets/today-page-adKXN2g1.js +1 -0
- package/dist/assets/{training-load-page-B78e1-o-.js → training-load-page-DTYbu9f0.js} +1 -1
- package/dist/assets/{ui-uo_bNP7c.js → ui-CdEDMtXF.js} +1 -1
- package/dist/assets/{use-anchored-overlay-position-BSxFX6Hi.js → use-anchored-overlay-position-Cracjgo6.js} +1 -1
- package/dist/assets/{use-psyche-focus-target-1GLkhYiv.js → use-psyche-focus-target-DvRgu-94.js} +1 -1
- package/dist/assets/{user-badge-C4eZu1e_.js → user-badge-B8hYK6NU.js} +1 -1
- package/dist/assets/{user-select-field-CmKwcbZt.js → user-select-field-akGHK-2t.js} +1 -1
- package/dist/assets/{utility-widgets-B06wQFrd.js → utility-widgets-D4KsKxLT.js} +2 -2
- package/dist/assets/{vendor-B7FKSwHK.js → vendor-y_uz1Wft.js} +1 -1
- package/dist/assets/{vitals-page-BC7QFsm2.js → vitals-page-Cjcxh-kO.js} +1 -1
- package/dist/assets/{weekly-review-page-BjNsNoWj.js → weekly-review-page-CR57efzH.js} +1 -1
- package/dist/assets/{weight-loss-page-BOahGY9r.js → weight-loss-page-Bk7YkB7b.js} +1 -1
- package/dist/assets/{wiki-article-markdown-DO47HnZf.js → wiki-article-markdown-um6gpmGQ.js} +1 -1
- package/dist/assets/{wiki-editor-page-OWRUHl4O.js → wiki-editor-page-DdP5hvjZ.js} +3 -3
- package/dist/assets/{wiki-ingest-history-page-CuHpg2lZ.js → wiki-ingest-history-page-DSTndduq.js} +1 -1
- package/dist/assets/{wiki-ingest-modal-EZ3kX-vA.js → wiki-ingest-modal-PNW3CJ-o.js} +1 -1
- package/dist/assets/{wiki-page-BPV3HIgu.js → wiki-page-CsJlPyQ6.js} +1 -1
- package/dist/assets/{workbench-flow-page-C53KueEz.js → workbench-flow-page-DFtIKgNe.js} +1 -1
- package/dist/assets/{workbench-page-DJ7nT2JQ.js → workbench-page-DEpKjMEv.js} +1 -1
- package/dist/assets/{workout-detail-page-Dhyu0q7o.js → workout-detail-page-BwfEhxA_.js} +2 -2
- package/dist/index.html +8 -8
- package/dist/server/apps/api/migrations/073_artifact_entity_links_repair.sql +24 -0
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/server/migrations/073_artifact_entity_links_repair.sql +24 -0
- package/skills/forge-openclaw/entity_conversation_playbooks.md +9 -6
- package/dist/assets/artifacts-page-BgyFVIVM.js +0 -2
- package/dist/assets/index-CSd8ylsy.css +0 -1
- package/dist/assets/pill-cluster-BYVFNppV.js +0 -1
- package/dist/assets/today-page-Dipns9tl.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{j as a,bY as Ve,aG as ya,b8 as ja,ck as Ya,dA as Ja,cF as Xa,bC as Oe,cq as et,cJ as ka,cc as at,c7 as wa,dB as tt,dC as nt,br as Na,dD as rt,dE as st,r as M,bW as it,d9 as ot,dg as lt,dc as ct,aV as dt,dF as ut,cz as gt,bu as oa,dG as mt,bs as ht,be as pt}from"./vendor-B7FKSwHK.js";import{j as xt,i as ft,k as Z}from"./state-BFyKSULP.js";import{P as bt}from"./page-hero-U603l9rQ.js";import{C as U,ad as de,B as G,I as C,c as Ue,j as E,T as Ae,d as vt,L as yt,e as jt,eh as la,ei as kt,ej as wt,ek as Nt,el as ca,em as Ct,en as Mt,eo as Ft,ep as Kt,eq as St,er as Gt,es as At}from"./index-gmPaoLN-.js";import{S as L,a as F}from"./surface-BJObZeRw.js";import{Q as De,F as y,a as da}from"./question-flow-dialog-yMYVk998.js";import{g as Dt,f as Se}from"./date-keys-BnZV4PNO.js";import"./motion-BibSzp57.js";import"./ui-uo_bNP7c.js";import"./board-DprRipIG.js";import"./forms-ByKjodjN.js";function _t({view:e,onOpenPlan:t,onOpenFoodSearch:n,onOpenCustomFood:r,onOpenChatGptFood:s,onOpenCheckin:l,onOpenHistory:g}){const c=[{label:"Plan target",value:`${e.target.calorieTarget.toFixed(0)} kcal`},{label:"Protein",value:`${e.target.proteinGramsTarget.toFixed(0)}g`},{label:"Fiber",value:`${e.target.fiberGramsTarget.toFixed(0)}g`}];return a.jsxs(U,{className:"grid gap-4 border-[var(--ui-border-subtle)] bg-[var(--ui-surface-section)] p-5",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",children:[a.jsx("span",{children:"Control center"}),a.jsx(de,{label:"Explain weight-loss controls",content:"Use these actions to change the nutrition plan, log food, or record body signals. The day budget cards above use today's active-calorie source; the plan target here is the baseline target before today's active adjustment."})]}),a.jsx("h2",{className:"mt-1 text-xl font-semibold leading-tight text-[var(--ui-ink-strong)]",children:e.target.bodyGoal?`Goal: ${e.target.bodyGoal}`:"Set the body objective"}),a.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:"Adjust the baseline plan, log food with exact quantities, or record body signals from guided flows."})]}),a.jsx("div",{className:"grid gap-2 sm:grid-cols-3 xl:grid-cols-1 min-[1360px]:grid-cols-3",children:c.map(i=>a.jsxs("div",{className:"min-w-0 rounded-[8px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] px-3 py-2",children:[a.jsx("div",{className:"text-[10px] uppercase tracking-[0.14em] text-[var(--ui-ink-faint)]",children:i.label}),a.jsx("div",{className:"mt-1 truncate text-sm font-semibold text-[var(--ui-ink-strong)]",children:i.value})]},i.label))}),a.jsxs("div",{className:"grid min-w-0 grid-cols-2 gap-2",children:[a.jsxs(G,{type:"button",onClick:r,children:[a.jsx(Ve,{className:"size-4"}),"Custom food"]}),a.jsxs(G,{type:"button",variant:"secondary",onClick:s,children:[a.jsx(ya,{className:"size-4"}),"Ask ChatGPT"]}),a.jsxs(G,{type:"button",variant:"secondary",onClick:n,children:[a.jsx(ja,{className:"size-4"}),"Search food"]}),a.jsxs(G,{type:"button",variant:"secondary",onClick:t,children:[a.jsx(Ya,{className:"size-4"}),"Plan settings"]}),a.jsxs(G,{type:"button",variant:"secondary",onClick:l,children:[a.jsx(Ja,{className:"size-4"}),"Add measure"]}),a.jsxs(G,{type:"button",variant:"secondary",onClick:g,children:[a.jsx(Xa,{className:"size-4"}),"Food history"]})]})]})}function _(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ce(e){return typeof e=="string"&&e.trim()?e:null}function o(e,t=0){const n=_(e);return n===null?"n/a":n.toFixed(t)}function q(e,t=0){const n=_(e);return n===null?"n/a":`${n>0?"+":""}${n.toFixed(t)}`}function Me(e){const t=_(e);return t===null?"n/a":`${t.toFixed(1)}/10`}function Et(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&!Array.isArray(t)):[]}function $t(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 Tt(e){switch(e){case"user_override":return"Using your manual value for today.";case"today_healthkit_active_energy":return"Using same-day HealthKit active energy instead of the 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 It(e){return`${e>=0?"+":""}${e.toFixed(0)} kcal`}function Lt(e){return e.trim()===""?"0":e}function Pt({view:e,draftValue:t,pending:n,error:r,onDraftChange:s,onSave:l,onReset:g}){const c=e.energyModel,i=e.todayLedger,u=c.todayActiveOverride,f=c.todayActiveCaloriesSource,K=`${i.plannedTargetCalories.toFixed(0)} ${It(c.todayTargetAdjustmentKcal)} = ${i.targetCalories.toFixed(0)} kcal`;return a.jsxs(U,{className:"grid min-w-0 gap-3 border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-4",children:[a.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-1 text-[11px] uppercase tracking-[0.14em] text-[var(--ui-ink-faint)]",children:["Active kcal",a.jsx(de,{label:"Explain active calories",content:`Selected-day target = baseline food target plus the day-specific active adjustment. ${K}. Automatic same-day activity can only add ${Math.round(c.activityEatBackFraction*100)}% of the positive surplus above the baseline day. A manual edit overrides this date 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:[c.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(Oe,{className:"size-4"})})]}),a.jsxs("div",{className:"grid gap-1 text-xs leading-5 text-[var(--ui-ink-soft)]",children:[a.jsx("div",{className:"break-words font-medium text-[var(--ui-ink-medium)]",children:Tt(f)}),a.jsxs("div",{children:["Baseline ",c.baselineActiveCaloriesKcal.toFixed(0)," kcal"," · ","observed"," ",c.todayObservedActiveCaloriesKcal!=null?`${c.todayObservedActiveCaloriesKcal.toFixed(0)} kcal`:"n/a"]}),a.jsxs("div",{className:"break-words",children:["Source: ",$t(f)]})]}),a.jsxs("div",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)_auto] gap-2",children:[a.jsx(C,{inputMode:"decimal",value:t,onChange:w=>s(Lt(w.target.value)),"aria-label":"Selected day active calories",className:"py-2.5"}),a.jsxs(G,{type:"button",onClick:l,pending:n,pendingLabel:"Applying",children:[a.jsx(et,{className:"size-4"}),"Apply"]})]}),a.jsxs(G,{type:"button",variant:"secondary",onClick:g,disabled:!u||n,children:[a.jsx(ka,{className:"size-4"}),"Use evidence"]}),r?a.jsx("div",{className:"rounded-[8px] border border-[var(--danger)]/20 bg-[var(--ui-danger-soft)] px-3 py-2 text-xs leading-5 text-[color-mix(in_srgb,var(--danger)_76%,var(--ui-ink-strong)_24%)]",children:r}):null]})}const Rt={default:"bg-[color-mix(in_srgb,var(--primary)_14%,transparent)] text-[var(--primary)]",green:"bg-[var(--ui-success-soft)] text-[color-mix(in_srgb,var(--success)_78%,var(--ui-ink-strong)_22%)]",amber:"bg-[var(--ui-warning-soft)] text-[color-mix(in_srgb,var(--warning)_76%,var(--ui-ink-strong)_24%)]",rose:"bg-[var(--ui-danger-soft)] text-[color-mix(in_srgb,var(--danger)_76%,var(--ui-ink-strong)_24%)]",cyan:"bg-[var(--ui-info-soft)] text-[color-mix(in_srgb,var(--info)_78%,var(--ui-ink-strong)_22%)]"};function ee({label:e,value:t,detail:n,icon:r,tone:s="default",help:l,helpMaxWidthPx:g}){return a.jsxs(U,{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:Ue("rounded-2xl p-2.5",Rt[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}),l?a.jsx(de,{content:l,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 Wt({meal:e,onLogAgain:t,onEdit:n,onDelete:r,pending:s=!1,hideMealLabel:l=!1}){const g=e.items[0]??null,c=Math.max(0,e.items.length-1),i=g?`${g.name}${c>0?` + ${c} more`:""}`:l?"Food entry":e.mealLabel??"Meal",u=e.items.slice(0,3).map(f=>{const K=Number.isFinite(f.quantity)&&f.quantity>0?Number.isInteger(f.quantity)?String(f.quantity):f.quantity.toFixed(2).replace(/\.?0+$/,""):null,w=f.unit??"serving",j=f.grams!=null?`${f.grams.toFixed(0)}g`:null;return[K,w,j?`(${j})`:null].filter(Boolean).join(" ")}).filter(Boolean).join(" · ");return a.jsxs(L,{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:i}),a.jsx("div",{className:"mt-1 text-xs leading-5 text-[var(--ui-ink-faint)]",children:u||e.notes||"No quantity recorded"})]}),a.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[e.mealLabel&&!l?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(G,{type:"button",size:"sm",variant:"secondary",onClick:()=>n(e),children:[a.jsx(at,{className:"size-4"}),"Edit"]}):null,r?a.jsxs(G,{type:"button",size:"sm",variant:"ghost",pending:s,onClick:()=>r(e),children:[a.jsx(wa,{className:"size-4"}),"Delete"]}):null,t?a.jsxs(G,{type:"button",size:"sm",variant:"ghost",pending:s,onClick:()=>t(e),children:[a.jsx(ka,{className:"size-4"}),"Log again"]}):null]})]})}function Ze({children:e}){return a.jsx(L,{className:"border-dashed border-[var(--ui-border-strong)] p-5 text-sm text-[var(--ui-ink-soft)]",children:e})}function fe(e){return`${e.toFixed(0)} kcal`}function Bt(e){return e>=0?"Kcal left":"Over target"}function Ht(e){return e>=0?fe(e):fe(Math.abs(e))}function zt(e){var n;const t=(n=e.mealLabel)==null?void 0:n.trim();return t||"No meal marker"}function qt(e){const t=[],n=new Map;for(const r of e){const s=zt(r);let l=n.get(s);l||(l={label:s,calories:0,meals:[]},t.push(l),n.set(s,l)),l.meals.push(r),l.calories+=r.totals.calories}return t}function Ot({ledger:e,remainingCalories:t,intakePercent:n,logSavedPending:r,onLogAgain:s,onEditMeal:l,onDeleteMeal:g}){const c=e.totals,i=qt(e.meals);return a.jsxs(U,{className:"grid gap-5 border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-5",children:[a.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",children:"Food log"}),a.jsxs("h2",{className:"mt-1 flex items-center gap-2 text-xl font-semibold text-[var(--ui-ink-strong)]",children:[a.jsx("span",{children:"Calories, macros, and meal evidence"}),a.jsx(de,{label:"Explain food log",content:"The food log is the selected day's editable record of what was eaten. Meal markers are optional; they group entries as breakfast, lunch, snack, dinner, or any personal label."})]})]}),a.jsxs(E,{tone:"meta",children:[e.meals.length," logs"]})]}),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"}),a.jsx("div",{className:"mt-1 text-2xl font-semibold text-[var(--ui-ink-strong)]",children:fe(c.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"}),a.jsx("div",{className:"mt-1 text-2xl font-semibold text-[var(--ui-ink-strong)]",children:fe(e.targetCalories)})]}),a.jsxs("div",{className:Ue("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:Bt(t)}),a.jsx("div",{className:"mt-1 text-2xl font-semibold text-[var(--ui-ink-strong)]",children:Ht(t)})]})]}),a.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-[var(--ui-surface-2)]",children:a.jsx("div",{className:Ue("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:[c.carbohydrateGrams.toFixed(0),"g carbs"]}),a.jsxs("span",{children:[c.fatGrams.toFixed(0),"g fat"]}),a.jsxs("span",{children:[c.fiberGrams.toFixed(0),"g fiber"]}),a.jsxs("span",{children:[e.unconfirmedCount," unconfirmed"]})]})]}),a.jsx("div",{className:"grid gap-3",children:e.meals.length>0?i.map(u=>a.jsxs("section",{className:"grid gap-2 rounded-[8px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] p-3",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[a.jsx("div",{className:"text-sm font-semibold text-[var(--ui-ink-strong)]",children:u.label}),a.jsxs("div",{className:"text-xs text-[var(--ui-ink-soft)]",children:[u.meals.length," log",u.meals.length===1?"":"s"," ","· ",fe(u.calories)]})]}),a.jsx("div",{className:"grid gap-2",children:u.meals.map(f=>a.jsx(Wt,{meal:f,pending:r,hideMealLabel:!0,onLogAgain:s,onEdit:l,onDelete:g},f.id))})]},u.label)):a.jsx(Ze,{children:"No food logged for this day yet."})})]})}function Ut({hypotheses:e}){return a.jsxs(U,{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(L,{children:[a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsx(E,{tone:"signal",children:ce(t.metric)??"pattern"}),a.jsx("span",{className:"text-xs text-[var(--ui-ink-faint)]",children:o(t.confidence,2)})]}),a.jsx("div",{className:"mt-3 text-sm font-medium text-[var(--ui-ink-strong)]",children:ce(t.label)??"Candidate pattern"}),a.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:ce(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(Ze,{children:"Log meals plus energy, gut, and look check-ins for a few days to generate pattern candidates."})})})]})}function Qt({experiments:e}){return a.jsxs(U,{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(tt,{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(L,{children:[a.jsx("div",{className:"text-sm font-medium text-[var(--ui-ink-strong)]",children:ce(t.title)??"Nutrition experiment"}),a.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:ce(t.hypothesis)??ce(t.intervention)??"No hypothesis recorded."})]},String(t.id??n))),e.length===0?a.jsx(Ze,{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 Vt({view:e}){const t=e.dataQuality,n=e.todayLedger;return a.jsxs(U,{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(Zt,{label:"Source confidence",value:t.sourceConfidence,children:"Food parsing stays candidate-based until accepted; wearable burn is treated as a trend input."}),a.jsxs(L,{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(L,{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 Zt({label:e,value:t,children:n}){return a.jsxs(L,{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 Y={id:"hall_niddk_linearized_adult_12w",label:"Hall/NIDDK linearized adult model",defaultPlanningHorizonDays:84,steadyStateKcalPerKgPerDay:10/.45359237,timeConstantDays:365,staticEnergyDensityKcalPerKg:7700};function He(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:null}function Ca(e={}){const t=He(e.planningHorizonDays)??Y.defaultPlanningHorizonDays,n=He(e.timeConstantDays)??Y.timeConstantDays,r=He(e.steadyStateKcalPerKgPerDay)??Y.steadyStateKcalPerKgPerDay,s=1-Math.exp(-t/n);return{planningHorizonDays:t,timeConstantDays:n,steadyStateKcalPerKgPerDay:r,responseFraction:s}}function Ma(e,t={}){if(typeof e!="number"||!Number.isFinite(e))return null;if(e===0)return 0;const n=Ca(t);return n.responseFraction<=0?null:e*(n.planningHorizonDays/7)*n.steadyStateKcalPerKgPerDay/n.responseFraction}function Yt(e,t={}){if(typeof e!="number"||!Number.isFinite(e))return null;if(e===0)return 0;const n=Ca(t);return e/n.steadyStateKcalPerKgPerDay*n.responseFraction/(n.planningHorizonDays/7)}function Jt(e){return typeof e!="number"||!Number.isFinite(e)?null:e*Y.staticEnergyDensityKcalPerKg/7}function z(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(de,{label:t,title:"Weight Loss Formulas",maxWidthPx:520,panelClassName:"text-xs leading-5",content:a.jsxs("div",{className:"grid gap-3",children:[a.jsx("p",{children:"Forge keeps activity independent from the goal. The goal only adds a deficit, surplus, or zero adjustment to 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:[z("Mifflin-St Jeor resting baseline",`10 x weight kg + 6.25 x height cm - 5 x age ${r}`,`Current formula value: ${o(e==null?void 0:e.bmrKcal)} kcal/day.`),z("Resting calories","Mifflin-St Jeor formula baseline; HealthKit basal is complete-day evidence only",`Using: ${o(e==null?void 0:e.restingKcal)} kcal/day${e!=null&&e.restingSource?` (${e.restingSource})`:""}.`),z("Maintenance calories","resting calories + active calories",`${o(e==null?void 0:e.restingKcal)} + ${o(e==null?void 0:e.activeKcal)} = ${o(e==null?void 0:e.maintenanceKcal)} kcal/day.`),z("Objective adjustment","Hall/NIDDK linearized adult model, inverted over the planning horizon",`Weekly rate ${q(e==null?void 0:e.weeklyRateKg,2)} kg/week gives ${q(e==null?void 0:e.dailyAdjustmentKcal)} kcal/day${e!=null&&e.rateModel?` with ${e.rateModel}`:""}${e!=null&&e.rateModelHorizonDays?` over ${e.rateModelHorizonDays} days`:""}.`),z("Daily calorie target","max(sex floor, maintenance + objective adjustment)",`Floor ${o(e==null?void 0:e.calorieFloor)} kcal; target ${o(e==null?void 0:e.calorieTarget)} kcal/day.`),z("Protein target",`min(reference weight x ${s}, 45% of kcal / 4)`,`Reference ${o(e==null?void 0:e.proteinReferenceWeightKg,1)} kg; target ${o(e==null?void 0:e.proteinGrams)} g/day.`),z("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 ${o(e==null?void 0:e.fatGrams)} g/day.`),z("Carbohydrate target","(calorie target - protein g x 4 - fat g x 9) / 4",`Target ${o(e==null?void 0:e.carbohydrateGrams)} g/day. The 130g DRI is shown as reference, not forced if it breaks calories.`),z("Fiber target","14g per 1000 kcal; adult sex/age AI shown as reference",`Target ${o(e==null?void 0:e.fiberGrams)} g/day; energy-adjusted ${o(e==null?void 0:e.fiberEnergyAdjustedGrams)} g/day; adult AI reference ${o(e==null?void 0:e.fiberDriGrams)} g/day.`),z("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 Ka(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 xe(e,t){const n=typeof e=="string"?Number(e):_(e);return typeof n=="number"&&Number.isFinite(n)?n:t}function Xt(e){return Ka(e.target.notes,"sex")==="female"?"female":"male"}function en(e){return xe(Ka(e.target.notes,"age_years"),35)}function p(e,t,n,r,s,l){return{id:e,label:t,target:typeof n=="number"?Qe(n):n,unit:r,note:s,source:l}}function Qe(e){return Number.isFinite(e)?Math.abs(e)>=100?e.toFixed(0):e.toFixed(1).replace(/\.0$/,""):"n/a"}function oe(e,t){return`${Qe(e)}-${Qe(t)}`}function an(e,t,n,r){const s=Math.round(n/1e3*14);return r>0?r:s}function tn({calorieTarget:e,currentWeightKg:t,protein:n,savedFat:r}){const s=Math.max(0,(e-n*4)/9),l=Math.max(0,Math.min(s,e*.35/9,Math.max(t*.6,e*.25/9))),g=r??l;return{carbs:Math.max(0,(e-n*4-g*9)/4),fat:g}}function nn(e,t){return e==="male"?t>=51?14:17:t>=51?11:12}function rn(e,t){const n=t>70,r=t>=51;return[p("vitamin_a","Vitamin A",e==="male"?900:700,"ug RAE","Retinol activity equivalent target.","NASEM DRI"),p("vitamin_c","Vitamin C",e==="male"?90:75,"mg","Adult RDA.","NASEM DRI"),p("vitamin_d","Vitamin D",n?20:15,"ug","Assumes limited sun exposure; older adults need more.","NASEM DRI"),p("vitamin_e","Vitamin E",15,"mg alpha-tocopherol","Adult RDA.","NASEM DRI"),p("vitamin_k","Vitamin K",e==="male"?120:90,"ug","Adult AI.","NASEM DRI"),p("thiamin_b1","Thiamin B1",e==="male"?1.2:1.1,"mg","Adult RDA.","NASEM DRI"),p("riboflavin_b2","Riboflavin B2",e==="male"?1.3:1.1,"mg","Adult RDA.","NASEM DRI"),p("niacin_b3","Niacin B3",e==="male"?16:14,"mg NE","Adult RDA.","NASEM DRI"),p("vitamin_b6","Vitamin B6",r?e==="male"?1.7:1.5:1.3,"mg","RDA rises after 50.","NASEM DRI"),p("folate","Folate",400,"ug DFE","Adult RDA.","NASEM DRI"),p("vitamin_b12","Vitamin B12",2.4,"ug","Adult RDA.","NASEM DRI"),p("pantothenic_acid","Pantothenic acid",5,"mg","Adult AI.","NASEM DRI"),p("biotin","Biotin",30,"ug","Adult AI.","NASEM DRI"),p("choline","Choline",e==="male"?550:425,"mg","Adult AI.","NASEM DRI")]}function sn(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,l=t>=71?1800:t>=51?2e3:2300;return[p("calcium","Calcium",n,"mg","Bone and muscle target; higher for older adults and women 51+.","NASEM DRI"),p("iron","Iron",e==="female"&&t<=50?18:8,"mg","Menstruating-age female target is higher.","NASEM DRI"),p("magnesium","Magnesium",r,"mg","Adult RDA.","NASEM DRI"),p("phosphorus","Phosphorus",700,"mg","Adult RDA.","NASEM DRI"),p("zinc","Zinc",e==="male"?11:8,"mg","Adult RDA.","NASEM DRI"),p("iodine","Iodine",150,"ug","Adult RDA.","NASEM DRI"),p("selenium","Selenium",55,"ug","Adult RDA.","NASEM DRI"),p("copper","Copper",.9,"mg","Adult RDA.","NASEM DRI"),p("manganese","Manganese",e==="male"?2.3:1.8,"mg","Adult AI.","NASEM DRI"),p("chromium","Chromium",s,"ug","Adult AI.","NASEM DRI"),p("molybdenum","Molybdenum",45,"ug","Adult RDA.","NASEM DRI"),p("fluoride","Fluoride",e==="male"?4:3,"mg","Adult AI.","NASEM DRI"),p("chloride","Chloride",l,"mg","Adult AI.","NASEM DRI"),p("potassium","Potassium",e==="male"?3400:2600,"mg","Current adult AI for non-pregnant adults.","NASEM DRI"),p("sodium_limit","Sodium ceiling",2300,"mg max","Default daily ceiling unless medically individualized.","U.S. Dietary Guidelines")]}function on(e){const t=Xt(e),n=en(e),r=xe(e.weightTrend.latestWeightKg,80),s=Math.max(1,xe(e.target.calorieTarget,2200)),l=xe(e.target.proteinGramsTarget,r*1.8),{carbs:g,fat:c}=tn({calorieTarget:s,currentWeightKg:r,protein:l,savedFat:_(e.target.fatGramsTarget)}),i=an(t,n,s,xe(e.target.fiberGramsTarget,0)),u=_(e.energyModel.activeBurnKcal)??_(e.energyModel.activeEnergyCalories)??null,f=_(e.energyModel.movementCaloriesKcal),K=_(e.energyModel.restingEnergyCalories);return Sa({sex:t,ageYears:n,currentWeightKg:r,calorieTarget:s,proteinGramsTarget:l,carbohydrateGramsTarget:g,fatGramsTarget:c,fiberGramsTarget:i,activeBurnKcal:u,movementCaloriesKcal:f,restingEnergyKcal:K})}function Sa(e){const{sex:t,ageYears:n,currentWeightKg:r,calorieTarget:s,proteinGramsTarget:l,carbohydrateGramsTarget:g,fatGramsTarget:c,fiberGramsTarget:i,activeBurnKcal:u,movementCaloriesKcal:f,restingEnergyKcal:K}=e,w=u!=null?Math.min(4,Math.max(.1,u/500)):null,j=w!=null?w*.4:null,h=w!=null?w*.8:null,b=j!=null?j*500:null,k=h!=null?h*1e3:null,T=j!=null?j*78:null,P=h!=null?h*312:null,R=u!=null?Yt(u):null;return{profile:{sex:t,ageYears:n,currentWeightKg:r,calorieTarget:s,activeBurnKcal:u,movementCaloriesKcal:f,restingEnergyKcal:K},macros:[p("calories","Calories",s,"kcal","Plan target from BMR, active burn, and chosen weekly rate.","Forge plan"),p("protein","Protein",l,"g","Higher than the population RDA to preserve lean mass during weight change.","ISSN + Forge plan"),p("carbohydrate","Carbohydrate",g,"g","Remaining fuel after protein and fat. It may sit below the 130g/day adult DRI reference when needed to preserve the calorie target.","NASEM DRI + Forge plan"),p("fat","Total fat",c,"g","Uses the saved plan fat target when present; generated defaults aim for a practical floor around 0.6g/kg or 20-35% of calories when possible.","NASEM AMDR + Forge plan"),p("fiber","Fiber",i,"g","Uses 14g per 1000 kcal as the plan target; the sex/age adult AI remains a reference or stretch value when calories are low.","NASEM DRI"),p("saturated_fat","Saturated fat",s*.1/9,"g max","Keep below 10% of energy.","U.S. Dietary Guidelines"),p("added_sugar","Added sugar",s*.1/4,"g max","Keep below 10% of energy; lower is better when feasible.","U.S. Dietary Guidelines"),p("linoleic_acid","Linoleic acid",nn(t,n),"g","Essential n-6 fatty acid AI.","NASEM DRI"),p("ala","ALA omega-3",t==="male"?1.6:1.1,"g","Essential n-3 fatty acid AI.","NASEM DRI"),p("water","Total water",t==="male"?3.7:2.7,"L","All beverages and food water before extra training replacement.","NASEM DRI")],vitamins:rn(t,n),minerals:sn(t,n),sportLosses:[p("training_time","Estimated training time",w??"n/a","h/day","Derived from active burn at roughly 500 kcal/h.","Forge sport-loss model"),p("sweat_fluid","Expected sweat fluid",j!=null&&h!=null?oe(j,h):"n/a","L/day","Planning range uses 0.4-0.8 L/h; measure body mass change to calibrate.","ACSM"),p("sweat_sodium","Expected sweat sodium",b!=null&&k!=null?oe(b,k):"n/a","mg/day","Sodium varies widely; this uses a conservative range around common sweat sodium values.","ACSM + Sports Medicine review"),p("sweat_potassium","Expected sweat potassium",T!=null&&P!=null?oe(T,P):"n/a","mg/day","Potassium is usually much smaller than sodium but useful for long/hot sessions.","Sports Medicine review"),p("gross_sport_equivalent","Gross sport burn equivalent",R??"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:w,fluidLossLiters:j!=null&&h!=null?oe(j,h):"n/a",sodiumLossMg:b!=null&&k!=null?oe(b,k):"n/a",potassiumLossMg:T!=null&&P!=null?oe(T,P):"n/a",grossSportWeightEquivalentKgPerWeek:R}}}function ze({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 max-w-full gap-2 overflow-hidden rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-3",children:[a.jsxs("div",{className:"grid min-w-0 gap-2 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-start",children:[a.jsx("div",{className:"min-w-0 text-wrap text-sm font-semibold text-[var(--ui-ink)] [overflow-wrap:anywhere]",children:n.label}),a.jsxs("div",{className:"min-w-0 text-left text-sm font-semibold text-[var(--ui-ink)] sm:text-right",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 text-wrap text-xs leading-5 text-[var(--ui-ink-muted)] [overflow-wrap:anywhere]",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 min-w-0 max-w-full 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-[560px] table-fixed border-collapse text-left text-sm lg:min-w-0",children:[a.jsxs("colgroup",{children:[a.jsx("col",{className:"w-[24%]"}),a.jsx("col",{className:"w-[18%]"}),a.jsx("col",{className:t?"w-[58%]":"w-[40%]"}),t?null:a.jsx("col",{className:"w-[18%]"})]}),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:"min-w-0 px-4 py-3 font-medium text-[var(--ui-ink)] [overflow-wrap:anywhere]",children:n.label}),a.jsxs("td",{className:"min-w-0 px-4 py-3 text-[var(--ui-ink)] [overflow-wrap:anywhere]",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:"min-w-0 px-4 py-3 text-[var(--ui-ink-muted)] [overflow-wrap:anywhere]",children:n.note}),t?null:a.jsx("td",{className:"min-w-0 px-4 py-3",children:a.jsx(E,{tone:"meta",wrap:!0,children:n.source})})]},n.id))})]})})})]})}function pe({title:e,description:t,children:n}){return a.jsxs(L,{className:"min-w-0 max-w-full overflow-hidden",children:[a.jsxs("div",{className:"mb-4 min-w-0",children:[a.jsx("h3",{className:"text-wrap text-sm font-semibold text-[var(--ui-ink)] [overflow-wrap:anywhere]",children:e}),a.jsx("p",{className:"mt-1 text-wrap text-sm text-[var(--ui-ink-muted)] [overflow-wrap:anywhere]",children:t})]}),n]})}function ln({view:e}){const t=on(e),n=e.target.weeklyRateGoalKg??null,r=n!=null&&Number.isFinite(n)?Ma(n):null,s=t.profile.restingEnergyKcal,l=t.profile.activeBurnKcal,g=s!=null&&l!=null?s+l:null,c=e.target.bodyGoal??"maintain",i=c.includes("lose")?2:c.includes("gain")?1.8:1.6,u=j=>{var k;const h=(k=t.macros.find(T=>T.id===j))==null?void 0:k.target,b=Number(h);return Number.isFinite(b)?b:null},f=t.profile.sex==="male"?t.profile.ageYears>=51?30:38:t.profile.ageYears>=51?21:25,K=Math.round(t.profile.calorieTarget/1e3*14),w=t.sportSummary.grossSportWeightEquivalentKgPerWeek!=null?`${t.sportSummary.grossSportWeightEquivalentKgPerWeek.toFixed(2)} kg/week`:"n/a";return a.jsx("section",{className:"grid gap-4",children:a.jsxs(U,{className:"min-w-0 overflow-hidden p-4 sm:p-5",children:[a.jsxs("div",{className:"grid min-w-0 gap-3 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-start",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2 text-sm font-semibold text-[var(--ui-ink)]",children:[a.jsx(nt,{className:"size-4 shrink-0 text-[var(--ui-accent)]"}),a.jsx("span",{className:"min-w-0 text-wrap [overflow-wrap:anywhere]",children:"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:l,maintenanceKcal:g,weeklyRateKg:n,dailyAdjustmentKcal:r,rateModel:Y.label,rateModelHorizonDays:Y.defaultPlanningHorizonDays,calorieTarget:t.profile.calorieTarget,calorieFloor:t.profile.sex==="male"?1500:1200,proteinReferenceWeightKg:null,proteinFactor:i,proteinGrams:u("protein"),fatGrams:u("fat"),carbohydrateGrams:u("carbohydrate"),fiberGrams:u("fiber"),fiberEnergyAdjustedGrams:K,fiberDriGrams:f}})]}),a.jsx("p",{className:"mt-1 max-w-3xl text-wrap text-sm text-[var(--ui-ink-muted)] [overflow-wrap:anywhere]",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 min-w-0 flex-wrap gap-2 lg:justify-end",children:[a.jsxs(E,{tone:"signal",children:[t.profile.calorieTarget.toFixed(0)," kcal"]}),a.jsxs(E,{tone:"meta",wrap:!0,children:[t.profile.sex,", ",t.profile.ageYears.toFixed(0),"y"]})]})]}),a.jsxs("div",{className:"mt-5 grid min-w-0 gap-4 2xl:grid-cols-[minmax(0,1fr)_minmax(280px,0.58fr)]",children:[a.jsxs("div",{className:"grid min-w-0 gap-4",children:[a.jsx(pe,{title:"All macro targets",description:"Calories, protein, carbs, fat, fiber, sugar ceiling, saturated fat ceiling, essential fats, and water.",children:a.jsx(ze,{rows:t.macros,compact:!0})}),a.jsx(pe,{title:"Vitamins",description:"Adult daily vitamin targets from DRI values, adjusted for sex and age where the reference differs.",children:a.jsx(ze,{rows:t.vitamins})})]}),a.jsxs("div",{className:"grid min-w-0 content-start gap-4",children:[a.jsxs(pe,{title:"Expected sport losses",description:"Planning range from active burn. Calibrate with pre/post workout weight when possible.",children:[a.jsxs("div",{className:"grid min-w-0 gap-3 sm:grid-cols-2",children:[a.jsx(F,{label:"Active burn",value:t.profile.activeBurnKcal!=null?`${t.profile.activeBurnKcal.toFixed(0)} kcal`:"n/a"}),a.jsx(F,{label:"Sport equivalent",value:w}),a.jsx(F,{label:"Sweat fluid",value:`${t.sportSummary.fluidLossLiters} L`}),a.jsx(F,{label:"Sodium loss",value:`${t.sportSummary.sodiumLossMg} mg`})]}),a.jsxs("div",{className:"mt-4 flex min-w-0 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(Na,{className:"mt-0.5 size-4 shrink-0 text-[var(--ui-accent)]"}),a.jsx("span",{className:"min-w-0 text-wrap [overflow-wrap:anywhere]",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(pe,{title:"Minerals & oligoelements",description:"Daily mineral and trace-element targets including sodium ceiling and potassium AI.",children:a.jsx(ze,{rows:t.minerals,compact:!0})}),a.jsx(pe,{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(j=>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 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-start",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-sm font-semibold text-[var(--ui-ink)]",children:[j.id==="sweat_fluid"?a.jsx(rt,{className:"size-4 shrink-0 text-[var(--ui-accent)]"}):a.jsx(st,{className:"size-4 shrink-0 text-[var(--ui-accent)]"}),a.jsx("span",{className:"min-w-0 text-wrap [overflow-wrap:anywhere]",children:j.label})]}),a.jsx("p",{className:"mt-1 text-wrap text-xs text-[var(--ui-ink-faint)] [overflow-wrap:anywhere]",children:j.note})]}),a.jsxs("div",{className:"min-w-0 text-left text-sm font-semibold text-[var(--ui-ink)] sm:text-right",children:[j.target,a.jsx("div",{className:"text-xs font-normal text-[var(--ui-ink-faint)]",children:j.unit})]})]},j.id))})})]})]})]})})}function le(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 O(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>0?t:null}function Ga(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 Aa(e,t){return t==="gain"?e*1.03:t==="maintain"?e:e*.95}function Da(e){return e.toFixed(1)}function cn(e,t){return e==="male"?t>=51?30:38:t>=51?21:25}function dn(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 ua(e,t){const n=e/100;return n>0?t*n*n:null}function un(e){const t=e.goalMode==="lose"&&e.goalWeightKg!=null?Math.min(e.currentWeightKg,e.goalWeightKg):e.currentWeightKg,n=ua(e.heightCm,30),r=ua(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 gn(e,t){const n=O(e.currentWeightKg)??80;return{...e,goalMode:t,goalWeightKg:Da(Aa(n,t)),weeklyRateKg:Ga(n,t).toFixed(2)}}function qe(e){const t=_(e.weightTrend.latestWeightKg),n=e.target,r=le(n.notes,"sex"),s=le(n.notes,"age_years"),l=le(n.notes,"height_cm"),g=_(e.energyModel.activeBurnKcal)??_(e.energyModel.activeEnergyCalories)??_(e.energyModel.movementCaloriesKcal)??O(le(n.notes,"activity_kcal"))??0,c=n.bodyGoal??"",i=c.includes("gain")?"gain":c.includes("maintain")?"maintain":"lose",u=n.weightGoalKg??n.goalBodyWeightKg??null,f=t??80;return{goalMode:i,sex:r==="female"?"female":"male",ageYears:O(s)?String(s):"",heightCm:O(l)?String(l):"",currentWeightKg:t?t.toFixed(1):"",goalWeightKg:u?String(u):Da(Aa(f,i)),weeklyRateKg:n.weeklyRateGoalKg!==null&&n.weeklyRateGoalKg!==void 0?String(Math.abs(n.weeklyRateGoalKg)):Ga(f,i).toFixed(2),activeCaloriesKcal:g.toFixed(0),restingCaloriesKcal:_(e.energyModel.formulaRestingKcal)!=null?String(_(e.energyModel.formulaRestingKcal)):"",dietStyle:n.dietStyle??""}}function mn(e){const t=O(le(e.target.notes,"age_years"))!=null,n=O(le(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 hn(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 ${o(t.activeBurnKcal)} kcal/day, workout average ${o(t.workoutEnergyKcal)} kcal/day, movement average ${o(t.movementCaloriesKcal)} kcal/day, today's workout ${o(t.todayWorkoutEnergyKcal)} kcal, today's movement ${o(t.todayMovementCaloriesKcal)} kcal.`}function _a(e){const t=Number(e.currentWeightKg)||80,n=Number(e.heightCm)||178,r=Number(e.ageYears)||35,s=O(e.goalWeightKg),l=Math.max(0,Number(e.activeCaloriesKcal)||0),g=dn({sex:e.sex,ageYears:r,heightCm:n,weightKg:t})??10*t+6.25*n-5*r+5,c=g,i=c+l,u=Math.abs(Number(e.weeklyRateKg)||0),f=e.goalMode==="lose"?-u:e.goalMode==="gain"?u:0,K=Ma(f)??0,w=Jt(f)??0,j=e.sex==="male"?1500:1200,h=Math.round(i+K),b=Math.max(j,h),k=un({currentWeightKg:t,goalWeightKg:s,heightCm:n,goalMode:e.goalMode}),T=e.goalMode==="lose"?2:e.goalMode==="gain"?1.8:1.6,P=Math.round(k*T),R=Math.floor(b*.45/4),ae=Math.max(1,Math.min(P,R)),Q=k*.6,te=b*.25/9,V=Math.max(0,(b-ae*4)/9),B=Math.max(0,Math.floor(Math.min(V,b*.35/9,Math.max(Q,te)))),H=Math.max(0,Math.floor((b-ae*4-B*9)/4)),ne=Math.round(b/1e3*14),re=cn(e.sex,r),se=ne,J=Math.round(b*.1/9),ue=Math.round(b*.1/4);return{bmr:Math.round(g),restingCalories:Math.round(c),restingSource:"Mifflin-St Jeor baseline",activeCalories:Math.round(l),maintenanceCalories:Math.round(i),plannedCalorieTarget:h,minimumCalorieFloor:j,weeklyRateGoalKg:f,dailyEnergyAdjustment:Math.round(K),staticDailyEnergyAdjustment:Math.round(w),rateModel:Y.id,rateModelLabel:Y.label,rateModelPlanningHorizonDays:Y.defaultPlanningHorizonDays,calorieTarget:b,proteinReferenceWeight:Math.round(k*10)/10,proteinGramsTarget:ae,carbohydrateGramsTarget:H,fatGramsTarget:B,fiberGramsTarget:se,fiberEnergyAdjustedGrams:ne,fiberDriGrams:re,saturatedFatLimitGrams:J,addedSugarLimitGrams:ue}}function pn(e){const t=[],n=Number(e.ageYears),r=Number(e.heightCm),s=Number(e.currentWeightKg),l=Number(e.goalWeightKg),g=Number(e.weeklyRateKg),c=e.activeCaloriesKcal.trim()?Number(e.activeCaloriesKcal):Number.NaN,i=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(l)||l<30||l>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(c)||c<0||c>3e3)&&t.push("- Enter average active calories per day. Zero is valid only when Forge has no activity evidence."),i!=null&&(!Number.isFinite(i)||i<900||i>3500)&&t.push("- Formula resting baseline should stay in a plausible daily range."),t.length>0?t.join(`
|
|
1
|
+
import{j as a,bY as Ve,aG as ya,b8 as ja,cm as Ya,dA as Ja,cG as Xa,bC as Oe,cs as et,cK as ka,c0 as at,c1 as wa,dB as tt,dC as nt,br as Na,dD as rt,dE as st,r as M,bW as it,c2 as ot,dg as lt,dc as ct,aV as dt,dF as ut,cA as gt,bu as oa,dG as mt,bs as ht,be as pt}from"./vendor-y_uz1Wft.js";import{j as xt,i as ft,k as Z}from"./state-DWw8Jay_.js";import{P as bt}from"./page-hero-DYmFM6-q.js";import{C as U,ad as de,B as G,I as C,c as Ue,j as E,T as Ae,d as vt,L as yt,e as jt,eh as la,ei as kt,ej as wt,ek as Nt,el as ca,em as Ct,en as Mt,eo as Ft,ep as Kt,eq as St,er as Gt,es as At}from"./index-Dj8q65se.js";import{S as L,a as F}from"./surface-Dg5fauKP.js";import{Q as De,F as y,a as da}from"./question-flow-dialog-CPyXCqA-.js";import{g as Dt,f as Se}from"./date-keys-BnZV4PNO.js";import"./motion-DeJZhOSA.js";import"./ui-CdEDMtXF.js";import"./board-CGgOvBP9.js";import"./forms-DhEGHkFR.js";function _t({view:e,onOpenPlan:t,onOpenFoodSearch:n,onOpenCustomFood:r,onOpenChatGptFood:s,onOpenCheckin:l,onOpenHistory:g}){const c=[{label:"Plan target",value:`${e.target.calorieTarget.toFixed(0)} kcal`},{label:"Protein",value:`${e.target.proteinGramsTarget.toFixed(0)}g`},{label:"Fiber",value:`${e.target.fiberGramsTarget.toFixed(0)}g`}];return a.jsxs(U,{className:"grid gap-4 border-[var(--ui-border-subtle)] bg-[var(--ui-surface-section)] p-5",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",children:[a.jsx("span",{children:"Control center"}),a.jsx(de,{label:"Explain weight-loss controls",content:"Use these actions to change the nutrition plan, log food, or record body signals. The day budget cards above use today's active-calorie source; the plan target here is the baseline target before today's active adjustment."})]}),a.jsx("h2",{className:"mt-1 text-xl font-semibold leading-tight text-[var(--ui-ink-strong)]",children:e.target.bodyGoal?`Goal: ${e.target.bodyGoal}`:"Set the body objective"}),a.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:"Adjust the baseline plan, log food with exact quantities, or record body signals from guided flows."})]}),a.jsx("div",{className:"grid gap-2 sm:grid-cols-3 xl:grid-cols-1 min-[1360px]:grid-cols-3",children:c.map(i=>a.jsxs("div",{className:"min-w-0 rounded-[8px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] px-3 py-2",children:[a.jsx("div",{className:"text-[10px] uppercase tracking-[0.14em] text-[var(--ui-ink-faint)]",children:i.label}),a.jsx("div",{className:"mt-1 truncate text-sm font-semibold text-[var(--ui-ink-strong)]",children:i.value})]},i.label))}),a.jsxs("div",{className:"grid min-w-0 grid-cols-2 gap-2",children:[a.jsxs(G,{type:"button",onClick:r,children:[a.jsx(Ve,{className:"size-4"}),"Custom food"]}),a.jsxs(G,{type:"button",variant:"secondary",onClick:s,children:[a.jsx(ya,{className:"size-4"}),"Ask ChatGPT"]}),a.jsxs(G,{type:"button",variant:"secondary",onClick:n,children:[a.jsx(ja,{className:"size-4"}),"Search food"]}),a.jsxs(G,{type:"button",variant:"secondary",onClick:t,children:[a.jsx(Ya,{className:"size-4"}),"Plan settings"]}),a.jsxs(G,{type:"button",variant:"secondary",onClick:l,children:[a.jsx(Ja,{className:"size-4"}),"Add measure"]}),a.jsxs(G,{type:"button",variant:"secondary",onClick:g,children:[a.jsx(Xa,{className:"size-4"}),"Food history"]})]})]})}function _(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ce(e){return typeof e=="string"&&e.trim()?e:null}function o(e,t=0){const n=_(e);return n===null?"n/a":n.toFixed(t)}function q(e,t=0){const n=_(e);return n===null?"n/a":`${n>0?"+":""}${n.toFixed(t)}`}function Me(e){const t=_(e);return t===null?"n/a":`${t.toFixed(1)}/10`}function Et(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&!Array.isArray(t)):[]}function $t(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 Tt(e){switch(e){case"user_override":return"Using your manual value for today.";case"today_healthkit_active_energy":return"Using same-day HealthKit active energy instead of the 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 It(e){return`${e>=0?"+":""}${e.toFixed(0)} kcal`}function Lt(e){return e.trim()===""?"0":e}function Pt({view:e,draftValue:t,pending:n,error:r,onDraftChange:s,onSave:l,onReset:g}){const c=e.energyModel,i=e.todayLedger,u=c.todayActiveOverride,f=c.todayActiveCaloriesSource,K=`${i.plannedTargetCalories.toFixed(0)} ${It(c.todayTargetAdjustmentKcal)} = ${i.targetCalories.toFixed(0)} kcal`;return a.jsxs(U,{className:"grid min-w-0 gap-3 border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-4",children:[a.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-1 text-[11px] uppercase tracking-[0.14em] text-[var(--ui-ink-faint)]",children:["Active kcal",a.jsx(de,{label:"Explain active calories",content:`Selected-day target = baseline food target plus the day-specific active adjustment. ${K}. Automatic same-day activity can only add ${Math.round(c.activityEatBackFraction*100)}% of the positive surplus above the baseline day. A manual edit overrides this date 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:[c.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(Oe,{className:"size-4"})})]}),a.jsxs("div",{className:"grid gap-1 text-xs leading-5 text-[var(--ui-ink-soft)]",children:[a.jsx("div",{className:"break-words font-medium text-[var(--ui-ink-medium)]",children:Tt(f)}),a.jsxs("div",{children:["Baseline ",c.baselineActiveCaloriesKcal.toFixed(0)," kcal"," · ","observed"," ",c.todayObservedActiveCaloriesKcal!=null?`${c.todayObservedActiveCaloriesKcal.toFixed(0)} kcal`:"n/a"]}),a.jsxs("div",{className:"break-words",children:["Source: ",$t(f)]})]}),a.jsxs("div",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)_auto] gap-2",children:[a.jsx(C,{inputMode:"decimal",value:t,onChange:w=>s(Lt(w.target.value)),"aria-label":"Selected day active calories",className:"py-2.5"}),a.jsxs(G,{type:"button",onClick:l,pending:n,pendingLabel:"Applying",children:[a.jsx(et,{className:"size-4"}),"Apply"]})]}),a.jsxs(G,{type:"button",variant:"secondary",onClick:g,disabled:!u||n,children:[a.jsx(ka,{className:"size-4"}),"Use evidence"]}),r?a.jsx("div",{className:"rounded-[8px] border border-[var(--danger)]/20 bg-[var(--ui-danger-soft)] px-3 py-2 text-xs leading-5 text-[color-mix(in_srgb,var(--danger)_76%,var(--ui-ink-strong)_24%)]",children:r}):null]})}const Rt={default:"bg-[color-mix(in_srgb,var(--primary)_14%,transparent)] text-[var(--primary)]",green:"bg-[var(--ui-success-soft)] text-[color-mix(in_srgb,var(--success)_78%,var(--ui-ink-strong)_22%)]",amber:"bg-[var(--ui-warning-soft)] text-[color-mix(in_srgb,var(--warning)_76%,var(--ui-ink-strong)_24%)]",rose:"bg-[var(--ui-danger-soft)] text-[color-mix(in_srgb,var(--danger)_76%,var(--ui-ink-strong)_24%)]",cyan:"bg-[var(--ui-info-soft)] text-[color-mix(in_srgb,var(--info)_78%,var(--ui-ink-strong)_22%)]"};function ee({label:e,value:t,detail:n,icon:r,tone:s="default",help:l,helpMaxWidthPx:g}){return a.jsxs(U,{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:Ue("rounded-2xl p-2.5",Rt[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}),l?a.jsx(de,{content:l,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 Wt({meal:e,onLogAgain:t,onEdit:n,onDelete:r,pending:s=!1,hideMealLabel:l=!1}){const g=e.items[0]??null,c=Math.max(0,e.items.length-1),i=g?`${g.name}${c>0?` + ${c} more`:""}`:l?"Food entry":e.mealLabel??"Meal",u=e.items.slice(0,3).map(f=>{const K=Number.isFinite(f.quantity)&&f.quantity>0?Number.isInteger(f.quantity)?String(f.quantity):f.quantity.toFixed(2).replace(/\.?0+$/,""):null,w=f.unit??"serving",j=f.grams!=null?`${f.grams.toFixed(0)}g`:null;return[K,w,j?`(${j})`:null].filter(Boolean).join(" ")}).filter(Boolean).join(" · ");return a.jsxs(L,{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:i}),a.jsx("div",{className:"mt-1 text-xs leading-5 text-[var(--ui-ink-faint)]",children:u||e.notes||"No quantity recorded"})]}),a.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[e.mealLabel&&!l?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(G,{type:"button",size:"sm",variant:"secondary",onClick:()=>n(e),children:[a.jsx(at,{className:"size-4"}),"Edit"]}):null,r?a.jsxs(G,{type:"button",size:"sm",variant:"ghost",pending:s,onClick:()=>r(e),children:[a.jsx(wa,{className:"size-4"}),"Delete"]}):null,t?a.jsxs(G,{type:"button",size:"sm",variant:"ghost",pending:s,onClick:()=>t(e),children:[a.jsx(ka,{className:"size-4"}),"Log again"]}):null]})]})}function Ze({children:e}){return a.jsx(L,{className:"border-dashed border-[var(--ui-border-strong)] p-5 text-sm text-[var(--ui-ink-soft)]",children:e})}function fe(e){return`${e.toFixed(0)} kcal`}function Bt(e){return e>=0?"Kcal left":"Over target"}function Ht(e){return e>=0?fe(e):fe(Math.abs(e))}function zt(e){var n;const t=(n=e.mealLabel)==null?void 0:n.trim();return t||"No meal marker"}function qt(e){const t=[],n=new Map;for(const r of e){const s=zt(r);let l=n.get(s);l||(l={label:s,calories:0,meals:[]},t.push(l),n.set(s,l)),l.meals.push(r),l.calories+=r.totals.calories}return t}function Ot({ledger:e,remainingCalories:t,intakePercent:n,logSavedPending:r,onLogAgain:s,onEditMeal:l,onDeleteMeal:g}){const c=e.totals,i=qt(e.meals);return a.jsxs(U,{className:"grid gap-5 border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-5",children:[a.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",children:"Food log"}),a.jsxs("h2",{className:"mt-1 flex items-center gap-2 text-xl font-semibold text-[var(--ui-ink-strong)]",children:[a.jsx("span",{children:"Calories, macros, and meal evidence"}),a.jsx(de,{label:"Explain food log",content:"The food log is the selected day's editable record of what was eaten. Meal markers are optional; they group entries as breakfast, lunch, snack, dinner, or any personal label."})]})]}),a.jsxs(E,{tone:"meta",children:[e.meals.length," logs"]})]}),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"}),a.jsx("div",{className:"mt-1 text-2xl font-semibold text-[var(--ui-ink-strong)]",children:fe(c.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"}),a.jsx("div",{className:"mt-1 text-2xl font-semibold text-[var(--ui-ink-strong)]",children:fe(e.targetCalories)})]}),a.jsxs("div",{className:Ue("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:Bt(t)}),a.jsx("div",{className:"mt-1 text-2xl font-semibold text-[var(--ui-ink-strong)]",children:Ht(t)})]})]}),a.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-[var(--ui-surface-2)]",children:a.jsx("div",{className:Ue("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:[c.carbohydrateGrams.toFixed(0),"g carbs"]}),a.jsxs("span",{children:[c.fatGrams.toFixed(0),"g fat"]}),a.jsxs("span",{children:[c.fiberGrams.toFixed(0),"g fiber"]}),a.jsxs("span",{children:[e.unconfirmedCount," unconfirmed"]})]})]}),a.jsx("div",{className:"grid gap-3",children:e.meals.length>0?i.map(u=>a.jsxs("section",{className:"grid gap-2 rounded-[8px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] p-3",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[a.jsx("div",{className:"text-sm font-semibold text-[var(--ui-ink-strong)]",children:u.label}),a.jsxs("div",{className:"text-xs text-[var(--ui-ink-soft)]",children:[u.meals.length," log",u.meals.length===1?"":"s"," ","· ",fe(u.calories)]})]}),a.jsx("div",{className:"grid gap-2",children:u.meals.map(f=>a.jsx(Wt,{meal:f,pending:r,hideMealLabel:!0,onLogAgain:s,onEdit:l,onDelete:g},f.id))})]},u.label)):a.jsx(Ze,{children:"No food logged for this day yet."})})]})}function Ut({hypotheses:e}){return a.jsxs(U,{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(L,{children:[a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsx(E,{tone:"signal",children:ce(t.metric)??"pattern"}),a.jsx("span",{className:"text-xs text-[var(--ui-ink-faint)]",children:o(t.confidence,2)})]}),a.jsx("div",{className:"mt-3 text-sm font-medium text-[var(--ui-ink-strong)]",children:ce(t.label)??"Candidate pattern"}),a.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:ce(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(Ze,{children:"Log meals plus energy, gut, and look check-ins for a few days to generate pattern candidates."})})})]})}function Qt({experiments:e}){return a.jsxs(U,{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(tt,{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(L,{children:[a.jsx("div",{className:"text-sm font-medium text-[var(--ui-ink-strong)]",children:ce(t.title)??"Nutrition experiment"}),a.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:ce(t.hypothesis)??ce(t.intervention)??"No hypothesis recorded."})]},String(t.id??n))),e.length===0?a.jsx(Ze,{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 Vt({view:e}){const t=e.dataQuality,n=e.todayLedger;return a.jsxs(U,{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(Zt,{label:"Source confidence",value:t.sourceConfidence,children:"Food parsing stays candidate-based until accepted; wearable burn is treated as a trend input."}),a.jsxs(L,{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(L,{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 Zt({label:e,value:t,children:n}){return a.jsxs(L,{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 Y={id:"hall_niddk_linearized_adult_12w",label:"Hall/NIDDK linearized adult model",defaultPlanningHorizonDays:84,steadyStateKcalPerKgPerDay:10/.45359237,timeConstantDays:365,staticEnergyDensityKcalPerKg:7700};function He(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:null}function Ca(e={}){const t=He(e.planningHorizonDays)??Y.defaultPlanningHorizonDays,n=He(e.timeConstantDays)??Y.timeConstantDays,r=He(e.steadyStateKcalPerKgPerDay)??Y.steadyStateKcalPerKgPerDay,s=1-Math.exp(-t/n);return{planningHorizonDays:t,timeConstantDays:n,steadyStateKcalPerKgPerDay:r,responseFraction:s}}function Ma(e,t={}){if(typeof e!="number"||!Number.isFinite(e))return null;if(e===0)return 0;const n=Ca(t);return n.responseFraction<=0?null:e*(n.planningHorizonDays/7)*n.steadyStateKcalPerKgPerDay/n.responseFraction}function Yt(e,t={}){if(typeof e!="number"||!Number.isFinite(e))return null;if(e===0)return 0;const n=Ca(t);return e/n.steadyStateKcalPerKgPerDay*n.responseFraction/(n.planningHorizonDays/7)}function Jt(e){return typeof e!="number"||!Number.isFinite(e)?null:e*Y.staticEnergyDensityKcalPerKg/7}function z(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(de,{label:t,title:"Weight Loss Formulas",maxWidthPx:520,panelClassName:"text-xs leading-5",content:a.jsxs("div",{className:"grid gap-3",children:[a.jsx("p",{children:"Forge keeps activity independent from the goal. The goal only adds a deficit, surplus, or zero adjustment to 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:[z("Mifflin-St Jeor resting baseline",`10 x weight kg + 6.25 x height cm - 5 x age ${r}`,`Current formula value: ${o(e==null?void 0:e.bmrKcal)} kcal/day.`),z("Resting calories","Mifflin-St Jeor formula baseline; HealthKit basal is complete-day evidence only",`Using: ${o(e==null?void 0:e.restingKcal)} kcal/day${e!=null&&e.restingSource?` (${e.restingSource})`:""}.`),z("Maintenance calories","resting calories + active calories",`${o(e==null?void 0:e.restingKcal)} + ${o(e==null?void 0:e.activeKcal)} = ${o(e==null?void 0:e.maintenanceKcal)} kcal/day.`),z("Objective adjustment","Hall/NIDDK linearized adult model, inverted over the planning horizon",`Weekly rate ${q(e==null?void 0:e.weeklyRateKg,2)} kg/week gives ${q(e==null?void 0:e.dailyAdjustmentKcal)} kcal/day${e!=null&&e.rateModel?` with ${e.rateModel}`:""}${e!=null&&e.rateModelHorizonDays?` over ${e.rateModelHorizonDays} days`:""}.`),z("Daily calorie target","max(sex floor, maintenance + objective adjustment)",`Floor ${o(e==null?void 0:e.calorieFloor)} kcal; target ${o(e==null?void 0:e.calorieTarget)} kcal/day.`),z("Protein target",`min(reference weight x ${s}, 45% of kcal / 4)`,`Reference ${o(e==null?void 0:e.proteinReferenceWeightKg,1)} kg; target ${o(e==null?void 0:e.proteinGrams)} g/day.`),z("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 ${o(e==null?void 0:e.fatGrams)} g/day.`),z("Carbohydrate target","(calorie target - protein g x 4 - fat g x 9) / 4",`Target ${o(e==null?void 0:e.carbohydrateGrams)} g/day. The 130g DRI is shown as reference, not forced if it breaks calories.`),z("Fiber target","14g per 1000 kcal; adult sex/age AI shown as reference",`Target ${o(e==null?void 0:e.fiberGrams)} g/day; energy-adjusted ${o(e==null?void 0:e.fiberEnergyAdjustedGrams)} g/day; adult AI reference ${o(e==null?void 0:e.fiberDriGrams)} g/day.`),z("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 Ka(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 xe(e,t){const n=typeof e=="string"?Number(e):_(e);return typeof n=="number"&&Number.isFinite(n)?n:t}function Xt(e){return Ka(e.target.notes,"sex")==="female"?"female":"male"}function en(e){return xe(Ka(e.target.notes,"age_years"),35)}function p(e,t,n,r,s,l){return{id:e,label:t,target:typeof n=="number"?Qe(n):n,unit:r,note:s,source:l}}function Qe(e){return Number.isFinite(e)?Math.abs(e)>=100?e.toFixed(0):e.toFixed(1).replace(/\.0$/,""):"n/a"}function oe(e,t){return`${Qe(e)}-${Qe(t)}`}function an(e,t,n,r){const s=Math.round(n/1e3*14);return r>0?r:s}function tn({calorieTarget:e,currentWeightKg:t,protein:n,savedFat:r}){const s=Math.max(0,(e-n*4)/9),l=Math.max(0,Math.min(s,e*.35/9,Math.max(t*.6,e*.25/9))),g=r??l;return{carbs:Math.max(0,(e-n*4-g*9)/4),fat:g}}function nn(e,t){return e==="male"?t>=51?14:17:t>=51?11:12}function rn(e,t){const n=t>70,r=t>=51;return[p("vitamin_a","Vitamin A",e==="male"?900:700,"ug RAE","Retinol activity equivalent target.","NASEM DRI"),p("vitamin_c","Vitamin C",e==="male"?90:75,"mg","Adult RDA.","NASEM DRI"),p("vitamin_d","Vitamin D",n?20:15,"ug","Assumes limited sun exposure; older adults need more.","NASEM DRI"),p("vitamin_e","Vitamin E",15,"mg alpha-tocopherol","Adult RDA.","NASEM DRI"),p("vitamin_k","Vitamin K",e==="male"?120:90,"ug","Adult AI.","NASEM DRI"),p("thiamin_b1","Thiamin B1",e==="male"?1.2:1.1,"mg","Adult RDA.","NASEM DRI"),p("riboflavin_b2","Riboflavin B2",e==="male"?1.3:1.1,"mg","Adult RDA.","NASEM DRI"),p("niacin_b3","Niacin B3",e==="male"?16:14,"mg NE","Adult RDA.","NASEM DRI"),p("vitamin_b6","Vitamin B6",r?e==="male"?1.7:1.5:1.3,"mg","RDA rises after 50.","NASEM DRI"),p("folate","Folate",400,"ug DFE","Adult RDA.","NASEM DRI"),p("vitamin_b12","Vitamin B12",2.4,"ug","Adult RDA.","NASEM DRI"),p("pantothenic_acid","Pantothenic acid",5,"mg","Adult AI.","NASEM DRI"),p("biotin","Biotin",30,"ug","Adult AI.","NASEM DRI"),p("choline","Choline",e==="male"?550:425,"mg","Adult AI.","NASEM DRI")]}function sn(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,l=t>=71?1800:t>=51?2e3:2300;return[p("calcium","Calcium",n,"mg","Bone and muscle target; higher for older adults and women 51+.","NASEM DRI"),p("iron","Iron",e==="female"&&t<=50?18:8,"mg","Menstruating-age female target is higher.","NASEM DRI"),p("magnesium","Magnesium",r,"mg","Adult RDA.","NASEM DRI"),p("phosphorus","Phosphorus",700,"mg","Adult RDA.","NASEM DRI"),p("zinc","Zinc",e==="male"?11:8,"mg","Adult RDA.","NASEM DRI"),p("iodine","Iodine",150,"ug","Adult RDA.","NASEM DRI"),p("selenium","Selenium",55,"ug","Adult RDA.","NASEM DRI"),p("copper","Copper",.9,"mg","Adult RDA.","NASEM DRI"),p("manganese","Manganese",e==="male"?2.3:1.8,"mg","Adult AI.","NASEM DRI"),p("chromium","Chromium",s,"ug","Adult AI.","NASEM DRI"),p("molybdenum","Molybdenum",45,"ug","Adult RDA.","NASEM DRI"),p("fluoride","Fluoride",e==="male"?4:3,"mg","Adult AI.","NASEM DRI"),p("chloride","Chloride",l,"mg","Adult AI.","NASEM DRI"),p("potassium","Potassium",e==="male"?3400:2600,"mg","Current adult AI for non-pregnant adults.","NASEM DRI"),p("sodium_limit","Sodium ceiling",2300,"mg max","Default daily ceiling unless medically individualized.","U.S. Dietary Guidelines")]}function on(e){const t=Xt(e),n=en(e),r=xe(e.weightTrend.latestWeightKg,80),s=Math.max(1,xe(e.target.calorieTarget,2200)),l=xe(e.target.proteinGramsTarget,r*1.8),{carbs:g,fat:c}=tn({calorieTarget:s,currentWeightKg:r,protein:l,savedFat:_(e.target.fatGramsTarget)}),i=an(t,n,s,xe(e.target.fiberGramsTarget,0)),u=_(e.energyModel.activeBurnKcal)??_(e.energyModel.activeEnergyCalories)??null,f=_(e.energyModel.movementCaloriesKcal),K=_(e.energyModel.restingEnergyCalories);return Sa({sex:t,ageYears:n,currentWeightKg:r,calorieTarget:s,proteinGramsTarget:l,carbohydrateGramsTarget:g,fatGramsTarget:c,fiberGramsTarget:i,activeBurnKcal:u,movementCaloriesKcal:f,restingEnergyKcal:K})}function Sa(e){const{sex:t,ageYears:n,currentWeightKg:r,calorieTarget:s,proteinGramsTarget:l,carbohydrateGramsTarget:g,fatGramsTarget:c,fiberGramsTarget:i,activeBurnKcal:u,movementCaloriesKcal:f,restingEnergyKcal:K}=e,w=u!=null?Math.min(4,Math.max(.1,u/500)):null,j=w!=null?w*.4:null,h=w!=null?w*.8:null,b=j!=null?j*500:null,k=h!=null?h*1e3:null,T=j!=null?j*78:null,P=h!=null?h*312:null,R=u!=null?Yt(u):null;return{profile:{sex:t,ageYears:n,currentWeightKg:r,calorieTarget:s,activeBurnKcal:u,movementCaloriesKcal:f,restingEnergyKcal:K},macros:[p("calories","Calories",s,"kcal","Plan target from BMR, active burn, and chosen weekly rate.","Forge plan"),p("protein","Protein",l,"g","Higher than the population RDA to preserve lean mass during weight change.","ISSN + Forge plan"),p("carbohydrate","Carbohydrate",g,"g","Remaining fuel after protein and fat. It may sit below the 130g/day adult DRI reference when needed to preserve the calorie target.","NASEM DRI + Forge plan"),p("fat","Total fat",c,"g","Uses the saved plan fat target when present; generated defaults aim for a practical floor around 0.6g/kg or 20-35% of calories when possible.","NASEM AMDR + Forge plan"),p("fiber","Fiber",i,"g","Uses 14g per 1000 kcal as the plan target; the sex/age adult AI remains a reference or stretch value when calories are low.","NASEM DRI"),p("saturated_fat","Saturated fat",s*.1/9,"g max","Keep below 10% of energy.","U.S. Dietary Guidelines"),p("added_sugar","Added sugar",s*.1/4,"g max","Keep below 10% of energy; lower is better when feasible.","U.S. Dietary Guidelines"),p("linoleic_acid","Linoleic acid",nn(t,n),"g","Essential n-6 fatty acid AI.","NASEM DRI"),p("ala","ALA omega-3",t==="male"?1.6:1.1,"g","Essential n-3 fatty acid AI.","NASEM DRI"),p("water","Total water",t==="male"?3.7:2.7,"L","All beverages and food water before extra training replacement.","NASEM DRI")],vitamins:rn(t,n),minerals:sn(t,n),sportLosses:[p("training_time","Estimated training time",w??"n/a","h/day","Derived from active burn at roughly 500 kcal/h.","Forge sport-loss model"),p("sweat_fluid","Expected sweat fluid",j!=null&&h!=null?oe(j,h):"n/a","L/day","Planning range uses 0.4-0.8 L/h; measure body mass change to calibrate.","ACSM"),p("sweat_sodium","Expected sweat sodium",b!=null&&k!=null?oe(b,k):"n/a","mg/day","Sodium varies widely; this uses a conservative range around common sweat sodium values.","ACSM + Sports Medicine review"),p("sweat_potassium","Expected sweat potassium",T!=null&&P!=null?oe(T,P):"n/a","mg/day","Potassium is usually much smaller than sodium but useful for long/hot sessions.","Sports Medicine review"),p("gross_sport_equivalent","Gross sport burn equivalent",R??"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:w,fluidLossLiters:j!=null&&h!=null?oe(j,h):"n/a",sodiumLossMg:b!=null&&k!=null?oe(b,k):"n/a",potassiumLossMg:T!=null&&P!=null?oe(T,P):"n/a",grossSportWeightEquivalentKgPerWeek:R}}}function ze({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 max-w-full gap-2 overflow-hidden rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-3",children:[a.jsxs("div",{className:"grid min-w-0 gap-2 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-start",children:[a.jsx("div",{className:"min-w-0 text-wrap text-sm font-semibold text-[var(--ui-ink)] [overflow-wrap:anywhere]",children:n.label}),a.jsxs("div",{className:"min-w-0 text-left text-sm font-semibold text-[var(--ui-ink)] sm:text-right",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 text-wrap text-xs leading-5 text-[var(--ui-ink-muted)] [overflow-wrap:anywhere]",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 min-w-0 max-w-full 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-[560px] table-fixed border-collapse text-left text-sm lg:min-w-0",children:[a.jsxs("colgroup",{children:[a.jsx("col",{className:"w-[24%]"}),a.jsx("col",{className:"w-[18%]"}),a.jsx("col",{className:t?"w-[58%]":"w-[40%]"}),t?null:a.jsx("col",{className:"w-[18%]"})]}),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:"min-w-0 px-4 py-3 font-medium text-[var(--ui-ink)] [overflow-wrap:anywhere]",children:n.label}),a.jsxs("td",{className:"min-w-0 px-4 py-3 text-[var(--ui-ink)] [overflow-wrap:anywhere]",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:"min-w-0 px-4 py-3 text-[var(--ui-ink-muted)] [overflow-wrap:anywhere]",children:n.note}),t?null:a.jsx("td",{className:"min-w-0 px-4 py-3",children:a.jsx(E,{tone:"meta",wrap:!0,children:n.source})})]},n.id))})]})})})]})}function pe({title:e,description:t,children:n}){return a.jsxs(L,{className:"min-w-0 max-w-full overflow-hidden",children:[a.jsxs("div",{className:"mb-4 min-w-0",children:[a.jsx("h3",{className:"text-wrap text-sm font-semibold text-[var(--ui-ink)] [overflow-wrap:anywhere]",children:e}),a.jsx("p",{className:"mt-1 text-wrap text-sm text-[var(--ui-ink-muted)] [overflow-wrap:anywhere]",children:t})]}),n]})}function ln({view:e}){const t=on(e),n=e.target.weeklyRateGoalKg??null,r=n!=null&&Number.isFinite(n)?Ma(n):null,s=t.profile.restingEnergyKcal,l=t.profile.activeBurnKcal,g=s!=null&&l!=null?s+l:null,c=e.target.bodyGoal??"maintain",i=c.includes("lose")?2:c.includes("gain")?1.8:1.6,u=j=>{var k;const h=(k=t.macros.find(T=>T.id===j))==null?void 0:k.target,b=Number(h);return Number.isFinite(b)?b:null},f=t.profile.sex==="male"?t.profile.ageYears>=51?30:38:t.profile.ageYears>=51?21:25,K=Math.round(t.profile.calorieTarget/1e3*14),w=t.sportSummary.grossSportWeightEquivalentKgPerWeek!=null?`${t.sportSummary.grossSportWeightEquivalentKgPerWeek.toFixed(2)} kg/week`:"n/a";return a.jsx("section",{className:"grid gap-4",children:a.jsxs(U,{className:"min-w-0 overflow-hidden p-4 sm:p-5",children:[a.jsxs("div",{className:"grid min-w-0 gap-3 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-start",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2 text-sm font-semibold text-[var(--ui-ink)]",children:[a.jsx(nt,{className:"size-4 shrink-0 text-[var(--ui-accent)]"}),a.jsx("span",{className:"min-w-0 text-wrap [overflow-wrap:anywhere]",children:"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:l,maintenanceKcal:g,weeklyRateKg:n,dailyAdjustmentKcal:r,rateModel:Y.label,rateModelHorizonDays:Y.defaultPlanningHorizonDays,calorieTarget:t.profile.calorieTarget,calorieFloor:t.profile.sex==="male"?1500:1200,proteinReferenceWeightKg:null,proteinFactor:i,proteinGrams:u("protein"),fatGrams:u("fat"),carbohydrateGrams:u("carbohydrate"),fiberGrams:u("fiber"),fiberEnergyAdjustedGrams:K,fiberDriGrams:f}})]}),a.jsx("p",{className:"mt-1 max-w-3xl text-wrap text-sm text-[var(--ui-ink-muted)] [overflow-wrap:anywhere]",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 min-w-0 flex-wrap gap-2 lg:justify-end",children:[a.jsxs(E,{tone:"signal",children:[t.profile.calorieTarget.toFixed(0)," kcal"]}),a.jsxs(E,{tone:"meta",wrap:!0,children:[t.profile.sex,", ",t.profile.ageYears.toFixed(0),"y"]})]})]}),a.jsxs("div",{className:"mt-5 grid min-w-0 gap-4 2xl:grid-cols-[minmax(0,1fr)_minmax(280px,0.58fr)]",children:[a.jsxs("div",{className:"grid min-w-0 gap-4",children:[a.jsx(pe,{title:"All macro targets",description:"Calories, protein, carbs, fat, fiber, sugar ceiling, saturated fat ceiling, essential fats, and water.",children:a.jsx(ze,{rows:t.macros,compact:!0})}),a.jsx(pe,{title:"Vitamins",description:"Adult daily vitamin targets from DRI values, adjusted for sex and age where the reference differs.",children:a.jsx(ze,{rows:t.vitamins})})]}),a.jsxs("div",{className:"grid min-w-0 content-start gap-4",children:[a.jsxs(pe,{title:"Expected sport losses",description:"Planning range from active burn. Calibrate with pre/post workout weight when possible.",children:[a.jsxs("div",{className:"grid min-w-0 gap-3 sm:grid-cols-2",children:[a.jsx(F,{label:"Active burn",value:t.profile.activeBurnKcal!=null?`${t.profile.activeBurnKcal.toFixed(0)} kcal`:"n/a"}),a.jsx(F,{label:"Sport equivalent",value:w}),a.jsx(F,{label:"Sweat fluid",value:`${t.sportSummary.fluidLossLiters} L`}),a.jsx(F,{label:"Sodium loss",value:`${t.sportSummary.sodiumLossMg} mg`})]}),a.jsxs("div",{className:"mt-4 flex min-w-0 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(Na,{className:"mt-0.5 size-4 shrink-0 text-[var(--ui-accent)]"}),a.jsx("span",{className:"min-w-0 text-wrap [overflow-wrap:anywhere]",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(pe,{title:"Minerals & oligoelements",description:"Daily mineral and trace-element targets including sodium ceiling and potassium AI.",children:a.jsx(ze,{rows:t.minerals,compact:!0})}),a.jsx(pe,{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(j=>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 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-start",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-sm font-semibold text-[var(--ui-ink)]",children:[j.id==="sweat_fluid"?a.jsx(rt,{className:"size-4 shrink-0 text-[var(--ui-accent)]"}):a.jsx(st,{className:"size-4 shrink-0 text-[var(--ui-accent)]"}),a.jsx("span",{className:"min-w-0 text-wrap [overflow-wrap:anywhere]",children:j.label})]}),a.jsx("p",{className:"mt-1 text-wrap text-xs text-[var(--ui-ink-faint)] [overflow-wrap:anywhere]",children:j.note})]}),a.jsxs("div",{className:"min-w-0 text-left text-sm font-semibold text-[var(--ui-ink)] sm:text-right",children:[j.target,a.jsx("div",{className:"text-xs font-normal text-[var(--ui-ink-faint)]",children:j.unit})]})]},j.id))})})]})]})]})})}function le(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 O(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>0?t:null}function Ga(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 Aa(e,t){return t==="gain"?e*1.03:t==="maintain"?e:e*.95}function Da(e){return e.toFixed(1)}function cn(e,t){return e==="male"?t>=51?30:38:t>=51?21:25}function dn(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 ua(e,t){const n=e/100;return n>0?t*n*n:null}function un(e){const t=e.goalMode==="lose"&&e.goalWeightKg!=null?Math.min(e.currentWeightKg,e.goalWeightKg):e.currentWeightKg,n=ua(e.heightCm,30),r=ua(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 gn(e,t){const n=O(e.currentWeightKg)??80;return{...e,goalMode:t,goalWeightKg:Da(Aa(n,t)),weeklyRateKg:Ga(n,t).toFixed(2)}}function qe(e){const t=_(e.weightTrend.latestWeightKg),n=e.target,r=le(n.notes,"sex"),s=le(n.notes,"age_years"),l=le(n.notes,"height_cm"),g=_(e.energyModel.activeBurnKcal)??_(e.energyModel.activeEnergyCalories)??_(e.energyModel.movementCaloriesKcal)??O(le(n.notes,"activity_kcal"))??0,c=n.bodyGoal??"",i=c.includes("gain")?"gain":c.includes("maintain")?"maintain":"lose",u=n.weightGoalKg??n.goalBodyWeightKg??null,f=t??80;return{goalMode:i,sex:r==="female"?"female":"male",ageYears:O(s)?String(s):"",heightCm:O(l)?String(l):"",currentWeightKg:t?t.toFixed(1):"",goalWeightKg:u?String(u):Da(Aa(f,i)),weeklyRateKg:n.weeklyRateGoalKg!==null&&n.weeklyRateGoalKg!==void 0?String(Math.abs(n.weeklyRateGoalKg)):Ga(f,i).toFixed(2),activeCaloriesKcal:g.toFixed(0),restingCaloriesKcal:_(e.energyModel.formulaRestingKcal)!=null?String(_(e.energyModel.formulaRestingKcal)):"",dietStyle:n.dietStyle??""}}function mn(e){const t=O(le(e.target.notes,"age_years"))!=null,n=O(le(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 hn(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 ${o(t.activeBurnKcal)} kcal/day, workout average ${o(t.workoutEnergyKcal)} kcal/day, movement average ${o(t.movementCaloriesKcal)} kcal/day, today's workout ${o(t.todayWorkoutEnergyKcal)} kcal, today's movement ${o(t.todayMovementCaloriesKcal)} kcal.`}function _a(e){const t=Number(e.currentWeightKg)||80,n=Number(e.heightCm)||178,r=Number(e.ageYears)||35,s=O(e.goalWeightKg),l=Math.max(0,Number(e.activeCaloriesKcal)||0),g=dn({sex:e.sex,ageYears:r,heightCm:n,weightKg:t})??10*t+6.25*n-5*r+5,c=g,i=c+l,u=Math.abs(Number(e.weeklyRateKg)||0),f=e.goalMode==="lose"?-u:e.goalMode==="gain"?u:0,K=Ma(f)??0,w=Jt(f)??0,j=e.sex==="male"?1500:1200,h=Math.round(i+K),b=Math.max(j,h),k=un({currentWeightKg:t,goalWeightKg:s,heightCm:n,goalMode:e.goalMode}),T=e.goalMode==="lose"?2:e.goalMode==="gain"?1.8:1.6,P=Math.round(k*T),R=Math.floor(b*.45/4),ae=Math.max(1,Math.min(P,R)),Q=k*.6,te=b*.25/9,V=Math.max(0,(b-ae*4)/9),B=Math.max(0,Math.floor(Math.min(V,b*.35/9,Math.max(Q,te)))),H=Math.max(0,Math.floor((b-ae*4-B*9)/4)),ne=Math.round(b/1e3*14),re=cn(e.sex,r),se=ne,J=Math.round(b*.1/9),ue=Math.round(b*.1/4);return{bmr:Math.round(g),restingCalories:Math.round(c),restingSource:"Mifflin-St Jeor baseline",activeCalories:Math.round(l),maintenanceCalories:Math.round(i),plannedCalorieTarget:h,minimumCalorieFloor:j,weeklyRateGoalKg:f,dailyEnergyAdjustment:Math.round(K),staticDailyEnergyAdjustment:Math.round(w),rateModel:Y.id,rateModelLabel:Y.label,rateModelPlanningHorizonDays:Y.defaultPlanningHorizonDays,calorieTarget:b,proteinReferenceWeight:Math.round(k*10)/10,proteinGramsTarget:ae,carbohydrateGramsTarget:H,fatGramsTarget:B,fiberGramsTarget:se,fiberEnergyAdjustedGrams:ne,fiberDriGrams:re,saturatedFatLimitGrams:J,addedSugarLimitGrams:ue}}function pn(e){const t=[],n=Number(e.ageYears),r=Number(e.heightCm),s=Number(e.currentWeightKg),l=Number(e.goalWeightKg),g=Number(e.weeklyRateKg),c=e.activeCaloriesKcal.trim()?Number(e.activeCaloriesKcal):Number.NaN,i=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(l)||l<30||l>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(c)||c<0||c>3e3)&&t.push("- Enter average active calories per day. Zero is valid only when Forge has no activity evidence."),i!=null&&(!Number.isFinite(i)||i<900||i>3500)&&t.push("- Formula resting baseline should stay in a plausible daily range."),t.length>0?t.join(`
|
|
2
2
|
`):null}function xn(e){const t=_a(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 fn({open:e,onOpenChange:t,view:n,value:r,onChange:s,onSubmit:l,pending:g,error:c}){const i=M.useMemo(()=>_a(r),[r]),u=O(r.ageYears)!=null&&O(r.heightCm)!=null&&O(r.currentWeightKg)!=null,f=u?String(i.bmr):"",K=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: ${i.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.",w=M.useMemo(()=>Sa({sex:r.sex,ageYears:Number(r.ageYears)||35,currentWeightKg:Number(r.currentWeightKg)||80,calorieTarget:i.calorieTarget,proteinGramsTarget:i.proteinGramsTarget,carbohydrateGramsTarget:i.carbohydrateGramsTarget,fatGramsTarget:i.fatGramsTarget,fiberGramsTarget:i.fiberGramsTarget,activeBurnKcal:i.activeCalories,movementCaloriesKcal:_(n.energyModel.movementCaloriesKcal),restingEnergyKcal:i.restingCalories}),[i,r,n.energyModel.movementCaloriesKcal]),j=[{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:(h,b)=>a.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[a.jsx(y,{label:"Sex",children:a.jsx(da,{value:h.sex,onChange:k=>b({sex:k}),options:[{value:"male",label:"Male"},{value:"female",label:"Female"}]})}),a.jsx(y,{label:"Age",children:a.jsx(C,{inputMode:"numeric",value:h.ageYears,onChange:k=>b({ageYears:k.target.value}),placeholder:"35"})}),a.jsx(y,{label:"Height cm",children:a.jsx(C,{inputMode:"decimal",value:h.heightCm,onChange:k=>b({heightCm:k.target.value}),placeholder:"178"})}),a.jsx(y,{label:"Current weight kg",children:a.jsx(C,{inputMode:"decimal",value:h.currentWeightKg,onChange:k=>b({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:(h,b)=>a.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[a.jsx("div",{className:"md:col-span-2",children:a.jsx(da,{columns:3,value:h.goalMode,onChange:k=>b(gn(h,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(y,{label:"Target weight kg",hint:"Filled from the objective; change it anytime.",children:a.jsx(C,{inputMode:"decimal",value:h.goalWeightKg,onChange:k=>b({goalWeightKg:k.target.value}),placeholder:"75.0"})}),a.jsx(y,{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(C,{inputMode:"decimal",value:h.weeklyRateKg,onChange:k=>b({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:(h,b)=>a.jsxs("div",{className:"grid gap-4",children:[a.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[a.jsx(y,{label:"Formula resting baseline/day",hint:K,children:a.jsx(C,{inputMode:"decimal",value:f,readOnly:!0,placeholder:"Calculated from profile"})}),a.jsx(y,{label:"Average active calories/day",hint:hn(n),children:a.jsx(C,{inputMode:"decimal",value:h.activeCaloriesKcal,onChange:k=>b({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(F,{label:i.restingSource,value:`${i.restingCalories} kcal`}),a.jsx(F,{label:"Maintenance",value:`${i.maintenanceCalories} kcal`}),a.jsx(F,{label:"Daily adjustment",value:`${i.dailyEnergyAdjustment>0?"+":""}${i.dailyEnergyAdjustment} kcal`})]})]})},{id:"macros",eyebrow:"Macros",title:"Validate calories, macros, and limits",description:"Target intake equals resting burn plus active burn plus the objective adjustment. Macros are generated from protein-per-kg, a practical fat floor, remaining carbohydrates, fiber density, and dietary limits.",render:(h,b)=>a.jsxs("div",{className:"grid gap-4",children:[a.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-[20px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] px-4 py-3",children:[a.jsx("div",{className:"min-w-0 text-sm leading-6 text-[var(--ui-ink-muted)]",children:"Inspect the exact math behind the current calories, macro targets, and sport-loss preview."}),a.jsx(Fa,{values:{sex:h.sex,ageYears:Number(h.ageYears)||null,currentWeightKg:Number(h.currentWeightKg)||null,heightCm:Number(h.heightCm)||null,bmrKcal:i.bmr,restingKcal:i.restingCalories,restingSource:i.restingSource,activeKcal:i.activeCalories,maintenanceKcal:i.maintenanceCalories,weeklyRateKg:i.weeklyRateGoalKg,dailyAdjustmentKcal:i.dailyEnergyAdjustment,rateModel:i.rateModelLabel,rateModelHorizonDays:i.rateModelPlanningHorizonDays,calorieTarget:i.calorieTarget,calorieFloor:i.minimumCalorieFloor,proteinReferenceWeightKg:i.proteinReferenceWeight,proteinFactor:h.goalMode==="lose"?2:h.goalMode==="gain"?1.8:1.6,proteinGrams:i.proteinGramsTarget,fatGrams:i.fatGramsTarget,carbohydrateGrams:i.carbohydrateGramsTarget,fiberGrams:i.fiberGramsTarget,fiberEnergyAdjustedGrams:i.fiberEnergyAdjustedGrams,fiberDriGrams:i.fiberDriGrams}})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-4 xl:grid-cols-7",children:[a.jsx(F,{label:"Calories",value:`${i.calorieTarget}`}),a.jsx(F,{label:"Protein",value:`${i.proteinGramsTarget}g`}),a.jsx(F,{label:"Carbs",value:`${i.carbohydrateGramsTarget}g`}),a.jsx(F,{label:"Fat",value:`${i.fatGramsTarget}g`}),a.jsx(F,{label:"Fiber",value:`${i.fiberGramsTarget}g`}),a.jsx(F,{label:"Sat fat max",value:`${i.saturatedFatLimitGrams}g`}),a.jsx(F,{label:"Added sugar max",value:`${i.addedSugarLimitGrams}g`})]}),a.jsxs("div",{className:"grid gap-4 rounded-[24px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-4",children:[a.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-sm font-semibold text-[var(--ui-ink)]",children:"Micronutrient and sport-loss preview"}),a.jsx("div",{className:"mt-1 text-sm leading-6 text-[var(--ui-ink-muted)]",children:"The dashboard will track vitamin, mineral, trace-element, water, sodium-ceiling, essential-fat, and sport-loss targets from this plan."})]}),a.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.jsxs(E,{tone:"meta",children:[w.vitamins.length," vitamins"]}),a.jsxs(E,{tone:"meta",children:[w.minerals.length," minerals"]}),a.jsxs(E,{tone:"signal",children:[w.sportSummary.fluidLossLiters," L sweat"]})]})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[a.jsx(F,{label:"Sport sodium loss",value:`${w.sportSummary.sodiumLossMg} mg`}),a.jsx(F,{label:"Sport potassium loss",value:`${w.sportSummary.potassiumLossMg} mg`}),a.jsx(F,{label:"Water baseline",value:r.sex==="male"?"3.7 L":"2.7 L"}),a.jsx(F,{label:"Essential fats",value:r.sex==="male"?"17g LA / 1.6g ALA":"12g LA / 1.1g ALA"})]})]}),a.jsx(y,{label:"Diet style or constraints",children:a.jsx(Ae,{value:h.dietStyle,onChange:k=>b({dietStyle:k.target.value}),placeholder:"Mediterranean, high protein, no lactose, low FODMAP trial..."})})]})}];return a.jsx(De,{open:e,onOpenChange:t,eyebrow:"Weight plan",title:"Set weight objective",description:"Build an editable calorie and macro plan.",value:r,onChange:s,steps:j,onSubmit:l,submitLabel:"Save plan",pending:g,pendingLabel:"Saving plan",error:c,draftPersistenceKey:"weight-loss-plan"})}const bn={tsp:5,tbsp:15,cup:240};function Fe(){return{mealLabel:"",notes:"",source:"search",selectedItems:[]}}function A(e,t,n){return typeof e!="number"||!Number.isFinite(e)?null:$a(n)==="grams"?e:t>0?Math.round(e/t*10)/10:e}function vn(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:A(e.calories,t,n),proteinGrams:A(e.proteinGrams,t,n),carbohydrateGrams:A(e.carbohydrateGrams,t,n),fatGrams:A(e.fatGrams,t,n),fiberGrams:A(e.fiberGrams,t,n),sugarGrams:A(e.sugarGrams,t,n),sodiumMg:A(e.sodiumMg,t,n),potassiumMg:A(e.potassiumMg,t,n),caffeineMg:A(e.caffeineMg,t,n),alcoholGrams:A(e.alcoholGrams,t,n),glycemicIndex:e.glycemicIndex??null,novaGroup:e.novaGroup??null,tags:e.tags??[],confidence:e.confidence??null}}function yn(e,t,n){const r=Number.isFinite(e.quantity)&&e.quantity>0?e.quantity:1,s=e.unit??"serving",l=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:l??null,calories:A(e.calories,r,s),proteinGrams:A(e.proteinGrams,r,s),carbohydrateGrams:A(e.carbohydrateGrams,r,s),fatGrams:A(e.fatGrams,r,s),fiberGrams:A(e.fiberGrams,r,s),sugarGrams:A(e.sugarGrams,r,s),sodiumMg:A(e.sodiumMg,r,s),potassiumMg:A(e.potassiumMg,r,s),caffeineMg:A(e.caffeineMg,r,s),alcoholGrams:A(e.alcoholGrams,r,s),glycemicIndex:e.glycemicIndex??null,novaGroup:e.novaGroup??null,tags:e.tags??[],confidence:e.confidence??null}}function jn(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 ve(e){return typeof e.servingGrams=="number"&&Number.isFinite(e.servingGrams)&&e.servingGrams>0?e.servingGrams:jn(e.servingLabel)}function kn(e){const t=ve(e);return t!=null?`${o(t)} g`:e.servingLabel??"serving"}function Ea(e){const t=Number(e.amount)||0;if(t<=0)return null;const n=ve(e.food);return e.unit==="grams"?t:e.unit==="tsp"||e.unit==="tbsp"||e.unit==="cup"?t*bn[e.unit]:n!=null?t*n:null}function ga(e){return!(e.unit==="grams"||e.unit==="tsp"||e.unit==="tbsp"||e.unit==="cup")||ve(e.food)!=null?null:"Add base grams before using grams or household measures. Without a denominator, Forge will not guess a ratio."}function $a(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 wn(e){switch(e){case"manual":case"search":case"barcode":case"chatgpt":case"photo":case"saved_meal":return e;default:return"manual"}}function Nn(e){return{mealLabel:e.mealLabel??"",notes:e.notes??"",loggedAt:e.loggedAt,dayKey:e.dayKey,source:wn(e.source),selectedItems:e.items.map(t=>({localId:t.id,food:vn(t),amount:String(t.quantity||1),unit:t.unit??"serving"}))}}function Cn(e,t=e.source??"manual"){return{mealLabel:e.mealLabel??"",notes:e.notes??"",loggedAt:e.loggedAt,dayKey:e.dayKey,timeZone:e.timeZone,source:e.source??"manual",selectedItems:e.items.map((n,r)=>({localId:`${t}-${r}-${Date.now()}`,food:yn(n,r,t),amount:String(n.quantity||1),unit:$a(n.unit)}))}}function Ta(){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 Mn(){return{mealLabel:"",notes:"",source:"manual",selectedItems:[{localId:`custom-${Date.now()}`,food:Ta(),amount:"100",unit:"grams"}]}}const Ge=["Reading the meal text","Searching nutrition catalogs","Checking calories and macros","Preparing the review draft"];function Fn(e){return typeof e!="number"||!Number.isFinite(e)?null:`${Math.max(.1,e/1e3).toFixed(1)}s`}function Kn({feedback:e,pending:t,stageIndex:n}){if(!t&&(e==null?void 0:e.status)!=="success")return null;if(t){const l=Ge[n]??Ge[0];return a.jsxs("div",{className:"overflow-hidden rounded-[20px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-[var(--ui-ink-strong)]",children:[a.jsx(it,{className:"size-4 animate-spin text-[var(--primary)]"}),l]}),a.jsx("div",{className:"mt-3 grid grid-cols-4 gap-1.5",children:Ge.map((g,c)=>a.jsx("div",{className:`h-1.5 rounded-full transition-colors duration-300 ${c<=n?"bg-[linear-gradient(90deg,var(--primary),var(--secondary))]":"bg-[var(--ui-surface-3)]"}`},g))}),a.jsx("div",{className:"mt-2 text-xs leading-5 text-[var(--ui-ink-soft)]",children:"Forge is parsing the text, matching foods, and refusing incomplete nutrition before it adds anything to the draft."})]})}const r=e==null?void 0:e.summary;if(!r)return null;const s=Fn(r.elapsedMs);return a.jsxs("div",{className:"rounded-[20px] border border-[color-mix(in_srgb,var(--success)_26%,var(--ui-border-subtle)_74%)] bg-[color-mix(in_srgb,var(--success)_10%,var(--ui-surface-1)_90%)] p-3",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-[var(--ui-ink-strong)]",children:[a.jsx(ot,{className:"size-4 text-[var(--success)]"}),r.itemCount," food",r.itemCount===1?"":"s"," added to the draft"]}),a.jsxs(E,{tone:"signal",children:[r.completeNutritionItemCount,"/",r.itemCount," complete"]})]}),a.jsxs("div",{className:"mt-2 grid gap-2 text-xs leading-5 text-[var(--ui-ink-soft)] sm:grid-cols-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(lt,{className:"size-3.5 text-[var(--secondary)]"}),r.catalogResolvedItemCount," catalog match",r.catalogResolvedItemCount===1?"":"es"," ·"," ",r.chatGptValidatedItemCount," model validation",r.chatGptValidatedItemCount===1?"":"s"]}),a.jsxs("div",{children:[r.llmCallCount," model call",r.llmCallCount===1?"":"s",s?` · ${s}`:""]})]}),a.jsx("div",{className:"mt-2 text-xs leading-5 text-[var(--ui-ink-soft)]",children:"You can add more food here, or continue to review exact quantities and nutrients before saving."})]})}function Sn({open:e,onOpenChange:t,value:n,onChange:r,foodResults:s,searchPending:l,chatGptPending:g=!1,chatGptError:c=null,chatGptFeedback:i=null,logPending:u,onSearch:f,onParseWithChatGpt:K,onSubmit:w,mode:j="create",intent:h="search",initialStepId:b}){const[k,T]=M.useState(""),[P,R]=M.useState(""),[ae,Q]=M.useState(0),[te,V]=M.useState(null),B=M.useMemo(()=>Tn(n.selectedItems),[n.selectedItems]),H=x=>r({...n,...x}),ne=x=>{H({selectedItems:[...n.selectedItems,{localId:`${x.id}-${Date.now()}`,food:x,amount:"1",unit:"serving"}]}),V(null)},re=()=>{ne(Ta())},se=async()=>{const x=P.trim();!x||!K||(await K(x),R(""))},J=(x,v)=>{H({selectedItems:n.selectedItems.map(N=>N.localId===x?{...N,...v}:N)})},ue=(x,v)=>{H({selectedItems:n.selectedItems.map(N=>N.localId===x?{...N,food:{...N.food,...v}}:N)})},ye=x=>{H({selectedItems:n.selectedItems.filter(v=>v.localId!==x)})},_e=async()=>{n.selectedItems.length!==0&&(ha(n)||await w())};M.useEffect(()=>{if(!g){Q(0);return}const x=window.setInterval(()=>{Q(v=>(v+1)%Ge.length)},1250);return()=>window.clearInterval(x)},[g]);const W=ha(n),je=a.jsxs(L,{className:"grid gap-3",children:[a.jsx(y,{label:"Ask ChatGPT",labelHelp:"Uses the connected OpenAI Codex OAuth / ChatGPT subscription model to create a reviewable candidate meal draft. It does not use the metered OpenAI Platform API.",children:a.jsx(Ae,{value:P,onChange:x=>R(x.target.value),placeholder:"Example: 2 eggs, 150g Greek yogurt, one banana, and a cappuccino..."})}),c?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:c}):null,a.jsx(Kn,{feedback:i,pending:g,stageIndex:ae}),a.jsxs(G,{type:"button",variant:h==="chatgpt"?"primary":"secondary",pending:g,pendingLabel:"Parsing",disabled:!P.trim()||!K,onClick:()=>void se(),children:[a.jsx(ya,{className:"size-4"}),"Parse with ChatGPT"]})]}),ge=a.jsx(L,{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(G,{type:"button",size:"sm",onClick:re,children:[a.jsx(Ve,{className:"size-4"}),"Add custom"]})]})}),me=h==="chatgpt"?[je,ge]:[ge,je],X=[{id:"search",eyebrow:h==="chatgpt"?"ChatGPT food parser":"Food",title:h==="chatgpt"?"Describe the meal, then review every item":"Search, create, or ask ChatGPT",description:h==="chatgpt"?"ChatGPT creates a candidate meal through the subscription-backed connection; you still review quantities and nutrients before saving.":"Search the catalog, create a custom food, or use ChatGPT to turn rough meal text into editable items.",render:()=>a.jsxs("div",{className:"grid gap-4",children:[a.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_auto]",children:[a.jsx(y,{label:"Food search",labelHelp:"Search returns food candidates with per-serving nutrition. Click a result to inspect macros before adding it to the meal draft.",children:a.jsx(C,{value:k,onChange:x=>T(x.target.value),placeholder:"Search eggs, yogurt, sourdough..."})}),a.jsxs(G,{type:"button",variant:"secondary",pending:l,disabled:!k.trim(),onClick:()=>f(k),children:[a.jsx(ja,{className:"size-4"}),"Search"]})]}),a.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:me.map((x,v)=>a.jsx("div",{children:x},`${h}-assistant-panel-${v}`))}),te?a.jsx(En,{food:te,onAdd:()=>ne(te)}):null,a.jsx("div",{className:"grid gap-3",children:s.map(x=>a.jsx(L,{interactive:!0,className:"p-0",children:a.jsx("button",{type:"button",className:"block w-full rounded-[22px] p-4 text-left",onClick:()=>V(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:[o(x.calories)," kcal"]})]})})},x.id))})]})},{id:"amounts",eyebrow:h==="custom"?"Custom food":"Quantity",title:h==="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(L,{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: ",o(v.food.calories)," kcal per"," ",kn(v.food)]})]}),a.jsxs(G,{type:"button",size:"sm",variant:"ghost",onClick:()=>ye(v.localId),children:[a.jsx(wa,{className:"size-4"}),"Remove"]})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto]",children:[a.jsx(y,{label:"Quantity",labelHelp:"This is the amount actually eaten. Forge converts the selected unit to an eaten gram equivalent when base grams are known, then scales every nutrient by eaten grams divided by base grams.",children:a.jsx(C,{inputMode:"decimal",value:v.amount,onChange:N=>J(v.localId,{amount:N.target.value}),placeholder:"1"})}),a.jsx(y,{label:"Unit",labelHelp:"Servings multiply the base serving. Grams, teaspoons, tablespoons, and cups use a gram conversion table and require base grams.",children:a.jsxs("select",{className:"interactive-tap w-full rounded-[22px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-3 text-[15px] text-[var(--ui-ink-strong)] outline-none",value:v.unit,onChange:N=>J(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:[o(be(v).calories)," kcal"]})]}),ga(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:ga(v)}):a.jsxs("div",{className:"text-xs text-[var(--ui-ink-faint)]",children:[o(Number(v.amount)||0)," ",v.unit," ="," ",o(Ea(v))," g eaten; ratio ="," ",o(be(v).scale),"x the base nutrition."]}),a.jsx(_n,{item:v,onChange:N=>ue(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(F,{label:"Calories",value:o(B.calories)}),a.jsx(F,{label:"Protein",value:`${o(B.proteinGrams)}g`}),a.jsx(F,{label:"Carbs",value:`${o(B.carbohydrateGrams)}g`}),a.jsx(F,{label:"Fat",value:`${o(B.fatGrams)}g`})]}),W?a.jsx("div",{className:"rounded-[20px] border border-[color-mix(in_srgb,var(--danger)_28%,var(--ui-border-subtle)_72%)] bg-[var(--ui-danger-soft)] px-4 py-3 text-sm leading-6 text-[color-mix(in_srgb,var(--danger)_76%,var(--ui-ink-strong)_24%)]",children:W}):null]})},{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.jsxs(y,{label:"Meal marker (optional)",labelHelp:"Use a marker such as breakfast, lunch, snack, or dinner when it helps group the day. Leave it blank when the log should stand alone without a meal label.",children:[a.jsxs("div",{className:"mb-2 flex flex-wrap gap-2",children:[["Breakfast","Lunch","Dinner","Snack"].map(N=>a.jsx(G,{type:"button",size:"sm",variant:x.mealLabel===N?"primary":"secondary",onClick:()=>v({mealLabel:N}),children:N},N)),a.jsx(G,{type:"button",size:"sm",variant:"ghost",onClick:()=>v({mealLabel:""}),children:"Clear"})]}),a.jsx(C,{value:x.mealLabel,onChange:N=>v({mealLabel:N.target.value}),placeholder:"Breakfast, lunch, snack, dinner, or blank"})]}),a.jsx(y,{label:"Notes",labelHelp:"Use notes for context the numbers do not capture: hunger, cravings, gut comfort, energy, timing, place, or workout relationship.",children:a.jsx(Ae,{value:x.notes,onChange:N=>v({notes:N.target.value}),placeholder:"Energy, cravings, gut comfort, training effect..."})})]})}];return a.jsx(De,{open:e,onOpenChange:t,eyebrow:"Food log",title:j==="edit"?"Edit food":"Add food",description:"Search, inspect, scale, edit nutrition parameters, and save meal items.",value:n,onChange:r,steps:X,initialStepId:b,onSubmit:_e,submitLabel:j==="edit"?"Update meal":"Save meal",pending:u,pendingLabel:"Saving meal",resolveError:x=>x!=="search"?n.selectedItems.length===0?"Select at least one food before saving.":W:null,resolveContinueNudge:x=>x==="search"&&(i==null?void 0:i.status)==="success"&&n.selectedItems.length>0?"Meal draft is ready. Continue to review quantities.":null,draftPersistenceKey:`weight-loss-food-log.${j}.${h}`})}function Ia(e,t={}){return{loggedAt:e.loggedAt,dayKey:e.dayKey??t.dateKey??null,timeZone:e.timeZone??t.timeZone,mealLabel:ma(e.mealLabel),source:e.source??"search",confirmationState:"confirmed",notes:ma(e.notes),items:e.selectedItems.map(n=>{const r=be(n);return{foodId:Gn(n),name:n.food.name,brand:n.food.brand,quantity:Number(n.amount)||1,unit:n.unit,grams:r.grams,calories:r.calories,proteinGrams:r.proteinGrams,carbohydrateGrams:r.carbohydrateGrams,fatGrams:r.fatGrams,fiberGrams:r.fiberGrams,sugarGrams:r.sugarGrams,sodiumMg:r.sodiumMg,potassiumMg:r.potassiumMg,caffeineMg:r.caffeineMg,alcoholGrams:r.alcoholGrams,novaGroup:n.food.novaGroup,tags:n.food.tags,confidence:.9}})}}function ma(e,t=""){return typeof e=="string"?e:t}function Gn(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 An(e,t={}){return Ia(e,t)}function Dn(e){const t=Number(e);return Number.isFinite(t)?t:null}function _n({item:e,onChange:t}){const n=e.food,r=(s,l)=>t({[s]:Dn(l)});return a.jsxs("div",{className:"grid gap-3 rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-[var(--ui-ink-strong)]",children:["Food parameters",a.jsx(de,{label:`Explain editable food parameters for ${n.name}`,content:"These are the nutrient values for the base serving shown above. Changing them recalculates the eaten quantity and stores the corrected values in Forge."})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[a.jsx(y,{label:"Base label",labelHelp:"Human-readable denominator shown for the nutrition values, such as 100 g, 220 g, one burger, or one scoop.",children:a.jsx(C,{value:n.servingLabel??"",onChange:s=>t({servingLabel:s.target.value||null}),placeholder:"100 g"})}),a.jsx(y,{label:"Base grams",labelHelp:"Gram denominator for the base nutrition values. If kcal is per 220 g, enter 220. If kcal is per 100 g, enter 100.",children:a.jsx(C,{inputMode:"decimal",value:n.servingGrams??"",onChange:s=>r("servingGrams",s.target.value),placeholder:"100"})}),a.jsx(y,{label:"Food name",labelHelp:"Rename the item when the database result is too generic or wrong.",children:a.jsx(C,{value:n.name,onChange:s=>t({name:s.target.value})})}),a.jsx(y,{label:"Brand",labelHelp:"Optional brand or preparation source, useful when the same food has different nutrition.",children:a.jsx(C,{value:n.brand??"",onChange:s=>t({brand:s.target.value||null})})})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[a.jsx(y,{label:"kcal",labelHelp:"Kilocalories for the base amount above. Forge multiplies this by eaten grams divided by base grams, so 2 g of a 220 g base is not treated as 2 servings.",children:a.jsx(C,{inputMode:"decimal",value:n.calories??"",onChange:s=>r("calories",s.target.value)})}),a.jsx(y,{label:"Protein g",labelHelp:"Protein grams for the base amount above. This is scaled by the same gram ratio as calories.",children:a.jsx(C,{inputMode:"decimal",value:n.proteinGrams??"",onChange:s=>r("proteinGrams",s.target.value)})}),a.jsx(y,{label:"Carbs g",labelHelp:"Carbohydrate grams for the base amount above. Carbs are training fuel after protein and fat are allocated.",children:a.jsx(C,{inputMode:"decimal",value:n.carbohydrateGrams??"",onChange:s=>r("carbohydrateGrams",s.target.value)})}),a.jsx(y,{label:"Fat g",labelHelp:"Fat grams for the base amount above. Fat supports the practical floor and AMDR context in the plan.",children:a.jsx(C,{inputMode:"decimal",value:n.fatGrams??"",onChange:s=>r("fatGrams",s.target.value)})}),a.jsx(y,{label:"Fiber g",labelHelp:"Fiber grams for the base amount above. Forge compares this to the 14g per 1000 kcal planning target.",children:a.jsx(C,{inputMode:"decimal",value:n.fiberGrams??"",onChange:s=>r("fiberGrams",s.target.value)})}),a.jsx(y,{label:"Sugar g",labelHelp:"Sugar grams for the base amount above. Added sugar is tracked as a ceiling, not a goal.",children:a.jsx(C,{inputMode:"decimal",value:n.sugarGrams??"",onChange:s=>r("sugarGrams",s.target.value)})}),a.jsx(y,{label:"Sodium mg",labelHelp:"Sodium milligrams for the base amount above. Sodium affects daily ceiling, sport loss replacement, and water retention hypotheses.",children:a.jsx(C,{inputMode:"decimal",value:n.sodiumMg??"",onChange:s=>r("sodiumMg",s.target.value)})})]})]})}function En({food:e,onAdd:t}){return a.jsxs(U,{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(G,{type:"button",onClick:t,children:[a.jsx(Ve,{className:"size-4"}),"Add"]})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[a.jsx(F,{label:"Calories",value:o(e.calories)}),a.jsx(F,{label:"Protein",value:`${o(e.proteinGrams)}g`}),a.jsx(F,{label:"Carbs",value:`${o(e.carbohydrateGrams)}g`}),a.jsx(F,{label:"Fat",value:`${o(e.fatGrams)}g`}),a.jsx(F,{label:"Fiber",value:`${o(e.fiberGrams)}g`}),a.jsx(F,{label:"Sugar",value:`${o(e.sugarGrams)}g`}),a.jsx(F,{label:"Sodium",value:`${o(e.sodiumMg)}mg`}),a.jsx(F,{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(ct,{className:"size-4"}),"Base grams: ",o(ve(e)),". Adjust exact intake in the next step."]})]})}function be(e){const t=Number(e.amount)||0,n=ve(e.food),r=Ea(e),s=e.unit==="serving"||e.unit==="unit",l=t<=0?0:n!=null&&r!=null?r/n:s?t:null,g=c=>l!=null&&typeof c=="number"&&Number.isFinite(c)?Math.round(c*l*10)/10:null;return{grams:r,scale:l,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 Ke(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function $n(e){const t=be(e),n=[];return Ke(t.calories)||n.push("calories"),Ke(t.proteinGrams)||n.push("protein"),Ke(t.carbohydrateGrams)||n.push("carbs"),Ke(t.fatGrams)||n.push("fat"),n}function ha(e){const t=e.selectedItems.map(n=>({name:n.food.name,missing:$n(n)})).filter(n=>n.missing.length>0);return t.length===0?null:`Add complete nutrition before saving: ${t.map(n=>`${n.name} is missing ${n.missing.join(", ")}`).join("; ")}.`}function Tn(e){return e.reduce((t,n)=>{const r=be(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 pa(){return{weightKg:"",waistCm:"",bodyFatPercent:"",energy:"",hunger:"",cravings:"",bloating:"",facePuffiness:"",leanness:"",notes:""}}function In({open:e,onOpenChange:t,value:n,onChange:r,onSubmit:s,pending:l}){const g=[{id:"body",eyebrow:"Body",title:"Measurements",description:"Add weight and body measures when you have them. Empty fields are ignored.",render:(c,i)=>a.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[a.jsx(y,{label:"Weight kg",children:a.jsx(C,{inputMode:"decimal",value:c.weightKg,onChange:u=>i({weightKg:u.target.value})})}),a.jsx(y,{label:"Waist cm",children:a.jsx(C,{inputMode:"decimal",value:c.waistCm,onChange:u=>i({waistCm:u.target.value})})}),a.jsx(y,{label:"Body fat %",children:a.jsx(C,{inputMode:"decimal",value:c.bodyFatPercent,onChange:u=>i({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:(c,i)=>a.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[a.jsx(y,{label:"Energy 0-10",children:a.jsx(C,{inputMode:"decimal",value:c.energy,onChange:u=>i({energy:u.target.value})})}),a.jsx(y,{label:"Hunger 0-10",children:a.jsx(C,{inputMode:"decimal",value:c.hunger,onChange:u=>i({hunger:u.target.value})})}),a.jsx(y,{label:"Cravings 0-10",children:a.jsx(C,{inputMode:"decimal",value:c.cravings,onChange:u=>i({cravings:u.target.value})})}),a.jsx(y,{label:"Bloating 0-10",children:a.jsx(C,{inputMode:"decimal",value:c.bloating,onChange:u=>i({bloating:u.target.value})})}),a.jsx(y,{label:"Face puffiness 0-10",children:a.jsx(C,{inputMode:"decimal",value:c.facePuffiness,onChange:u=>i({facePuffiness:u.target.value})})}),a.jsx(y,{label:"Leanness 0-10",children:a.jsx(C,{inputMode:"decimal",value:c.leanness,onChange:u=>i({leanness:u.target.value})})})]})},{id:"notes",eyebrow:"Context",title:"Notes",description:"Capture anything that explains the signal.",render:(c,i)=>a.jsx(y,{label:"Notes",children:a.jsx(Ae,{value:c.notes,onChange:u=>i({notes:u.target.value}),placeholder:"Sleep, sodium, workout soreness, stressful day..."})})}];return a.jsx(De,{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:l,pendingLabel:"Saving check-in",draftPersistenceKey:"weight-loss-checkin"})}function Ln(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 Pn(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 Rn(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 Wn({open:e,onOpenChange:t,meals:n,onLogAgain:r,onEdit:s,onDelete:l,pending:g}){return a.jsx(De,{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(c=>a.jsxs(L,{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:Pn(c)}),a.jsxs("div",{className:"mt-1 text-xs text-[var(--ui-ink-faint)]",children:[c.loggedAt.slice(0,10)," ·"," ",Rn(c)||c.mealLabel||"No quantity recorded"]})]}),a.jsxs(E,{tone:"meta",children:[c.totals.calories.toFixed(0)," kcal"]})]}),a.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.jsx(G,{type:"button",size:"sm",variant:"secondary",onClick:()=>s(c),children:"Edit"}),a.jsx(G,{type:"button",size:"sm",variant:"ghost",pending:g,onClick:()=>l(c),children:"Delete"}),a.jsx(G,{type:"button",size:"sm",variant:"secondary",pending:g,onClick:()=>r(c),children:"Log again"})]})]},c.id))})}],onSubmit:async()=>t(!1),submitLabel:"Done"})}function Bn(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 Hn(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 zn(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 ${o(t.averageCalorieIntake)} kcal/day from ${n}.`;const r=`Recent average balance: intake ${o(t.averageCalorieIntake)} - TDEE ${o(t.estimatedTdeeKcal)} = ${q(t.estimatedDailyEnergyBalanceKcal)} kcal/day.`,s=t.restingEnergyCalories!=null&&t.activeBurnKcal!=null?`TDEE = formula resting baseline ${o(t.restingEnergyCalories)} + active burn ${o(t.activeBurnKcal)}.`:`TDEE is falling back to the configured plan estimate ${o(t.inferredTdee)}.`,l=t.energySourceConfidence==="healthkit_daily_active_energy"?`Active burn uses HealthKit daily active energy ${o(t.activeBurnKcal)}; workout and movement are evidence only.`:t.energySourceConfidence==="workout_movement_fallback"?`Active burn fallback = workout ${o(t.workoutEnergyKcal)} + movement ${o(t.movementCaloriesKcal)} = ${o(t.activeBurnKcal)}, so movement is not added again.`:"Active burn is not measured yet.";return`${r} ${s} ${l} Food window: ${n}. Negative means estimated deficit; this is not today's remaining calories.`}function qn(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",l=t.energySourceConfidence==="healthkit_daily_active_energy"?`active burn = HealthKit daily active energy average = ${o(t.activeBurnKcal)} kcal/day`:t.energySourceConfidence==="workout_movement_fallback"?`active burn = workout average ${o(t.workoutEnergyKcal)} + movement-trip average ${o(t.movementCaloriesKcal)} = ${o(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 ${o(t.restingEnergyCalories)} + active burn average ${o(t.activeBurnKcal)} = ${o(t.estimatedTdeeKcal)} kcal/day.`:`TDEE = ${o(t.estimatedTdeeKcal)} kcal/day from the configured plan because complete resting + active energy is not available.`,c=t.estimatedTdeeKcal!=null?`Energy gap = average logged intake - TDEE = ${o(t.averageCalorieIntake)} - ${o(t.estimatedTdeeKcal)} = ${q(t.estimatedDailyEnergyBalanceKcal)} kcal/day.`:"Energy gap cannot be computed until Forge has either measured expenditure or an inferred TDEE.",i=t.energySourceConfidence==="healthkit_daily_active_energy"?`selected active burn = HealthKit daily active energy average = ${o(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 ${o(t.workoutEnergyKcal)} + movement-trip average ${o(t.movementCaloriesKcal)} = ${o(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 ${o(t.activeBurnKcal)} = HealthKit daily active energy average; TDEE ${o(t.estimatedTdeeKcal)} = formula resting baseline ${o(t.restingEnergyCalories)} + active burn ${o(t.activeBurnKcal)}; energy gap ${q(t.estimatedDailyEnergyBalanceKcal)} = intake ${o(t.averageCalorieIntake)} - TDEE ${o(t.estimatedTdeeKcal)}.`:t.energySourceConfidence==="workout_movement_fallback"?`Arithmetic shown here: active burn ${o(t.activeBurnKcal)} = workout ${o(t.workoutEnergyKcal)} + movement ${o(t.movementCaloriesKcal)}; TDEE ${o(t.estimatedTdeeKcal)} = formula resting baseline ${o(t.restingEnergyCalories)} + active burn ${o(t.activeBurnKcal)}; energy gap ${q(t.estimatedDailyEnergyBalanceKcal)} = intake ${o(t.averageCalorieIntake)} - TDEE ${o(t.estimatedTdeeKcal)}.`:`Arithmetic shown here: TDEE ${o(t.estimatedTdeeKcal)} = formula resting baseline ${o(t.restingEnergyCalories)} + active burn ${o(t.activeBurnKcal)}; energy gap ${q(t.estimatedDailyEnergyBalanceKcal)} = intake ${o(t.averageCalorieIntake)} - TDEE ${o(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.",f=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.",K=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.",w=`Today is separate: today's target = baseline plan target plus the day-specific active adjustment. Today active evidence currently uses ${La(t.todayActiveCaloriesSource)}: ${o(t.todayActiveCaloriesKcal)} kcal. Default active calories: ${o(t.baselineActiveCaloriesKcal)} kcal. Eat-back fraction ${o(t.activityEatBackFraction*100,0)}%; target adjustment ${q(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.`,j=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:"})," ",c]}),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:"})," ",i]}),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 ",o(t.averageCalorieIntake)," kcal/day; TDEE"," ",o(t.estimatedTdeeKcal)," kcal/day; formula resting"," ",o(t.restingEnergyCalories)," kcal/day; active burn"," ",o(t.activeBurnKcal)," kcal/day; workout"," ",o(t.workoutEnergyKcal)," kcal/day; movement"," ",o(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:"})," ",j]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Food window:"})," ",f," Current denominator: ",s,"."]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Expenditure:"})," ",g," ",l,". 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:"})," ",Bn(t.energySourceConfidence)," across"," ",t.evidenceDays," expenditure evidence day",t.evidenceDays===1?"":"s"," ending the selected day (",r,"). Available streams: ",Hn(e),"."," ",K]}),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:"})," ",w]})]})}function On(e){const t=q(e);return t==="n/a"?t:`${t} kcal/d`}function La(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 xa(e){return`${e>=0?"+":""}${e.toFixed(0)} kcal`}function Un(e){return e>=0?`${e.toFixed(0)} kcal left`:`${Math.abs(e).toFixed(0)} kcal over`}function fa(e){return e.trim()===""?"0":e}function ba(e,t,n){const r=e.energyModel.baselineActiveCaloriesKcal??e.energyModel.todayActiveCaloriesKcal??0,s=e.energyModel.activityEatBackFraction??0,l=t-r,g=Math.round(l*s),c=e.energyModel.todayTargetAdjustmentKcal??0,i=e.todayLedger.plannedTargetCalories??e.todayLedger.targetCalories-c,u=Math.max(0,Math.round(i+g)),f=Math.round(e.todayLedger.totals.calories-u),K=Math.round(u-e.todayLedger.totals.calories),w=Math.max(0,l),j=Math.round(w*s);return{...e,summary:{...e.summary,targetCalories:u,todayCalorieDelta:f,remainingCalories:K},todayLedger:{...e.todayLedger,plannedTargetCalories:i,targetCalories:u,activeAdjustmentCalories:g,activeCaloriesSource:"user_override",calorieDelta:f,remainingCalories:K},energyModel:{...e.energyModel,todayActiveCaloriesKcal:t,todayActiveCaloriesSource:"user_override",todayTargetAdjustmentKcal:g,todayActiveDeltaKcal:Math.round(l),todayActiveSurplusKcal:Math.round(w),todayActivityBufferKcal:j,todayActiveOverride:n}}}function Qn(e){const[t,n,r]=e.split("-").map(Number),s=new Date(t,n-1,r),l=new Date(t,n-1,r+1);return{dayStartAt:s.toISOString(),dayEndAt:l.toISOString()}}function va(e,t){const[n,r,s]=e.split("-").map(Number);return Se(new Date(n,r-1,s+t))}function Vn(e){const[t,n,r]=e.split("-").map(Number);return new Intl.DateTimeFormat(void 0,{weekday:"long",month:"short",day:"numeric"}).format(new Date(t,n-1,r,12))}function Zn(){const e=new Date,t=new Date(e);return t.setHours(24,0,2,0),Math.max(1e3,t.getTime()-e.getTime())}function lr(){const e=vt(),t=xt(),n=e.selectedUserIds,r=M.useMemo(()=>Dt(),[]),s=Se(),[l,g]=M.useState(()=>Se()),c=M.useMemo(()=>Qn(l),[l]),i=M.useMemo(()=>["forge-weight-loss-view",l,r,...n],[l,r,n]),u=l===s,[f,K]=M.useState(!1),[w,j]=M.useState(!1),[h,b]=M.useState(!1),[k,T]=M.useState(!1),[P,R]=M.useState(!1),[ae,Q]=M.useState(null),[te,V]=M.useState(null),[B,H]=M.useState(""),[ne,re]=M.useState(null),[se,J]=M.useState(null),[ue,ye]=M.useState("search"),[_e,W]=M.useState(null),[je,ge]=M.useState(void 0),[me,X]=M.useState(()=>Fe()),[x,v]=M.useState(()=>pa()),N=ft({queryKey:i,queryFn:async()=>(await At(n,{dateKey:l,...c,timeZone:r})).weightLoss}),$=N.data;M.useEffect(()=>{const d=()=>{u&&g(D=>{const he=Se();return he===D?D:he})},m=window.setTimeout(d,Zn());return window.addEventListener("focus",d),document.addEventListener("visibilitychange",d),()=>{window.clearTimeout(m),window.removeEventListener("focus",d),document.removeEventListener("visibilitychange",d)}},[l,u]),M.useEffect(()=>{!$||w||f||mn($)||(j(!0),re(qe($)),Q(`Forge needs the missing profile fields before the calorie and macro plan can be trusted.
|
|
3
3
|
|
|
4
4
|
- Confirm age, height, current weight, objective, weekly rate, and active calories.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{j as a,aC as j,r as w}from"./vendor-
|
|
1
|
+
import{j as a,aC as j,r as w}from"./vendor-y_uz1Wft.js";import{c as u,b7 as N,ch as $}from"./index-Dj8q65se.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
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 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]",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-","")}),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};
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{aJ as Be,b7 as Ke,b_ as Qe,bZ as
|
|
1
|
+
import{aJ as Be,b7 as Ke,b_ as Qe,bZ as De,r as d,j as e,cx as Ve,cy as qe,cP as He,cs as Ue,c5 as Je,aU as Xe,aR as Ye,cg as Ze,dK as Ge,dL as ea,aK as we,bH as aa}from"./vendor-y_uz1Wft.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-CdEDMtXF.js";import{j as sa,i as X,k as ta}from"./state-DWw8Jay_.js";import{E as F}from"./entity-link-multiselect-DZ_jAjs4.js";import{d as ra,j 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,ad as ve,eH as oa,cu as da,bw as ca,eI as ua,eJ as pa}from"./index-Dj8q65se.js";import{W as xa}from"./wiki-article-markdown-um6gpmGQ.js";import"./use-anchored-overlay-position-Cracjgo6.js";import"./motion-DeJZhOSA.js";import"./board-CGgOvBP9.js";import"./forms-DhEGHkFR.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 max-w-[min(14rem,calc(100vw-2rem))] -translate-x-1/2 whitespace-normal rounded-[12px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-popover)] px-2.5 py-1.5 text-center text-[11px] font-medium text-[var(--ui-ink-medium)] opacity-0 shadow-[var(--ui-shadow-floating)] transition [overflow-wrap:anywhere] 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=Ke(),{pageId:m}=Qe(),[A,Oe]=
|
|
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 max-w-[min(14rem,calc(100vw-2rem))] -translate-x-1/2 whitespace-normal rounded-[12px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-popover)] px-2.5 py-1.5 text-center text-[11px] font-medium text-[var(--ui-ink-medium)] opacity-0 shadow-[var(--ui-shadow-floating)] transition [overflow-wrap:anywhere] 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=Ke(),{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,K]=d.useState(!1),[Q,Ee]=d.useState(!1),[D,V]=d.useState(""),[q,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(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=Z.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?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: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(De,{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:()=>K(!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(""),D(""),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:q,onChange:a=>D(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),D("")},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: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(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",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:()=>K(!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(""),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: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=>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"}
|