forge-openclaw-plugin 0.3.13 → 0.3.14
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-BFjWjRIM.js → action-bar-B9MYlps2.js} +1 -1
- package/dist/assets/{activity-page-D-6yBWuZ.js → activity-page-DbzbChcE.js} +1 -1
- package/dist/assets/{ai-surface-workspace-BEfo9bRO.js → ai-surface-workspace-CF0257Hs.js} +1 -1
- package/dist/assets/{atlas-panel-BfMyJXxQ.js → atlas-panel-CO3RYAKn.js} +1 -1
- package/dist/assets/{calendar-page-D4tQNJ2V.js → calendar-page-BuuHKEHC.js} +1 -1
- package/dist/assets/{calendar-rules-C-6O_uGU.js → calendar-rules-DKftgNx5.js} +1 -1
- package/dist/assets/{calendar-week-toolbar-_NzeKsYx.js → calendar-week-toolbar-ChIpkT-G.js} +1 -1
- package/dist/assets/{companion-sync-lab-page-D1Oqsf6M.js → companion-sync-lab-page-BZRX4Btw.js} +1 -1
- package/dist/assets/{daily-metrics-dashboard-DtE3pVOl.js → daily-metrics-dashboard-CXDsaAQd.js} +1 -1
- package/dist/assets/{define-workbench-box-D-32C8nM.js → define-workbench-box-CpG0Zb1L.js} +1 -1
- package/dist/assets/{entity-link-multiselect-DcCvkesQ.js → entity-link-multiselect-Dl4rZqdg.js} +1 -1
- package/dist/assets/{entity-note-count-link-Cjsk5oT2.js → entity-note-count-link-Bs1aKYyD.js} +1 -1
- package/dist/assets/{entity-notes-surface-DQQPLjxd.js → entity-notes-surface-B56XSw7M.js} +1 -1
- package/dist/assets/{execution-board-agWQbN-y.js → execution-board-D66C_ikW.js} +1 -1
- package/dist/assets/{faceted-token-search-DldM3-ru.js → faceted-token-search-Dg2rjknH.js} +1 -1
- package/dist/assets/{flagship-signal-deck-BlLYW9Kz.js → flagship-signal-deck-C6KVPhmM.js} +1 -1
- package/dist/assets/{floating-action-menu-D9-psbha.js → floating-action-menu-DAFAEBcA.js} +1 -1
- package/dist/assets/{generic-node-view-CcepUVhP.js → generic-node-view-C6DK5hJ6.js} +1 -1
- package/dist/assets/{goal-detail-page-DP1n5-Hk.js → goal-detail-page-CC4VXud6.js} +1 -1
- package/dist/assets/{goal-dialog-Oxx8WqbZ.js → goal-dialog-15hD8EBp.js} +1 -1
- package/dist/assets/{goals-page-CUt1a4Y2.js → goals-page-CQ2lJMzI.js} +1 -1
- package/dist/assets/{habits-page-5REbWAlo.js → habits-page-a7KVPaQp.js} +1 -1
- package/dist/assets/{health-boxes-sHNML3tm.js → health-boxes-DqgvIYoL.js} +1 -1
- package/dist/assets/index-ClJbJhca.css +1 -0
- package/dist/assets/index-FpGANF9S.js +2 -0
- package/dist/assets/{inline-note-fields-Bql_KfR9.js → inline-note-fields-COgzxr_7.js} +1 -1
- package/dist/assets/{insight-flow-dialog-CN-CMSB7.js → insight-flow-dialog-Dmb6NSGp.js} +1 -1
- package/dist/assets/{insights-page-B1u6ONtQ.js → insights-page-OnqR4cYI.js} +1 -1
- package/dist/assets/{kanban-boxes-DB1kuUlY.js → kanban-boxes-BWUzntCV.js} +1 -1
- package/dist/assets/{kanban-page-BBW9_vMu.js → kanban-page-BI16Gzp_.js} +1 -1
- package/dist/assets/{knowledge-graph-page-CoJaydZb.js → knowledge-graph-page-DxEBaEke.js} +1 -1
- package/dist/assets/{life-force-page-DBYbA1GF.js → life-force-page-CDEXEQai.js} +1 -1
- package/dist/assets/{life-force-workspace-BiD9xOEt.js → life-force-workspace-C7UOnJEf.js} +1 -1
- package/dist/assets/{metric-tile-CuP9DOYm.js → metric-tile-boeHB1R1.js} +1 -1
- package/dist/assets/{movement-boxes-DZg_qPPg.js → movement-boxes-BUSqaTL2.js} +1 -1
- package/dist/assets/{movement-page-CmwsQGR_.js → movement-page-DcbO0497.js} +1 -1
- package/dist/assets/note-markdown-DXXI3W3V.js +3 -0
- package/dist/assets/{note-tags-input-C_x5WdK5.js → note-tags-input-CYh3TVW2.js} +1 -1
- package/dist/assets/{notes-boxes-BEFlp9yd.js → notes-boxes-CMJXX2K0.js} +1 -1
- package/dist/assets/{notes-page-B6Vl-GPf.js → notes-page-DvHMcQey.js} +1 -1
- package/dist/assets/{open-in-graph-button-C-bJekoH.js → open-in-graph-button-4UYrp1XP.js} +1 -1
- package/dist/assets/{orbit-map-DHeTM15g.js → orbit-map-BwK7sDaC.js} +1 -1
- package/dist/assets/{overview-page-BRWje1F9.js → overview-page-Z5vaUTm3.js} +1 -1
- package/dist/assets/{page-hero-8bITsx_x.js → page-hero-DvrM83_C.js} +1 -1
- package/dist/assets/{pill-cluster-XQjm-wPc.js → pill-cluster-DYI3Ibj8.js} +1 -1
- package/dist/assets/{preference-entity-handoff-button-DwYF_5i3.js → preference-entity-handoff-button-C2ATjvws.js} +1 -1
- package/dist/assets/{preferences-page-C7DBPpNb.js → preferences-page-BAexXHye.js} +1 -1
- package/dist/assets/{project-collections-mtxanSMf.js → project-collections-B9nr-Ts-.js} +1 -1
- package/dist/assets/{project-detail-page-BT87Goqc.js → project-detail-page-B9PqyPu9.js} +1 -1
- package/dist/assets/{project-dialog-DnZe757y.js → project-dialog-CBA-D65n.js} +1 -1
- package/dist/assets/{project-management-hierarchy-page-B3R2lNFI.js → project-management-hierarchy-page-DXK14jn0.js} +1 -1
- package/dist/assets/{project-management-section-nav-DyBWxHbe.js → project-management-section-nav-DJ3QKCtr.js} +1 -1
- package/dist/assets/{projects-boxes-CxZj3P29.js → projects-boxes-iBu_PRqe.js} +1 -1
- package/dist/assets/{projects-page-Bec11c0x.js → projects-page-CdAk-ByT.js} +1 -1
- package/dist/assets/{psyche-behaviors-page-DWRpYvl1.js → psyche-behaviors-page-CbhhTfU2.js} +1 -1
- package/dist/assets/{psyche-flashcards-page-CX4rcsXZ.js → psyche-flashcards-page-DQaw_vUQ.js} +1 -1
- package/dist/assets/{psyche-goal-map-page-Y6b3lCvV.js → psyche-goal-map-page-C-ZTVOEP.js} +1 -1
- package/dist/assets/{psyche-graph-CQuCWKIp.js → psyche-graph-DYzeClxn.js} +1 -1
- package/dist/assets/{psyche-metrics-page-DadDJOnm.js → psyche-metrics-page-C9hKn10A.js} +1 -1
- package/dist/assets/{psyche-mode-guide-page-B1nz0uCg.js → psyche-mode-guide-page-CR8e984W.js} +1 -1
- package/dist/assets/{psyche-modes-page-i3uSuhKA.js → psyche-modes-page-lQdpAcY3.js} +1 -1
- package/dist/assets/{psyche-page-Y_s-BE2m.js → psyche-page-CTdIDkw9.js} +1 -1
- package/dist/assets/{psyche-patterns-page-DaaOLIlN.js → psyche-patterns-page-Drgm-f7I.js} +1 -1
- package/dist/assets/{psyche-questionnaire-builder-page-CuF7rXOv.js → psyche-questionnaire-builder-page-gRwdGXde.js} +1 -1
- package/dist/assets/{psyche-questionnaire-detail-page-BfFEMkRY.js → psyche-questionnaire-detail-page-CIP9b2UI.js} +1 -1
- package/dist/assets/{psyche-questionnaire-run-detail-page-BoQTvd7Q.js → psyche-questionnaire-run-detail-page-SYndwtF3.js} +1 -1
- package/dist/assets/{psyche-questionnaire-run-page-C0qKiNZN.js → psyche-questionnaire-run-page-CXiJyd5i.js} +1 -1
- package/dist/assets/{psyche-questionnaires-page-B6hfD448.js → psyche-questionnaires-page-CFPKwA3O.js} +1 -1
- package/dist/assets/{psyche-report-detail-page-BlFL8moM.js → psyche-report-detail-page-dU30a2WE.js} +1 -1
- package/dist/assets/{psyche-reports-page-DAAcYENp.js → psyche-reports-page-Cn0EBndy.js} +1 -1
- package/dist/assets/{psyche-schemas-beliefs-page-CsxKSrKM.js → psyche-schemas-beliefs-page-Bab4xSWv.js} +1 -1
- package/dist/assets/{psyche-screen-time-page-n4b0e58x.js → psyche-screen-time-page-lIe6GQxJ.js} +1 -1
- package/dist/assets/{psyche-self-observation-page-BaxEQ2-3.js → psyche-self-observation-page-BTE3KfIl.js} +1 -1
- package/dist/assets/{psyche-values-page-DTv5NMSU.js → psyche-values-page-DclBZ9xw.js} +1 -1
- package/dist/assets/question-flow-dialog-Ded2E85L.js +2 -0
- package/dist/assets/{report-chain-fields-D132-EMh.js → report-chain-fields-DY640iqL.js} +1 -1
- package/dist/assets/{rewards-page-C533lVP-.js → rewards-page-FxUXB76B.js} +1 -1
- package/dist/assets/{scheduling-rules-editor-CDpontGp.js → scheduling-rules-editor-jakFfxqF.js} +1 -1
- package/dist/assets/{schema-badge-B3DiMnjB.js → schema-badge-30B5syHA.js} +1 -1
- package/dist/assets/{schemas-CH1_ngUX.js → schemas-Db29G8NU.js} +1 -1
- package/dist/assets/{select-menu-BOF-k4Ln.js → select-menu-BF2zI3RW.js} +1 -1
- package/dist/assets/{settings-agents-page-B5OQtlZX.js → settings-agents-page-Bh-Bv6FQ.js} +1 -1
- package/dist/assets/{settings-bin-page-D_bk3Kcu.js → settings-bin-page-DT8JJero.js} +1 -1
- package/dist/assets/{settings-calendar-page-PuSj9_kM.js → settings-calendar-page-BA4_Qqiu.js} +3 -3
- package/dist/assets/{settings-data-page-EwFMaeq6.js → settings-data-page-K4kpmQJY.js} +1 -1
- package/dist/assets/{settings-logs-page-BKkse0DX.js → settings-logs-page-DkuNPAZo.js} +1 -1
- package/dist/assets/{settings-mobile-page-BrIVmdeB.js → settings-mobile-page-4pCNwD91.js} +1 -1
- package/dist/assets/{settings-models-page-Mg84D_0K.js → settings-models-page-CZHG3t7W.js} +1 -1
- package/dist/assets/{settings-page-D-kul92f.js → settings-page-B_Be0vOY.js} +1 -1
- package/dist/assets/{settings-rewards-page-waNyCcX_.js → settings-rewards-page-C6nFTWJu.js} +1 -1
- package/dist/assets/{settings-section-nav-BmJWnrYk.js → settings-section-nav-Lo-VKCfZ.js} +1 -1
- package/dist/assets/{settings-users-page-DBgC6y56.js → settings-users-page-CVzNp4-m.js} +1 -1
- package/dist/assets/{settings-wiki-page-CM0te9dI.js → settings-wiki-page-DXM--7BB.js} +1 -1
- package/dist/assets/sleep-page-DvPdZMKx.js +1 -0
- package/dist/assets/{sports-page-eg5Rfc_E.js → sports-page-DjuZlOur.js} +1 -1
- package/dist/assets/{strategies-page-D4AqvFNW.js → strategies-page-PE1IlatS.js} +1 -1
- package/dist/assets/{strategy-detail-page-BlYVkXaW.js → strategy-detail-page-C4KiEGCI.js} +1 -1
- package/dist/assets/{strategy-dialog-FO9Oa0dB.js → strategy-dialog-Cwf7Y3P5.js} +1 -1
- package/dist/assets/surface-ubuOfukq.js +1 -0
- package/dist/assets/{task-detail-page-Dy-aRyY6.js → task-detail-page-B3SMFZQ3.js} +1 -1
- package/dist/assets/{task-dialog-DrA9pba7.js → task-dialog-CI_Fy_FW.js} +1 -1
- package/dist/assets/{timebox-planning-dialog-C_gnfxFx.js → timebox-planning-dialog-BtFuVoA1.js} +1 -1
- package/dist/assets/{today-boxes-BFOws_iC.js → today-boxes-CYuxSkZf.js} +1 -1
- package/dist/assets/{today-page-BoPj6a6q.js → today-page-CHGpLEZ3.js} +1 -1
- package/dist/assets/{training-load-page-DGU40Zfl.js → training-load-page-GZJF-Yy5.js} +1 -1
- package/dist/assets/{user-badge-CZWtYeMw.js → user-badge-ByhC6bMU.js} +1 -1
- package/dist/assets/{utility-widgets-B3wWGxQc.js → utility-widgets-ilORjDmg.js} +1 -1
- package/dist/assets/{vitals-page-BXRZEP_8.js → vitals-page-mdEqIm_9.js} +1 -1
- package/dist/assets/{weekly-review-page-D5cebA5x.js → weekly-review-page-C8W-yg5r.js} +1 -1
- package/dist/assets/weight-loss-page-BApTknCn.js +5 -0
- package/dist/assets/{wiki-article-markdown-CvaCjg_t.js → wiki-article-markdown-DBccllQg.js} +1 -1
- package/dist/assets/{wiki-editor-page-Dco79SLY.js → wiki-editor-page-BfRfH1O3.js} +2 -2
- package/dist/assets/{wiki-ingest-history-page-uvKRkRDF.js → wiki-ingest-history-page-C-6H3MU6.js} +1 -1
- package/dist/assets/{wiki-ingest-modal-BW6AJPea.js → wiki-ingest-modal-DnlhByD_.js} +1 -1
- package/dist/assets/{wiki-page-BIL5zMqv.js → wiki-page-DPZ55e3x.js} +1 -1
- package/dist/assets/{workbench-flow-page-Dx_nq8R_.js → workbench-flow-page-_-NKIx5R.js} +1 -1
- package/dist/assets/{workbench-page-BJnt_Zzf.js → workbench-page-NIAzggwX.js} +1 -1
- package/dist/assets/{workout-detail-page-CKgqyB-y.js → workout-detail-page-3fxr6HL4.js} +1 -1
- package/dist/index.html +2 -2
- package/dist/server/server/src/app.js +8 -4
- package/dist/server/server/src/health-weight-loss.js +321 -14
- package/dist/server/server/src/managers/platform/openai-responses-provider.js +2 -2
- package/dist/server/server/src/openapi.js +26 -3
- package/dist/server/server/src/repositories/ai-connectors.js +1 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/skills/forge-openclaw/SKILL.md +22 -0
- package/skills/forge-openclaw/entity_conversation_playbooks.md +17 -0
- package/skills/forge-openclaw/psyche_entity_playbooks.md +7 -0
- package/dist/assets/index-CQ5r7ZUz.js +0 -2
- package/dist/assets/index-FxgNSuZX.css +0 -1
- package/dist/assets/note-markdown-B82ncnFt.js +0 -3
- package/dist/assets/question-flow-dialog-CskCt5NZ.js +0 -2
- package/dist/assets/sleep-page-C_krRE59.js +0 -1
- package/dist/assets/surface-MVeeZGKB.js +0 -1
- package/dist/assets/weight-loss-page-BuUdFh9z.js +0 -5
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{j as r,r as w}from"./vendor-BwL6m4SE.js";import{c as x,c8 as b,a_ as $}from"./index-CQ5r7ZUz.js";function m(d,s){const i=[],e=/(!?\[\[([^\]]+)\]\]|\[([^\]]+)\]\(([^)]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|\*([^*]+)\*)/g;let l=0,n=null,a=0;for(;(n=e.exec(d))!==null;){if(n.index>l&&(i.push(r.jsx(w.Fragment,{children:d.slice(l,n.index)},`${s}-text-${a}`)),a+=1),n[1]&&n[2]){const o=n[2].trim(),t=n[1].startsWith("!"),c=o.indexOf("|"),h=c>=0?o.slice(0,c).trim():o,p=c>=0?o.slice(c+1).trim():h;if(h.toLowerCase().startsWith("forge:")){const[,u,g]=h.split(":"),f=u&&g?$(u,g):null,v=f?b(f):null;i.push(v?r.jsxs("a",{href:v,className:"inline-flex max-w-full items-center gap-1 rounded-full border border-[var(--warning)]/20 bg-[var(--ui-warning-soft)] px-2 py-0.5 text-[0.9em] text-[color-mix(in_srgb,var(--warning)_78%,var(--ui-ink-strong)_22%)] transition hover:bg-[var(--ui-surface-3)]",children:[r.jsx("span",{className:"shrink-0 text-[0.72em] uppercase tracking-[0.14em] text-[var(--ui-ink-faint)]",children:"Forge"}),r.jsx("span",{className:"min-w-0 break-words [overflow-wrap:anywhere]",children:p})]},`${s}-forge-${a}`):r.jsx("span",{className:"inline-flex max-w-full items-center gap-1 rounded-full bg-[var(--ui-surface-2)] px-2 py-0.5 text-[0.9em] text-[var(--ui-ink-soft)]",children:r.jsx("span",{className:"min-w-0 break-words [overflow-wrap:anywhere]",children:p})},`${s}-forge-${a}`))}else{const u=b(`/wiki/page/${encodeURIComponent(h)}`);i.push(r.jsxs("a",{href:u,className:x("inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[0.9em] transition",t?"border border-[var(--info)]/20 bg-[var(--ui-info-soft)] text-[color-mix(in_srgb,var(--info)_78%,var(--ui-ink-strong)_22%)] hover:bg-[var(--ui-surface-3)]":"bg-[var(--ui-surface-2)] text-[var(--secondary)] hover:bg-[var(--ui-surface-3)]"),children:[t?r.jsx("span",{className:"shrink-0 text-[0.72em] uppercase tracking-[0.14em] text-[var(--ui-ink-faint)]",children:"Embed"}):null,r.jsx("span",{className:"min-w-0 break-words [overflow-wrap:anywhere]",children:p})]},`${s}-wiki-${a}`))}}else if(n[3]&&n[4]){const o=n[4].trim(),t=/^https?:\/\//i.test(o);i.push(r.jsx("a",{href:o,className:"break-words text-[var(--secondary)] underline decoration-current/35 underline-offset-4 transition hover:text-[var(--ui-ink-strong)] [overflow-wrap:anywhere]",target:t?"_blank":void 0,rel:t?"noreferrer":void 0,children:n[3]},`${s}-link-${a}`))}else n[5]?i.push(r.jsx("code",{className:"rounded bg-[var(--ui-surface-2)] px-1.5 py-0.5 text-[0.92em] text-[var(--ui-ink-strong)] [overflow-wrap:anywhere]",children:n[5]},`${s}-code-${a}`)):n[6]?i.push(r.jsx("strong",{className:"font-semibold text-[var(--ui-ink-strong)]",children:n[6]},`${s}-strong-${a}`)):n[7]&&i.push(r.jsx("em",{className:"italic text-[var(--ui-ink-medium)]",children:n[7]},`${s}-em-${a}`));l=e.lastIndex,a+=1}return l<d.length&&i.push(r.jsx(w.Fragment,{children:d.slice(l)},`${s}-tail-${a}`)),i}function j(d){const s=d.replace(/\r/g,"").split(`
|
|
2
|
-
`),i=[];let e=0;for(;e<s.length;){const l=s[e]??"",n=l.trim();if(!n){e+=1;continue}if(n.startsWith("```")){const t=[];for(e+=1;e<s.length&&!(s[e]??"").trim().startsWith("```");)t.push(s[e]??""),e+=1;e+=1,i.push(r.jsx("pre",{className:"max-w-full overflow-x-auto rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-3 text-xs leading-6 text-[var(--ui-ink-strong)]",children:r.jsx("code",{className:"block min-w-0 whitespace-pre",children:t.join(`
|
|
3
|
-
`)})},`code-${e}`));continue}const a=l.match(/^(#{1,6})\s+(.*)$/);if(a){const t=a[1].length,c=t===1?"text-xl":t===2?"text-lg":t===3?"text-base":"text-sm";i.push(r.jsx("div",{className:x("font-semibold text-[var(--ui-ink-strong)]",c),children:m(a[2],`heading-${e}`)},`heading-${e}`)),e+=1;continue}if(/^>\s?/.test(l)){const t=[];for(;e<s.length&&/^>\s?/.test(s[e]??"");)t.push((s[e]??"").replace(/^>\s?/,"")),e+=1;i.push(r.jsx("blockquote",{className:"border-l-2 border-[var(--secondary)]/50 pl-4 text-sm leading-7 text-[var(--ui-ink-soft)]",children:m(t.join(" "),`quote-${e}`)},`quote-${e}`));continue}if(/^[-*+]\s+/.test(l)||/^\d+\.\s+/.test(l)){const t=/^\d+\.\s+/.test(l),c=[];for(;e<s.length&&(/^[-*+]\s+/.test(s[e]??"")||/^\d+\.\s+/.test(s[e]??""));)c.push((s[e]??"").replace(/^[-*+]\s+/,"").replace(/^\d+\.\s+/,"")),e+=1;const h=t?"ol":"ul";i.push(r.jsx(h,{className:x("space-y-1 pl-5 text-sm leading-7 text-[var(--ui-ink-soft)]",t?"list-decimal":"list-disc"),children:c.map((p,u)=>r.jsx("li",{children:m(p,`list-${e}-${u}`)},`item-${e}-${u}`))},`list-${e}`));continue}const o=[];for(;e<s.length;){const t=s[e]??"";if(!t.trim()||t.trim().startsWith("```")||/^#{1,6}\s+/.test(t)||/^>\s?/.test(t)||/^[-*+]\s+/.test(t)||/^\d+\.\s+/.test(t))break;o.push(t.trim()),e+=1}i.push(r.jsx("p",{className:"text-sm leading-7 text-[var(--ui-ink-soft)]",children:m(o.join(" "),`paragraph-${e}`)},`paragraph-${e}`))}return i}function y({markdown:d,className:s}){return r.jsx("div",{className:x("grid gap-3",s),children:j(d)})}export{y as N};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{r as o,j as e,cL as P,bW as K,bG as ee}from"./vendor-BwL6m4SE.js";import{R as te,P as ne,O as re,C as se,T as ae,D as ie,a as T}from"./ui-B9TWEtCx.js";import{u as le,aC as ce,B as b,c as S,a4 as oe,a3 as de}from"./index-CQ5r7ZUz.js";import{m as z,A as ue}from"./motion-DcgUnXhY.js";const $="(max-width: 1023px)",me="forge.question-flow-draft",W=1,fe=1e3;function xe({open:t,wasOpen:i,initialStepId:n,previousInitialStepId:r,currentStepIndex:s,steps:l}){if(!t)return 0;const c=()=>{if(!n)return 0;const g=l.findIndex(N=>N.id===n);return g>=0?g:0};return!i||r!==n?c():l.length===0?0:s>=l.length?Math.max(0,l.length-1):s<0?0:s}function pe(t){const i=t.split(/\n\s*\n/g).map(n=>n.split(`
|
|
2
|
-
`).map(r=>r.trim()).filter(r=>r.length>0)).filter(n=>n.length>0);return i.length===0?null:e.jsx("div",{className:"grid gap-2",children:i.map((n,r)=>{const s=n.filter(c=>c.startsWith("- ")),l=n.filter(c=>!c.startsWith("- "));return e.jsxs("div",{className:"grid gap-2",children:[l.map((c,f)=>e.jsx("p",{children:c},`${r}-${c}-${f}`)),s.length>0?e.jsx("ul",{className:"grid list-disc gap-1 pl-5",children:s.map((c,f)=>e.jsx("li",{children:c.slice(2)},`${r}-${c}-${f}`))}):null]},`section-${r}`)})})}function he(){const[t,i]=o.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia($).matches);return o.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia($),r=s=>{i(s.matches)};return i(n.matches),typeof n.addEventListener=="function"?(n.addEventListener("change",r),()=>n.removeEventListener("change",r)):(n.addListener(r),()=>n.removeListener(r))},[]),t}function j(){return typeof window<"u"&&typeof window.localStorage<"u"}function O(t){return`${me}.${t}`}function B(t){try{return JSON.stringify(t)}catch{return null}}function we(t){if(!j())return null;try{const i=window.localStorage.getItem(O(t));if(!i)return null;const n=JSON.parse(i);return n.version!==W||typeof n.baseline!="string"||typeof n.draft!="string"?null:n}catch{return null}}function ge(t,i){if(j())try{window.localStorage.setItem(O(t),JSON.stringify(i))}catch{}}function U(t){if(j())try{window.localStorage.removeItem(O(t))}catch{}}function ye({label:t,description:i,labelHelp:n,hint:r,error:s,children:l}){return e.jsxs("label",{className:"grid min-w-0 max-w-full gap-2",children:[e.jsxs("span",{className:"flex min-w-0 max-w-full items-center gap-2 text-sm font-medium text-[var(--ui-ink-strong)]",children:[e.jsx("span",{className:"min-w-0 break-words",children:t}),n?e.jsx(oe,{content:n,label:`Explain ${t}`}):null]}),i?e.jsx("span",{className:"min-w-0 break-words text-sm leading-6 text-[var(--ui-ink-soft)]",children:i}):null,l,r?e.jsx(de,{children:r}):null,s?e.jsx("span",{className:"text-sm text-rose-300",children:s}):null]})}function ke({options:t,value:i,onChange:n,columns:r=2}){return e.jsx("div",{className:S("grid min-w-0 max-w-full gap-3",r===3?"md:grid-cols-3":"md:grid-cols-2"),children:t.map(s=>{const l=s.value===i;return e.jsxs("button",{type:"button",className:S("min-w-0 max-w-full overflow-hidden rounded-[22px] border px-4 py-4 text-left transition",l?"border-[var(--primary)]/28 bg-[var(--ui-accent-soft)] text-[var(--ui-ink-strong)] shadow-[var(--ui-shadow-soft)]":"border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] text-[var(--ui-ink-medium)] hover:bg-[var(--ui-surface-hover)]"),onClick:()=>n(s.value),children:[e.jsx("div",{className:"min-w-0 break-words font-medium",children:s.label}),s.description?e.jsx("div",{className:"mt-2 min-w-0 break-words text-sm leading-6 text-[var(--ui-ink-soft)]",children:s.description}):null]},s.value)})})}function Re({open:t,onOpenChange:i,eyebrow:n,title:r,description:s,value:l,onChange:c,steps:f,onSubmit:g,submitLabel:N,pending:V=!1,pendingLabel:G,error:J,resolveError:y,initialStepId:v,contentClassName:q,draftPersistenceKey:u}){const{t:E}=le(),H=he(),[m,F]=o.useState(0),I=o.useRef(t),_=o.useRef(v),C=o.useRef(t),k=o.useRef(null),R=o.useRef(null),h=o.useRef(null),D=o.useRef(l),x=f[m];D.current=l,o.useEffect(()=>{const a=I.current,d=_.current,Q=xe({open:t,wasOpen:a,initialStepId:v,previousInitialStepId:d,currentStepIndex:m,steps:f});I.current=t,_.current=v,Q!==m&&F(Q)},[v,t,m,f]);const X=a=>{c({...l,...a})},w=f.length,Y=w===0?0:(m+1)/w*100,M=x?y==null?void 0:y(x.id):void 0,A=M===void 0?J:M,p=o.useCallback(()=>{if(!u)return;const a=R.current,d=B(D.current);if(!(!a||!d)){if(d===a){U(u),h.current=d;return}h.current!==d&&(ge(u,{version:W,baseline:a,draft:d,updatedAt:Date.now()}),h.current=d)}},[u]);o.useEffect(()=>{if(!t){k.current=null;return}if(!u){R.current=null,h.current=null;return}const a=B(l);if(!a||k.current===u)return;k.current=u,R.current=a;const d=we(u);if(d&&d.baseline===a&&d.draft!==a)try{c(JSON.parse(d.draft)),h.current=d.draft;return}catch{U(u)}h.current=a},[u,c,t,l]),o.useEffect(()=>{if(!u||!t||!j())return;const a=window.setInterval(()=>{p()},fe);return()=>window.clearInterval(a)},[u,t,p]),o.useEffect(()=>{C.current&&!t&&p(),C.current=t},[t,p]);const L=a=>{p(),F(a)},Z=a=>{a||p(),i(a)};return e.jsx(te,{open:t,onOpenChange:Z,children:e.jsxs(ne,{children:[e.jsx(re,{className:"surface-overlay fixed inset-0 z-40 backdrop-blur-xl"}),e.jsxs(se,{"data-testid":"question-flow-dialog",className:S("surface-modal-panel fixed z-50 flex flex-col overflow-hidden border",H?"inset-x-3 bottom-3 top-4 rounded-[30px]":"left-1/2 top-1/2 h-[min(52rem,calc(100vh-1rem))] w-[min(56rem,calc(100vw-1.5rem))] -translate-x-1/2 -translate-y-1/2 rounded-[34px]",q),children:[e.jsx(ae,{className:"sr-only",children:r}),e.jsx(ie,{className:"sr-only",children:s}),e.jsx("div",{className:"sticky top-0 z-10 border-b border-[var(--ui-border-subtle)] bg-[var(--surface-glass)] px-4 py-2.5 backdrop-blur-xl md:px-6",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",children:[e.jsx("span",{className:"truncate",children:n}),e.jsxs("span",{className:"shrink-0 text-right",children:["Step ",m+1," of ",w]})]}),e.jsx("div",{className:"mt-2 h-1.5 rounded-full bg-[var(--ui-surface-2)]",children:e.jsx(z.div,{className:"h-full rounded-full bg-[linear-gradient(90deg,var(--primary),var(--secondary))]",animate:{width:`${Y}%`},transition:{duration:.35,ease:"easeOut"}})})]}),e.jsx(T,{asChild:!0,children:e.jsx(ce,{"aria-label":E("common.dialogs.closeDialog")})})]})}),e.jsx("div",{"data-testid":"question-flow-canvas",className:"min-h-0 flex-1 overflow-y-auto overscroll-contain px-4 py-4 md:px-6 md:py-5",children:e.jsx(ue,{mode:"wait",children:e.jsx(z.div,{initial:{opacity:0,y:18},animate:{opacity:1,y:0},exit:{opacity:0,y:-18},transition:{duration:.28,ease:"easeOut"},className:"flex min-h-full min-w-0 flex-col gap-5",children:e.jsxs("div",{className:"flex min-h-full min-w-0 flex-col justify-start",children:[x.eyebrow?e.jsx("div",{className:"font-label text-[11px] uppercase tracking-[0.18em] text-[var(--secondary)]",children:x.eyebrow}):null,e.jsx("h3",{className:"mt-1.5 font-display text-[clamp(1.45rem,2.15vw,2rem)] leading-tight text-[var(--ui-ink-strong)]",children:x.title}),x.description?e.jsx("p",{className:"mt-1.5 max-w-3xl text-sm leading-6 text-[var(--ui-ink-soft)]",children:x.description}):null,A?e.jsx("div",{className:"mt-4 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:pe(A)}):null,e.jsx("div",{className:"mt-5 grid flex-1 content-start gap-5",children:x.render(l,X)})]})},x.id)})}),e.jsx("div",{className:"sticky bottom-0 border-t border-[var(--ui-border-subtle)] bg-[var(--surface-glass)] px-4 pt-2.5 pb-[calc(env(safe-area-inset-bottom)+0.75rem)] backdrop-blur-xl md:px-6 md:pb-3",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2 sm:justify-between",children:[e.jsx("div",{className:"hidden min-w-0 shrink text-[12px] text-[var(--ui-ink-faint)] sm:block",children:e.jsxs("span",{className:"truncate",children:["Step ",m+1,"/",w]})}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-wrap items-center justify-end gap-1.5 sm:gap-2",children:[m>0?e.jsxs(b,{type:"button",variant:"secondary",className:"min-w-0 px-3 text-[12px]",onClick:()=>L(Math.max(0,m-1)),children:[e.jsx(P,{className:"size-4"}),"Back"]}):e.jsx(T,{asChild:!0,children:e.jsx(b,{type:"button",variant:"secondary",className:"min-w-0 px-3 text-[12px]",children:E("common.actions.cancel")})}),m<w-1?e.jsxs(b,{type:"button",className:"min-w-0 px-3 text-[12px]",onClick:()=>L(Math.min(w-1,m+1)),children:["Continue",e.jsx(K,{className:"size-4"})]}):e.jsxs(b,{type:"button",className:"min-w-0 px-3 text-[12px]",pending:V,pendingLabel:G,onClick:()=>{p(),g()},children:[e.jsx(ee,{className:"size-4"}),N]})]})]})})]})]})})}export{ye as F,Re as Q,ke as a};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r as h,j as e,aV as ae,ck as te,cm as re}from"./vendor-BwL6m4SE.js";import{j as se,i as _,k as ie}from"./state-Bpe5dF3T.js";import{E as ne}from"./entity-link-multiselect-DcCvkesQ.js";import{d as de,S as le,e as ce,bs as oe,C as w,k as p,c as f,B as q,I as W,T as ue,d$ as me,bd as xe,e0 as pe,b3 as ve,b4 as ge,b5 as he,b6 as be,b9 as fe}from"./index-CQ5r7ZUz.js";import{P as ye}from"./page-hero-8bITsx_x.js";import{S as je,a as ke,b as Ne}from"./health-boxes-sHNML3tm.js";import{b as we,p as Se}from"./health-link-options-Cpx8w7uM.js";import"./use-anchored-overlay-position-BY4kNzPj.js";import"./motion-DcgUnXhY.js";import"./ui-B9TWEtCx.js";import"./board-CuxQRKPJ.js";import"./forms-D1qJ3oOP.js";import"./generic-node-view-CcepUVhP.js";import"./graph-BF4IsheG.js";import"./define-workbench-box-D-32C8nM.js";const _e=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],H={awake:{label:"Awake",strong:"var(--warning)",soft:"var(--ui-warning-soft)",text:"text-[color-mix(in_srgb,var(--warning)_78%,var(--ui-ink-strong)_22%)]"},core:{label:"Core",strong:"var(--primary)",soft:"var(--ui-accent-soft)",text:"text-[color-mix(in_srgb,var(--primary)_78%,var(--ui-ink-strong)_22%)]"},deep:{label:"Deep",strong:"var(--success)",soft:"var(--ui-success-soft)",text:"text-[color-mix(in_srgb,var(--success)_78%,var(--ui-ink-strong)_22%)]"},rem:{label:"REM",strong:"var(--info)",soft:"var(--ui-info-soft)",text:"text-[color-mix(in_srgb,var(--info)_78%,var(--ui-ink-strong)_22%)]"},in_bed:{label:"In bed",strong:"color-mix(in_srgb,var(--ui-ink-strong)_46%,transparent)",soft:"var(--ui-surface-3)",text:"text-[var(--ui-ink-medium)]"},asleep_unspecified:{label:"Asleep",strong:"var(--primary)",soft:"var(--ui-accent-soft)",text:"text-[color-mix(in_srgb,var(--primary)_78%,var(--ui-ink-strong)_22%)]"}};function I(a){return H[a]??H.asleep_unspecified}function v(a){if(a<=0)return"0m";const t=Math.floor(a/3600),r=Math.round(a%3600/60);return t===0?`${r}m`:r===0?`${t}h`:`${t}h ${r}m`}function Ae(a){const t=Math.round(a/60);return t===0?"on baseline":`${t>0?"+":"-"}${Math.abs(t)}m`}function T(a){return`${Math.round(a*100)}%`}function A(a,t){return a?new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",timeZone:t}).format(new Date(a)):"n/a"}function O(a,t){return new Intl.DateTimeFormat(void 0,{weekday:"long",day:"numeric",month:"long",timeZone:t}).format(new Date(a))}function C(a,t,r){return`${A(a,r)} - ${A(t,r)}`}function Te(a){const[t,r]=a.split("-").map(Number);return new Intl.DateTimeFormat(void 0,{month:"long",year:"numeric"}).format(new Date(t,(r??1)-1,1))}function U(a){const t=new Date(a),r=(a.getDay()+6)%7;return t.setDate(a.getDate()-r),t}function Re(a){const t=U(a);return t.setDate(t.getDate()+6),t}function De(a){const t=a.getFullYear(),r=`${a.getMonth()+1}`.padStart(2,"0"),s=`${a.getDate()}`.padStart(2,"0");return`${t}-${r}-${s}`}function B(a){return{qualitySummary:typeof a.annotations.qualitySummary=="string"?a.annotations.qualitySummary:"",notes:typeof a.annotations.notes=="string"?a.annotations.notes:"",tagsText:Array.isArray(a.annotations.tags)?a.annotations.tags.join(", "):"",linkValues:Array.isArray(a.links)?a.links.map(t=>`${t.entityType}:${t.entityId}`):[]}}function Me(a,t){if(!a)return[];const[r,s]=a.split("-").map(Number),n=new Date(r,(s??1)-1,1),u=new Date(r,s??1,0),d=U(n),x=Re(u),l=new Map(t.map(c=>[c.dateKey,c])),i=[];for(const c=new Date(d);c<=x;c.setDate(c.getDate()+1)){const j=De(c);i.push({dateKey:j,dayNumber:c.getDate(),outsideMonth:c.getMonth()!==n.getMonth(),sleep:l.get(j)??null})}return i}function Ie(a){return a>0?"text-[color-mix(in_srgb,var(--success)_78%,var(--ui-ink-strong)_22%)]":a<0?"text-[color-mix(in_srgb,var(--danger)_78%,var(--ui-ink-strong)_22%)]":"text-[var(--ui-ink-medium)]"}function J(a){return a==="recharged"||a==="recovered"?"bg-[var(--ui-success-soft)] text-[color-mix(in_srgb,var(--success)_78%,var(--ui-ink-strong)_22%)]":a==="steady"||a==="stable"?"bg-[var(--ui-info-soft)] text-[color-mix(in_srgb,var(--info)_78%,var(--ui-ink-strong)_22%)]":a==="fragile"||a==="strained"?"bg-[var(--ui-warning-soft)] text-[color-mix(in_srgb,var(--warning)_78%,var(--ui-ink-strong)_22%)]":a==="depleted"?"bg-[var(--ui-danger-soft)] text-[color-mix(in_srgb,var(--danger)_78%,var(--ui-ink-strong)_22%)]":"bg-[var(--ui-surface-3)] text-[var(--ui-ink-medium)]"}function Be(a){return a==="provider_raw"?"bg-[var(--ui-success-soft)] text-[color-mix(in_srgb,var(--success)_78%,var(--ui-ink-strong)_22%)]":a==="historical_raw"?"bg-[var(--ui-warning-soft)] text-[color-mix(in_srgb,var(--warning)_78%,var(--ui-ink-strong)_22%)]":"bg-[var(--ui-surface-3)] text-[var(--ui-ink-medium)]"}function Ce(a){return a==="provider_raw"?"Provider raw data":a==="historical_raw"?"Historical raw data":"Raw data unavailable"}function qe(a){return a.qualityKind==="provider_native"?"bg-[var(--ui-success-soft)] text-[color-mix(in_srgb,var(--success)_78%,var(--ui-ink-strong)_22%)]":"bg-[var(--ui-warning-soft)] text-[color-mix(in_srgb,var(--warning)_78%,var(--ui-ink-strong)_22%)]"}function Ke(a,t){const r=a.stage;if(typeof r=="string"&&r.trim().length>0)return r;const s=a.sourceType;if(typeof s=="string"&&s.trim().length>0)return s;const n=a.stageBreakdown;if(Array.isArray(n)&&n.length>0){const u=n[0];if(u&&typeof u=="object"&&typeof u.stage=="string")return(u.stage||"asleep_unspecified").trim()}return t.includes("awake")?"awake":"asleep_unspecified"}function $e(a){const t=a,r=(t==null?void 0:t.segments)??(t==null?void 0:t.rawSegments)??[],s=(t==null?void 0:t.auditLogs)??(t==null?void 0:t.rawLogs)??[],n=t!=null&&t.sourceRecords&&t.sourceRecords.length>0?t.sourceRecords:s.filter(d=>typeof d.startedAt=="string"&&typeof d.endedAt=="string").map(d=>({id:d.id,importRunId:d.importRunId,pairingSessionId:d.pairingSessionId,sleepSessionId:d.sleepSessionId,userId:d.userId,provider:d.source,providerRecordType:d.logType,providerRecordUid:d.externalUid??d.id,sourceDevice:"",sourceTimezone:d.sourceTimezone,localDateKey:d.localDateKey,startedAt:d.startedAt,endedAt:d.endedAt,rawStage:Ke(d.payload,d.logType),rawValue:null,qualityKind:"historical_import",payload:d.payload,metadata:d.metadata,ingestedAt:d.createdAt})),u=(t==null?void 0:t.rawDataStatus)??(n.length>0?"historical_raw":"raw_unavailable");return{sourceRecords:n,segments:r,auditLogs:s,rawDataStatus:u}}function G({stages:a}){const t=a.reduce((r,s)=>r+s.seconds,0);return a.length===0||t===0?e.jsx("div",{className:"rounded-[18px] border border-dashed border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-4 text-sm text-[var(--ui-ink-muted)]",children:"No stage composition was stored for this night yet."}):e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"flex h-3 overflow-hidden rounded-full bg-[var(--ui-surface-2)]",children:a.map(r=>{const s=I(r.stage);return e.jsx("div",{className:"h-full",style:{width:`${Math.max(4,r.seconds/t*100)}%`,background:s.strong},title:`${s.label} · ${v(r.seconds)}`},r.stage)})}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2 xl:grid-cols-4",children:a.map(r=>{const s=I(r.stage),n="percentage"in r&&typeof r.percentage=="number"?r.percentage:t>0?r.seconds/t:0;return e.jsxs("div",{className:"rounded-[16px] border border-[var(--ui-border-subtle)] px-3 py-3",style:{background:s.soft},children:[e.jsx("div",{className:f("text-sm font-medium",s.text),children:s.label}),e.jsx("div",{className:"mt-1 text-lg text-[var(--ui-ink-strong)]",children:v(r.seconds)}),e.jsx("div",{className:"text-xs text-[var(--ui-ink-muted)]",children:T(n)})]},r.stage)})})]})}function Q({blocks:a,selectedBlockId:t,onSelect:r}){return e.jsxs("div",{className:"relative h-12 overflow-hidden rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)]",children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 bg-[image:var(--ui-surface-section)] bg-[length:25%_100%]"}),a.map(s=>{const n=I(s.stage),u=t===s.id;return e.jsx("button",{type:"button",onClick:()=>r(s.id),className:f("absolute inset-y-[5px] rounded-[12px] border transition",u?"border-[var(--ui-border-strong)] shadow-[var(--ui-shadow-soft)]":"border-[var(--ui-border-subtle)]"),style:{left:`${s.offsetRatio*100}%`,width:`${Math.max(s.widthRatio*100,1.8)}%`,background:n.strong},title:`${s.label} · ${v(s.durationSeconds)} · ${s.startedAt} - ${s.endedAt}`,children:s.widthRatio>.13?e.jsx("span",{className:"truncate px-2 text-[10px] font-medium text-[var(--ui-ink-on-accent)]",children:s.label}):null},s.id)})]})}function Ee({timeline:a,timeZone:t}){var l,i;const r=a.blocks.filter(c=>c.lane==="in_bed"),s=a.blocks.filter(c=>c.lane==="sleep"),n=((l=s[0])==null?void 0:l.id)??((i=r[0])==null?void 0:i.id)??null,[u,d]=h.useState(n);h.useEffect(()=>{d(n)},[n,a.startedAt,a.endedAt,a.totalSeconds]);const x=a.blocks.find(c=>c.id===u)??null;return a.hasRawSegments?e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"grid gap-3",children:[r.length>0?e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:"In bed window"}),e.jsx(Q,{blocks:r,selectedBlockId:u,onSelect:d})]}):null,e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:a.hasSleepStageData?"Sleep phases":"Recorded sleep coverage"}),e.jsx(Q,{blocks:s.length>0?s:r,selectedBlockId:u,onSelect:d})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-[var(--ui-ink-muted)]",children:[e.jsx("span",{children:A(a.startedAt,t)}),e.jsx("span",{children:v(a.totalSeconds)}),e.jsx("span",{children:A(a.endedAt,t)})]}),x?e.jsx("div",{className:"rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:f("text-sm font-medium",I(x.stage).text),children:x.label}),e.jsxs("div",{className:"mt-1 text-sm text-[var(--ui-ink-muted)]",children:[A(x.startedAt,t)," -"," ",A(x.endedAt,t)]})]}),e.jsx(p,{tone:"meta",children:v(x.durationSeconds)})]})}):null]}):e.jsx("div",{className:"rounded-[18px] border border-dashed border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-5 text-sm text-[var(--ui-ink-muted)]",children:"Phase timing is unavailable for this night. Forge still keeps the canonical overnight summary, but the companion did not store segment-level timing."})}function Fe({latestNight:a,freshness:t}){if(!a)return e.jsxs(w,{className:"overflow-hidden p-6",children:[e.jsx("div",{className:"text-sm uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:"Sleep"}),e.jsx("div",{className:"mt-4 text-2xl text-[var(--ui-ink-strong)]",children:"No overnight sleep yet"}),e.jsx("div",{className:"mt-3 max-w-2xl text-sm leading-6 text-[var(--ui-ink-muted)]",children:"The sleep page will switch to a night-first summary once the companion syncs a canonical overnight session."})]});const r=(t==null?void 0:t.status)??a.freshnessStatus,s=(t==null?void 0:t.expectedDateKey)??a.expectedDateKey,n=(t==null?void 0:t.actualDateKey)??a.dateKey,u=(t==null?void 0:t.isCurrent)??a.isExpectedLastNight,d=r==="future"?"Clock check":u?"Last night":"Latest synced night";return e.jsx(w,{className:"overflow-hidden border-[var(--ui-border-subtle)] bg-[image:var(--ui-surface-section)] p-0",children:e.jsxs("div",{className:"relative overflow-hidden px-6 py-6 sm:px-7 sm:py-7",children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 bg-[image:var(--ui-surface-section)]"}),e.jsxs("div",{className:"relative grid gap-6 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]",children:[e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(p,{className:f("border-transparent",J(a.recoveryState)),children:a.qualitativeState}),e.jsx(p,{tone:"meta",children:a.sourceTimezone}),a.hasReflection?e.jsx(p,{tone:"meta",children:"Has reflection"}):null,a.hasRawSegments?e.jsxs(p,{tone:"meta",children:[a.rawSegmentCount," raw segments"]}):null]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.2em] text-[var(--ui-ink-muted)]",children:d}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-end gap-x-4 gap-y-2",children:[e.jsx("div",{className:"text-[clamp(2.5rem,6vw,5rem)] font-medium leading-none text-[var(--ui-ink-strong)]",children:v(a.asleepSeconds)}),e.jsxs("div",{className:"pb-2 text-sm text-[var(--ui-ink-muted)]",children:["asleep across ",C(a.startedAt,a.endedAt,a.sourceTimezone)]})]}),e.jsx("div",{className:"mt-3 text-sm text-[var(--ui-ink-medium)]",children:O(a.endedAt,a.sourceTimezone)}),a.qualitySummary?e.jsx("div",{className:"mt-4 max-w-2xl text-sm leading-6 text-[var(--ui-ink-medium)]",children:a.qualitySummary}):r==="stale"?e.jsxs("div",{className:"mt-4 max-w-2xl rounded-[16px] border border-amber-300/60 bg-amber-100/70 px-4 py-3 text-sm leading-6 text-amber-950 dark:border-amber-400/30 dark:bg-amber-500/15 dark:text-amber-100",children:["Expected wake-date ",s," in ",a.sourceTimezone,", but Forge has ",n,". Refresh the iPhone sync after unlock; this page checks again automatically."]}):r==="future"?e.jsxs("div",{className:"mt-4 max-w-2xl rounded-[16px] border border-sky-300/60 bg-sky-100/70 px-4 py-3 text-sm leading-6 text-sky-950 dark:border-sky-400/30 dark:bg-sky-500/15 dark:text-sky-100",children:["This sleep is dated after today in ",a.sourceTimezone,". Check the phone clock, timezone, and HealthKit sample dates."]}):e.jsx("div",{className:"mt-4 max-w-2xl text-sm leading-6 text-[var(--ui-ink-muted)]",children:"Canonical overnight summary computed from synced sleep segments, with raw evidence still available underneath."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:"In bed"}),e.jsx("div",{className:"mt-2 text-xl text-[var(--ui-ink-strong)]",children:v(a.timeInBedSeconds)})]}),e.jsxs("div",{className:"rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:"Score"}),e.jsx("div",{className:"mt-2 text-xl text-[var(--ui-ink-strong)]",children:a.score??"n/a"})]}),e.jsxs("div",{className:"rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:"Regularity"}),e.jsx("div",{className:"mt-2 text-xl text-[var(--ui-ink-strong)]",children:a.regularity??"n/a"})]}),e.jsxs("div",{className:"rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:"Efficiency"}),e.jsx("div",{className:"mt-2 text-xl text-[var(--ui-ink-strong)]",children:T(a.efficiency)})]})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"rounded-[22px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-5 py-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:"Baseline"}),e.jsx("div",{className:"mt-2 text-lg text-[var(--ui-ink-strong)]",children:"Compared with recent nights"})]}),e.jsx(te,{className:"size-5 text-[var(--primary)]"})]}),e.jsxs("div",{className:"mt-4 grid gap-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-[var(--ui-surface-2)] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-[var(--ui-ink-medium)]",children:"7-night average"}),e.jsx("span",{className:"text-sm text-[var(--ui-ink-strong)]",children:v(a.weeklyAverageSleepSeconds)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-[var(--ui-surface-2)] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-[var(--ui-ink-medium)]",children:"Versus baseline"}),e.jsx("span",{className:f("text-sm",Ie(a.deltaFromWeeklyAverageSeconds)),children:Ae(a.deltaFromWeeklyAverageSeconds)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-[var(--ui-surface-2)] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-[var(--ui-ink-medium)]",children:"Bedtime drift"}),e.jsxs("span",{className:"text-sm text-[var(--ui-ink-strong)]",children:[a.bedtimeDriftMinutes??0,"m"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-[var(--ui-surface-2)] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-[var(--ui-ink-medium)]",children:"Wake drift"}),e.jsxs("span",{className:"text-sm text-[var(--ui-ink-strong)]",children:[a.wakeDriftMinutes??0,"m"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[16px] bg-[var(--ui-surface-2)] px-4 py-3",children:[e.jsx("span",{className:"text-sm text-[var(--ui-ink-medium)]",children:"Restorative share"}),e.jsx("span",{className:"text-sm text-[var(--ui-ink-strong)]",children:T(a.restorativeShare)})]})]})]}),e.jsxs("div",{className:"rounded-[22px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-5 py-5",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:"Stage composition"}),e.jsx("div",{className:"mt-4",children:e.jsx(G,{stages:a.stageBreakdown})})]})]})]})]})})}function F({title:a,value:t,description:r}){return e.jsxs(w,{className:"h-full border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)]",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:a}),e.jsx("div",{className:"mt-3 text-3xl text-[var(--ui-ink-strong)]",children:t}),e.jsx("div",{className:"mt-3 text-sm leading-6 text-[var(--ui-ink-muted)]",children:r})]})}function ze({days:a,selectedSleepId:t,onSelect:r}){const s=h.useMemo(()=>Array.from(new Set(a.map(l=>l.dateKey.slice(0,7)))).sort((l,i)=>l.localeCompare(i)),[a]),[n,u]=h.useState(s[s.length-1]??"");h.useEffect(()=>{if(s.length===0){u("");return}s.includes(n)||u(s[s.length-1]??"")},[n,s]);const d=s.indexOf(n),x=h.useMemo(()=>Me(n,a),[a,n]);return n?e.jsx(w,{className:"overflow-hidden border-[var(--ui-border-subtle)] bg-[image:var(--ui-surface-section)] p-0",children:e.jsxs("div",{className:"grid gap-5 px-5 py-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:"Sleep calendar"}),e.jsx("div",{className:"mt-2 text-xl text-[var(--ui-ink-strong)]",children:Te(n)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(q,{type:"button",variant:"secondary",className:"h-9 rounded-full",disabled:d<=0,onClick:()=>u(s[Math.max(0,d-1)]??n),children:"Previous"}),e.jsx(q,{type:"button",variant:"secondary",className:"h-9 rounded-full",disabled:d===-1||d>=s.length-1,onClick:()=>u(s[Math.min(s.length-1,d+1)]??n),children:"Next"})]})]}),e.jsx("div",{className:"grid grid-cols-7 gap-2 text-center text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-muted)]",children:_e.map(l=>e.jsx("div",{children:l},l))}),e.jsx("div",{className:"grid grid-cols-7 gap-2",children:x.map(l=>{const i=l.sleep,c=(i==null?void 0:i.sleepId)===t,j=i&&typeof i.score=="number"?i.score>=80?"var(--ui-success-soft)":i.score>=65?"var(--ui-info-soft)":"var(--ui-warning-soft)":"var(--ui-surface-2)";return e.jsxs("button",{type:"button",disabled:!i,"aria-pressed":c,"aria-label":`Select sleep for ${l.dateKey}`,onClick:()=>{i&&(u(i.dateKey.slice(0,7)),r(i.sleepId,i.dateKey.slice(0,7)))},className:f("min-h-[90px] rounded-[18px] border px-2 py-2 text-left transition",i?"border-[var(--ui-border-subtle)] hover:border-[var(--ui-border-strong)] hover:bg-[var(--ui-surface-3)]":"border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)]",c&&"border-[var(--primary)] bg-[var(--primary)]/12",l.outsideMonth&&!i&&"opacity-35"),style:i?{background:j}:void 0,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("span",{className:f("text-sm",l.outsideMonth?"text-[var(--ui-ink-muted)]":"text-[var(--ui-ink-medium)]"),children:l.dayNumber}),i!=null&&i.hasReflection?e.jsx("span",{className:"size-2 rounded-full bg-[var(--success)]"}):null]}),i?e.jsxs("div",{className:"mt-4 grid gap-1",children:[e.jsxs("div",{className:"text-lg text-[var(--ui-ink-strong)]",children:[i.sleepHours.toFixed(1),"h"]}),e.jsxs("div",{className:"text-xs text-[var(--ui-ink-muted)]",children:[i.score??"n/a"," score"]}),e.jsx("div",{className:"text-xs text-[var(--ui-ink-muted)]",children:i.hasRawSegments?"phases available":"summary only"})]}):null]},l.dateKey)})})]})}):e.jsx(w,{className:"border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-5 py-8 text-sm leading-6 text-[var(--ui-ink-muted)]",children:"No canonical nights are available for the calendar yet."})}function z({active:a,children:t,onClick:r}){return e.jsx("button",{type:"button",onClick:r,className:f("rounded-full border px-4 py-2 text-sm transition",a?"border-[var(--primary)] bg-[var(--primary)]/12 text-[var(--ui-ink-strong)]":"border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] text-[var(--ui-ink-medium)] hover:text-[var(--ui-ink-strong)]"),children:t})}function Le({session:a,draft:t,rawDetail:r,rawDetailLoading:s,pending:n,tab:u,linkOptions:d,onTabChange:x,onDraftChange:l,onSave:i}){const[c,j]=h.useState(null),k=h.useMemo(()=>$e(r),[r]),K=typeof a.derived.efficiency=="number"?a.derived.efficiency:a.timeInBedSeconds>0?a.asleepSeconds/a.timeInBedSeconds:0,$=typeof a.derived.restorativeShare=="number"?a.derived.restorativeShare:0,R=typeof a.derived.recoveryState=="string"?a.derived.recoveryState:null;return e.jsx(w,{className:"overflow-hidden border-[var(--ui-border-subtle)] bg-[image:var(--ui-surface-section)] p-0",children:e.jsxs("div",{className:"grid gap-5 px-5 py-5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(p,{className:f("border-transparent",J(R)),children:R?R.replaceAll("_"," "):"Canonical night"}),e.jsxs(p,{tone:"meta",children:[a.rawSegmentCount," raw segments"]}),e.jsx(p,{tone:"meta",children:a.sourceTimezone})]}),e.jsx("div",{className:"mt-3 text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:"Selected night"}),e.jsx("div",{className:"mt-2 text-2xl text-[var(--ui-ink-strong)]",children:O(a.endedAt,a.sourceTimezone)}),e.jsx("div",{className:"mt-2 text-sm text-[var(--ui-ink-muted)]",children:C(a.startedAt,a.endedAt,a.sourceTimezone)})]}),e.jsxs("div",{className:"grid gap-2 text-right",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:"Summary"}),e.jsx("div",{className:"text-3xl text-[var(--ui-ink-strong)]",children:v(a.asleepSeconds)}),e.jsx("div",{className:"text-sm text-[var(--ui-ink-muted)]",children:"asleep"})]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:"In bed"}),e.jsx("div",{className:"mt-2 text-xl text-[var(--ui-ink-strong)]",children:v(a.timeInBedSeconds)})]}),e.jsxs("div",{className:"rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:"Awake"}),e.jsx("div",{className:"mt-2 text-xl text-[var(--ui-ink-strong)]",children:v(a.awakeSeconds)})]}),e.jsxs("div",{className:"rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:"Efficiency"}),e.jsx("div",{className:"mt-2 text-xl text-[var(--ui-ink-strong)]",children:T(K)})]}),e.jsxs("div",{className:"rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:"Restorative"}),e.jsx("div",{className:"mt-2 text-xl text-[var(--ui-ink-strong)]",children:T($)})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(z,{active:u==="summary",onClick:()=>x("summary"),children:"Summary"}),e.jsx(z,{active:u==="reflection",onClick:()=>x("reflection"),children:"Reflection"}),e.jsx(z,{active:u==="raw",onClick:()=>x("raw"),children:"Show raw data"})]}),u==="summary"?e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"rounded-[22px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:"Phase timeline"}),e.jsx("div",{className:"mt-4",children:s?e.jsx("div",{className:"rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-6 text-sm text-[var(--ui-ink-muted)]",children:"Loading phase timing from raw sleep segments…"}):e.jsx(Ee,{timeline:(r==null?void 0:r.phaseTimeline)??{startedAt:a.startedAt,endedAt:a.endedAt,totalSeconds:Math.max(0,Math.round((new Date(a.endedAt).getTime()-new Date(a.startedAt).getTime())/1e3)),hasRawSegments:!1,hasSleepStageData:!1,blocks:[]},timeZone:a.sourceTimezone})})]}),e.jsxs("div",{className:"rounded-[22px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:"Stage composition"}),e.jsx("div",{className:"mt-4",children:e.jsx(G,{stages:a.stageBreakdown})})]})]}):null,u==="reflection"?e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-[var(--ui-ink-muted)]",children:"Quality summary"}),e.jsx(W,{value:t.qualitySummary,onChange:o=>l({qualitySummary:o.target.value}),placeholder:"Recovered after a late evening, but sleep onset drifted."})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-[var(--ui-ink-muted)]",children:"Night notes"}),e.jsx(ue,{className:"min-h-[200px]",value:t.notes,onChange:o=>l({notes:o.target.value}),placeholder:"What shaped this night, and what should we remember about it?"})]}),e.jsxs("label",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-[var(--ui-ink-muted)]",children:"Tags"}),e.jsx(W,{value:t.tagsText,onChange:o=>l({tagsText:o.target.value}),placeholder:"travel, stress, good-routine, late-caffeine"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("span",{className:"text-sm text-[var(--ui-ink-muted)]",children:"Linked context"}),e.jsx(ne,{options:d,selectedValues:t.linkValues,onChange:o=>l({linkValues:o}),placeholder:"Search goals, tasks, habits, beliefs, reports, or patterns…"})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(q,{type:"button",pending:n,pendingLabel:"Saving",onClick:i,children:[e.jsx(re,{className:"size-4"}),"Save reflection"]})})]}):null,u==="raw"?e.jsxs("div",{className:"grid gap-5",children:[e.jsx("div",{className:"rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-4 text-sm leading-6 text-[var(--ui-ink-muted)]",children:"Forge shows the canonical overnight session by default. This view reveals the evidence stack underneath it: raw provider or historical imported records first, then Forge-normalized sleep segments."}),s?e.jsx("div",{className:"text-sm text-[var(--ui-ink-muted)]",children:"Loading raw sleep evidence…"}):null,s?null:e.jsxs("div",{className:"grid gap-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(p,{className:f("border-transparent",Be(k.rawDataStatus)),children:Ce(k.rawDataStatus)}),k.rawDataStatus==="historical_raw"?e.jsx(p,{tone:"meta",children:"Partial evidence"}):null]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:"Raw data"}),k.sourceRecords.length?k.sourceRecords.map(o=>e.jsxs("div",{className:"rounded-[16px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(p,{className:f("border-transparent",qe(o)),children:o.qualityKind==="provider_native"?"Provider raw":"Historical raw"}),e.jsx(p,{tone:"meta",className:"capitalize",children:o.rawStage.replaceAll("_"," ")}),e.jsx("span",{className:"text-sm text-[var(--ui-ink-medium)]",children:C(o.startedAt,o.endedAt,o.sourceTimezone)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-[var(--ui-ink-muted)]",children:o.providerRecordType.replaceAll("_"," ")}),e.jsx(q,{type:"button",variant:"secondary",className:"h-8 rounded-full px-3",onClick:()=>j(D=>D===o.id?null:o.id),children:c===o.id?"Hide JSON":"See JSON"})]})]}),e.jsx("div",{className:"mt-3 text-sm text-[var(--ui-ink-muted)]",children:v(Math.max(0,Math.round((new Date(o.endedAt).getTime()-new Date(o.startedAt).getTime())/1e3)))}),c===o.id?e.jsx("pre",{className:"mt-3 overflow-x-auto rounded-[14px] border border-[var(--ui-border-subtle)] bg-[var(--ui-code-bg)] p-3 text-xs leading-6 text-[var(--ui-ink-medium)]",children:JSON.stringify({payload:o.payload,metadata:o.metadata},null,2)}):null]},o.id)):e.jsx("div",{className:"rounded-[16px] border border-dashed border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-4 text-sm text-[var(--ui-ink-muted)]",children:"No raw data was stored for this night."})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:"Sleep segments"}),k.segments.length?k.segments.map(o=>e.jsx("div",{className:"rounded-[16px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-3",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(p,{tone:"meta",className:"capitalize",children:o.stage.replaceAll("_"," ")}),e.jsx(p,{tone:"meta",children:o.qualityKind==="provider_native"?"provider-backed":"historical"}),e.jsx("span",{className:"text-sm text-[var(--ui-ink-medium)]",children:C(o.startedAt,o.endedAt,o.sourceTimezone)})]}),e.jsx("span",{className:"text-sm text-[var(--ui-ink-muted)]",children:v(Math.max(0,Math.round((new Date(o.endedAt).getTime()-new Date(o.startedAt).getTime())/1e3)))})]})},o.id)):e.jsx("div",{className:"rounded-[16px] border border-dashed border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-4 text-sm text-[var(--ui-ink-muted)]",children:"No normalized sleep segments were stored for this night."})]})]})]}):null]})})}function ra(){var V;const a=de(),t=se(),[r,s]=h.useState({}),[n,u]=h.useState(null),[d,x]=h.useState("summary"),l=Array.isArray(a==null?void 0:a.selectedUserIds)?a.selectedUserIds:[],i=a==null?void 0:a.snapshot,c=_({queryKey:["forge-sleep",...l],queryFn:async()=>(await xe(l)).sleep,refetchInterval:6e4,refetchOnWindowFocus:!0,staleTime:15e3}),j=_({queryKey:["forge-sleep-raw",n],enabled:!!n,queryFn:async()=>pe(n)}),k=_({queryKey:["forge-sleep-values",...l],queryFn:async()=>(await ve(l)).values}),K=_({queryKey:["forge-sleep-patterns",...l],queryFn:async()=>(await ge(l)).patterns}),$=_({queryKey:["forge-sleep-behaviors",...l],queryFn:async()=>(await he(l)).behaviors}),R=_({queryKey:["forge-sleep-beliefs",...l],queryFn:async()=>(await be(l)).beliefs}),o=_({queryKey:["forge-sleep-reports",...l],queryFn:async()=>(await fe(l)).reports});h.useEffect(()=>{c.data&&s(Object.fromEntries(c.data.sessions.map(m=>[m.id,B(m)])))},[c.data]),h.useEffect(()=>{var N,y,S;if(!((N=c.data)!=null&&N.sessions.length)){u(null);return}c.data.sessions.some(E=>E.id===n)||u(((y=c.data.latestNight)==null?void 0:y.sleepId)??((S=c.data.sessions[0])==null?void 0:S.id)??null)},[n,c.data]),h.useEffect(()=>{x("summary")},[n]);const D=ie({mutationFn:async m=>me(m.sleepId,{qualitySummary:m.qualitySummary,notes:m.notes,tags:m.tagsText.split(",").map(N=>N.trim()).filter(Boolean),links:Se(m.linkValues)}),onSuccess:async()=>{await t.invalidateQueries({queryKey:["forge-sleep"]}),await t.invalidateQueries({queryKey:["forge-sleep-raw"]})}});if(c.isLoading)return e.jsx(le,{eyebrow:"Sleep",title:"Loading sleep surface",description:"Reading canonical nights, calendar summaries, and sleep phase detail.",columns:2,blocks:6});if(c.isError||!c.data)return e.jsx(ce,{eyebrow:"Sleep",error:c.error??new Error("Sleep data unavailable"),onRetry:()=>void c.refetch()});const g=c.data,M=g.sessions,L=new Map(M.map(m=>[m.id,m])),b=(n?L.get(n):null)??(g.latestNight?L.get(g.latestNight.sleepId):null)??M[0]??null,P=b?r[b.id]??B(b):null,Y=we({goals:(i==null?void 0:i.dashboard.goals)??[],projects:(i==null?void 0:i.dashboard.projects)??[],tasks:(i==null?void 0:i.dashboard.tasks)??[],habits:(i==null?void 0:i.dashboard.habits)??[],values:k.data??[],patterns:K.data??[],behaviors:$.data??[],beliefs:R.data??[],reports:o.data??[]});function X(m,N){s(y=>{const S=M.find(ee=>ee.id===m),E=y[m]??(S?B(S):{qualitySummary:"",notes:"",tagsText:"",linkValues:[]});return{...y,[m]:{...E,...N}}})}async function Z(m){const N=M.find(S=>S.id===m);if(!N)return;const y=r[m]??B(N);await D.mutateAsync({sleepId:m,qualitySummary:y.qualitySummary,notes:y.notes,tagsText:y.tagsText,linkValues:y.linkValues})}return e.jsxs("div",{className:"grid gap-5",children:[e.jsx(ye,{eyebrow:"Health",title:"Sleep",description:"Canonical overnight sessions first, with last-night recovery, a clickable night calendar, and raw segment evidence only when you ask for it.",badge:`${M.length} nights`}),e.jsx(oe,{}),e.jsx(je,{children:e.jsx(Fe,{latestNight:g.latestNight,freshness:g.latestNightFreshness})}),e.jsx(ke,{children:e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.95fr)_minmax(0,1.05fr)]",children:[e.jsx(F,{title:"Weekly average",value:v(g.summary.averageSleepSeconds),description:"Average overnight sleep duration across the recent week, used as the baseline for the latest-night comparison."}),e.jsx(F,{title:"Regularity",value:`${g.summary.averageRegularityScore}`,description:`Average bedtime drift ${g.summary.averageBedtimeConsistencyMinutes}m and wake drift ${g.summary.averageWakeConsistencyMinutes}m.`}),e.jsx(F,{title:"Restorative share",value:T(g.summary.averageRestorativeShare),description:`Deep + REM share across recent nights, with ${g.summary.reflectiveNightCount} nights already carrying context.`}),e.jsxs(w,{className:"border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-muted)]",children:"Recent stage mix"}),e.jsx("div",{className:"mt-2 text-xl text-[var(--ui-ink-strong)]",children:"Average nightly phases"})]}),e.jsx(ae,{className:"size-5 text-[var(--primary)]"})]}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:g.stageAverages.length>0?g.stageAverages.slice(0,5).map(m=>e.jsxs(p,{tone:"meta",children:[I(m.stage).label," ",v(m.averageSeconds)]},m.stage)):e.jsx("div",{className:"text-sm text-[var(--ui-ink-muted)]",children:"Stage averages will appear once nights include phase data."})})]})]})}),e.jsx(Ne,{children:e.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,25rem)_minmax(0,1fr)]",children:[e.jsx(ze,{days:g.calendarDays,selectedSleepId:(b==null?void 0:b.id)??null,onSelect:m=>u(m)}),b&&P?e.jsx(Le,{session:b,draft:P,rawDetail:j.data??null,rawDetailLoading:j.isLoading,pending:D.isPending&&((V=D.variables)==null?void 0:V.sleepId)===b.id,tab:d,linkOptions:Y,onTabChange:x,onDraftChange:m=>X(b.id,m),onSave:()=>void Z(b.id)}):e.jsx(w,{className:"border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-6 py-8 text-sm leading-6 text-[var(--ui-ink-muted)]",children:"Pick a night from the calendar to inspect its phase timing, stage summary, and reflection context."})]})})]})}export{ra as SleepPage};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{j as r}from"./vendor-BwL6m4SE.js";import{c as t}from"./index-CQ5r7ZUz.js";function n({className:e,interactive:a=!1,muted:s=!1,...i}){return r.jsx("div",{className:t("rounded-[22px] border border-[var(--ui-border-subtle)] p-4",s?"bg-[var(--ui-surface-2)]":"bg-[var(--ui-surface-1)]",a&&"transition hover:border-[var(--ui-border-strong)] hover:bg-[var(--ui-surface-hover)]",e),...i})}function c({label:e,value:a,className:s}){return r.jsxs(n,{className:t("rounded-[18px] p-3",s),children:[r.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:e}),r.jsx("div",{className:"mt-1 text-lg font-semibold text-[var(--ui-ink-strong)]",children:a})]})}export{n as S,c as a};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{j as a,bX as ze,aG as pa,b7 as ba,cg as Oa,dx as Ua,cB as Qa,bB as We,cm as Za,cF as xa,c8 as Va,c1 as fa,dy as Ya,dz as Ja,bq as va,dA as Xa,dB as et,r as F,d8 as at,aV as tt,dC as nt,cv as rt,bt as na,dD as st,br as it,bd as ot}from"./vendor-BwL6m4SE.js";import{j as lt,i as ct,k as U}from"./state-Bpe5dF3T.js";import{P as dt}from"./page-hero-8bITsx_x.js";import{C as q,a4 as de,B as G,I as w,c as Be,k as $,T as Ce,d as ut,L as gt,e as mt,e8 as ra,e9 as ht,ea as pt,eb as bt,ec as sa,ed as xt,ee as ft,ef as vt,eg as yt,eh as jt,ei as kt,ej as Nt}from"./index-CQ5r7ZUz.js";import{S as P,a as C}from"./surface-MVeeZGKB.js";import{Q as Fe,F as j,a as ia}from"./question-flow-dialog-CskCt5NZ.js";import{g as wt,f as we}from"./date-keys-BnZV4PNO.js";import"./motion-DcgUnXhY.js";import"./ui-B9TWEtCx.js";import"./board-CuxQRKPJ.js";import"./forms-D1qJ3oOP.js";function Ct({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(q,{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(o=>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:o.label}),a.jsx("div",{className:"mt-1 truncate text-sm font-semibold text-[var(--ui-ink-strong)]",children:o.value})]},o.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(ze,{className:"size-4"}),"Custom food"]}),a.jsxs(G,{type:"button",variant:"secondary",onClick:s,children:[a.jsx(pa,{className:"size-4"}),"Ask ChatGPT"]}),a.jsxs(G,{type:"button",variant:"secondary",onClick:n,children:[a.jsx(ba,{className:"size-4"}),"Search food"]}),a.jsxs(G,{type:"button",variant:"secondary",onClick:t,children:[a.jsx(Oa,{className:"size-4"}),"Plan settings"]}),a.jsxs(G,{type:"button",variant:"secondary",onClick:l,children:[a.jsx(Ua,{className:"size-4"}),"Add measure"]}),a.jsxs(G,{type:"button",variant:"secondary",onClick:g,children:[a.jsx(Qa,{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 i(e,t=0){const n=_(e);return n===null?"n/a":n.toFixed(t)}function H(e,t=0){const n=_(e);return n===null?"n/a":`${n>0?"+":""}${n.toFixed(t)}`}function ke(e){const t=_(e);return t===null?"n/a":`${t.toFixed(1)}/10`}function Mt(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&!Array.isArray(t)):[]}function Ft(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 Kt(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 St(e){return`${e>=0?"+":""}${e.toFixed(0)} kcal`}function Gt(e){return e.trim()===""?"0":e}function At({view:e,draftValue:t,pending:n,error:r,onDraftChange:s,onSave:l,onReset:g}){const c=e.energyModel,o=e.todayLedger,u=c.todayActiveOverride,p=c.todayActiveCaloriesSource,K=`${o.plannedTargetCalories.toFixed(0)} ${St(c.todayTargetAdjustmentKcal)} = ${o.targetCalories.toFixed(0)} kcal`;return a.jsxs(q,{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(We,{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:Kt(p)}),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: ",Ft(p)]})]}),a.jsxs("div",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)_auto] gap-2",children:[a.jsx(w,{inputMode:"decimal",value:t,onChange:k=>s(Gt(k.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(Za,{className:"size-4"}),"Apply"]})]}),a.jsxs(G,{type:"button",variant:"secondary",onClick:g,disabled:!u||n,children:[a.jsx(xa,{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 Dt={default:"bg-[color-mix(in_srgb,var(--primary)_14%,transparent)] text-[var(--primary)]",green:"bg-[var(--ui-success-soft)] text-[color-mix(in_srgb,var(--success)_78%,var(--ui-ink-strong)_22%)]",amber:"bg-[var(--ui-warning-soft)] text-[color-mix(in_srgb,var(--warning)_76%,var(--ui-ink-strong)_24%)]",rose:"bg-[var(--ui-danger-soft)] text-[color-mix(in_srgb,var(--danger)_76%,var(--ui-ink-strong)_24%)]",cyan:"bg-[var(--ui-info-soft)] text-[color-mix(in_srgb,var(--info)_78%,var(--ui-ink-strong)_22%)]"};function Y({label:e,value:t,detail:n,icon:r,tone:s="default",help:l,helpMaxWidthPx:g}){return a.jsxs(q,{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:Be("rounded-2xl p-2.5",Dt[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 _t({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),o=g?`${g.name}${c>0?` + ${c} more`:""}`:l?"Food entry":e.mealLabel??"Meal",u=e.items.slice(0,3).map(p=>{const K=Number.isFinite(p.quantity)&&p.quantity>0?Number.isInteger(p.quantity)?String(p.quantity):p.quantity.toFixed(2).replace(/\.?0+$/,""):null,k=p.unit??"serving",b=p.grams!=null?`${p.grams.toFixed(0)}g`:null;return[K,k,b?`(${b})`:null].filter(Boolean).join(" ")}).filter(Boolean).join(" · ");return a.jsxs(P,{className:"grid min-w-0 gap-3",children:[a.jsxs("div",{className:"flex min-w-0 flex-wrap items-start justify-between gap-3",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsx("div",{className:"break-words text-base font-semibold leading-6 text-[var(--ui-ink-strong)]",children:o}),a.jsx("div",{className:"mt-1 text-xs leading-5 text-[var(--ui-ink-faint)]",children:u||e.notes||"No quantity recorded"})]}),a.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[e.mealLabel&&!l?a.jsx($,{tone:"meta",children:e.mealLabel}):null,a.jsxs($,{tone:"meta",children:[e.totals.calories.toFixed(0)," kcal"]})]})]}),a.jsxs("div",{className:"grid gap-2 text-xs text-[var(--ui-ink-soft)] sm:grid-cols-3 xl:grid-cols-6",children:[a.jsxs("span",{children:[e.totals.proteinGrams.toFixed(0),"g protein"]}),a.jsxs("span",{children:[e.totals.carbohydrateGrams.toFixed(0),"g carbs"]}),a.jsxs("span",{children:[e.totals.fatGrams.toFixed(0),"g fat"]}),a.jsxs("span",{children:[e.totals.fiberGrams.toFixed(0),"g fiber"]}),a.jsxs("span",{children:[e.totals.sodiumMg.toFixed(0),"mg sodium"]}),a.jsx("span",{children:e.confirmationState})]}),a.jsxs("div",{className:"flex flex-wrap gap-2",children:[n?a.jsxs(G,{type:"button",size:"sm",variant:"secondary",onClick:()=>n(e),children:[a.jsx(Va,{className:"size-4"}),"Edit"]}):null,r?a.jsxs(G,{type:"button",size:"sm",variant:"ghost",pending:s,onClick:()=>r(e),children:[a.jsx(fa,{className:"size-4"}),"Delete"]}):null,t?a.jsxs(G,{type:"button",size:"sm",variant:"ghost",pending:s,onClick:()=>t(e),children:[a.jsx(xa,{className:"size-4"}),"Log again"]}):null]})]})}function qe({children:e}){return a.jsx(P,{className:"border-dashed border-[var(--ui-border-strong)] p-5 text-sm text-[var(--ui-ink-soft)]",children:e})}function pe(e){return`${e.toFixed(0)} kcal`}function Et(e){return e>=0?"Kcal left":"Over target"}function $t(e){return e>=0?pe(e):pe(Math.abs(e))}function Tt(e){var n;const t=(n=e.mealLabel)==null?void 0:n.trim();return t||"No meal marker"}function Lt(e){const t=[],n=new Map;for(const r of e){const s=Tt(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 It({ledger:e,remainingCalories:t,intakePercent:n,logSavedPending:r,onLogAgain:s,onEditMeal:l,onDeleteMeal:g}){const c=e.totals,o=Lt(e.meals);return a.jsxs(q,{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($,{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:pe(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:pe(e.targetCalories)})]}),a.jsxs("div",{className:Be("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:Et(t)}),a.jsx("div",{className:"mt-1 text-2xl font-semibold text-[var(--ui-ink-strong)]",children:$t(t)})]})]}),a.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-[var(--ui-surface-2)]",children:a.jsx("div",{className:Be("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?o.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"," ","· ",pe(u.calories)]})]}),a.jsx("div",{className:"grid gap-2",children:u.meals.map(p=>a.jsx(_t,{meal:p,pending:r,hideMealLabel:!0,onLogAgain:s,onEdit:l,onDelete:g},p.id))})]},u.label)):a.jsx(qe,{children:"No food logged for this day yet."})})]})}function Pt({hypotheses:e}){return a.jsxs(q,{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(P,{children:[a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsx($,{tone:"signal",children:ce(t.metric)??"pattern"}),a.jsx("span",{className:"text-xs text-[var(--ui-ink-faint)]",children:i(t.confidence,2)})]}),a.jsx("div",{className:"mt-3 text-sm font-medium text-[var(--ui-ink-strong)]",children: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(qe,{children:"Log meals plus energy, gut, and look check-ins for a few days to generate pattern candidates."})})})]})}function Rt({experiments:e}){return a.jsxs(q,{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(Ya,{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(P,{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(qe,{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 Wt({view:e}){const t=e.dataQuality,n=e.todayLedger;return a.jsxs(q,{className:"grid gap-4 border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-5",children:[a.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--ui-ink-faint)]",children:"Data quality"}),a.jsx("h2",{className:"mt-1 text-xl font-semibold text-[var(--ui-ink-strong)]",children:"Confidence, coverage, and next evidence"})]}),a.jsxs($,{tone:"meta",children:[e.summary.dataQualityScore.toFixed(0),"% coverage"]})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[a.jsx(Bt,{label:"Source confidence",value:t.sourceConfidence,children:"Food parsing stays candidate-based until accepted; wearable burn is treated as a trend input."}),a.jsxs(P,{children:[a.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:"Missing check-ins"}),a.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:t.missingHighValueCheckins.length>0?t.missingHighValueCheckins.map(r=>a.jsx($,{tone:"signal",children:r},r)):a.jsx("span",{className:"text-sm text-[var(--ui-ink-soft)]",children:"Core evidence loop is covered."})})]}),a.jsxs(P,{children:[a.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:"Next best cue"}),a.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:t.notes}),a.jsxs("div",{className:"mt-3 text-xs text-[var(--ui-ink-faint)]",children:[n.unconfirmedCount," unconfirmed candidate",n.unconfirmedCount===1?"":"s"]})]})]})]})}function Bt({label:e,value:t,children:n}){return a.jsxs(P,{children:[a.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:e}),a.jsx("div",{className:"mt-2 text-lg font-semibold text-[var(--ui-ink-strong)]",children:t}),a.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--ui-ink-soft)]",children:n})]})}const Q={id:"hall_niddk_linearized_adult_12w",label:"Hall/NIDDK linearized adult model",defaultPlanningHorizonDays:84,steadyStateKcalPerKgPerDay:10/.45359237,timeConstantDays:365,staticEnergyDensityKcalPerKg:7700};function Ie(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:null}function ya(e={}){const t=Ie(e.planningHorizonDays)??Q.defaultPlanningHorizonDays,n=Ie(e.timeConstantDays)??Q.timeConstantDays,r=Ie(e.steadyStateKcalPerKgPerDay)??Q.steadyStateKcalPerKgPerDay,s=1-Math.exp(-t/n);return{planningHorizonDays:t,timeConstantDays:n,steadyStateKcalPerKgPerDay:r,responseFraction:s}}function ja(e,t={}){if(typeof e!="number"||!Number.isFinite(e))return null;if(e===0)return 0;const n=ya(t);return n.responseFraction<=0?null:e*(n.planningHorizonDays/7)*n.steadyStateKcalPerKgPerDay/n.responseFraction}function Ht(e,t={}){if(typeof e!="number"||!Number.isFinite(e))return null;if(e===0)return 0;const n=ya(t);return e/n.steadyStateKcalPerKgPerDay*n.responseFraction/(n.planningHorizonDays/7)}function zt(e){return typeof e!="number"||!Number.isFinite(e)?null:e*Q.staticEnergyDensityKcalPerKg/7}function B(e,t,n){return a.jsxs("li",{className:"grid gap-0.5",children:[a.jsx("span",{className:"font-medium text-[var(--ui-ink)]",children:e}),a.jsx("code",{className:"rounded-[6px] bg-[var(--ui-surface-2)] px-1.5 py-0.5 font-mono text-[11px] text-[var(--ui-ink-soft)]",children:t}),n?a.jsx("span",{className:"text-xs text-[var(--ui-ink-faint)]",children:n}):null]})}function ka({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:[B("Mifflin-St Jeor resting baseline",`10 x weight kg + 6.25 x height cm - 5 x age ${r}`,`Current formula value: ${i(e==null?void 0:e.bmrKcal)} kcal/day.`),B("Resting calories","Mifflin-St Jeor formula baseline; HealthKit basal is complete-day evidence only",`Using: ${i(e==null?void 0:e.restingKcal)} kcal/day${e!=null&&e.restingSource?` (${e.restingSource})`:""}.`),B("Maintenance calories","resting calories + active calories",`${i(e==null?void 0:e.restingKcal)} + ${i(e==null?void 0:e.activeKcal)} = ${i(e==null?void 0:e.maintenanceKcal)} kcal/day.`),B("Objective adjustment","Hall/NIDDK linearized adult model, inverted over the planning horizon",`Weekly rate ${H(e==null?void 0:e.weeklyRateKg,2)} kg/week gives ${H(e==null?void 0:e.dailyAdjustmentKcal)} kcal/day${e!=null&&e.rateModel?` with ${e.rateModel}`:""}${e!=null&&e.rateModelHorizonDays?` over ${e.rateModelHorizonDays} days`:""}.`),B("Daily calorie target","max(sex floor, maintenance + objective adjustment)",`Floor ${i(e==null?void 0:e.calorieFloor)} kcal; target ${i(e==null?void 0:e.calorieTarget)} kcal/day.`),B("Protein target",`min(reference weight x ${s}, 45% of kcal / 4)`,`Reference ${i(e==null?void 0:e.proteinReferenceWeightKg,1)} kg; target ${i(e==null?void 0:e.proteinGrams)} g/day.`),B("Fat target","saved plan fat when present; otherwise min(remaining kcal after protein, 35% kcal / 9, max(0.6g/kg reference, 25% kcal / 9))",`Target ${i(e==null?void 0:e.fatGrams)} g/day.`),B("Carbohydrate target","(calorie target - protein g x 4 - fat g x 9) / 4",`Target ${i(e==null?void 0:e.carbohydrateGrams)} g/day. The 130g DRI is shown as reference, not forced if it breaks calories.`),B("Fiber target","14g per 1000 kcal; adult sex/age AI shown as reference",`Target ${i(e==null?void 0:e.fiberGrams)} g/day; energy-adjusted ${i(e==null?void 0:e.fiberEnergyAdjustedGrams)} g/day; adult AI reference ${i(e==null?void 0:e.fiberDriGrams)} g/day.`),B("Sport-loss estimate","training hours ~= active kcal / 500; sweat ~= 0.4-0.8 L/h; sodium ~= 500-1000 mg/L","Shown as expected loss ranges, not rigid supplement instructions.")]})]})})}function Na(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 he(e,t){const n=typeof e=="string"?Number(e):_(e);return typeof n=="number"&&Number.isFinite(n)?n:t}function qt(e){return Na(e.target.notes,"sex")==="female"?"female":"male"}function Ot(e){return he(Na(e.target.notes,"age_years"),35)}function h(e,t,n,r,s,l){return{id:e,label:t,target:typeof n=="number"?He(n):n,unit:r,note:s,source:l}}function He(e){return Number.isFinite(e)?Math.abs(e)>=100?e.toFixed(0):e.toFixed(1).replace(/\.0$/,""):"n/a"}function oe(e,t){return`${He(e)}-${He(t)}`}function Ut(e,t,n,r){const s=Math.round(n/1e3*14);return r>0?r:s}function Qt({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 Zt(e,t){return e==="male"?t>=51?14:17:t>=51?11:12}function Vt(e,t){const n=t>70,r=t>=51;return[h("vitamin_a","Vitamin A",e==="male"?900:700,"ug RAE","Retinol activity equivalent target.","NASEM DRI"),h("vitamin_c","Vitamin C",e==="male"?90:75,"mg","Adult RDA.","NASEM DRI"),h("vitamin_d","Vitamin D",n?20:15,"ug","Assumes limited sun exposure; older adults need more.","NASEM DRI"),h("vitamin_e","Vitamin E",15,"mg alpha-tocopherol","Adult RDA.","NASEM DRI"),h("vitamin_k","Vitamin K",e==="male"?120:90,"ug","Adult AI.","NASEM DRI"),h("thiamin_b1","Thiamin B1",e==="male"?1.2:1.1,"mg","Adult RDA.","NASEM DRI"),h("riboflavin_b2","Riboflavin B2",e==="male"?1.3:1.1,"mg","Adult RDA.","NASEM DRI"),h("niacin_b3","Niacin B3",e==="male"?16:14,"mg NE","Adult RDA.","NASEM DRI"),h("vitamin_b6","Vitamin B6",r?e==="male"?1.7:1.5:1.3,"mg","RDA rises after 50.","NASEM DRI"),h("folate","Folate",400,"ug DFE","Adult RDA.","NASEM DRI"),h("vitamin_b12","Vitamin B12",2.4,"ug","Adult RDA.","NASEM DRI"),h("pantothenic_acid","Pantothenic acid",5,"mg","Adult AI.","NASEM DRI"),h("biotin","Biotin",30,"ug","Adult AI.","NASEM DRI"),h("choline","Choline",e==="male"?550:425,"mg","Adult AI.","NASEM DRI")]}function Yt(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[h("calcium","Calcium",n,"mg","Bone and muscle target; higher for older adults and women 51+.","NASEM DRI"),h("iron","Iron",e==="female"&&t<=50?18:8,"mg","Menstruating-age female target is higher.","NASEM DRI"),h("magnesium","Magnesium",r,"mg","Adult RDA.","NASEM DRI"),h("phosphorus","Phosphorus",700,"mg","Adult RDA.","NASEM DRI"),h("zinc","Zinc",e==="male"?11:8,"mg","Adult RDA.","NASEM DRI"),h("iodine","Iodine",150,"ug","Adult RDA.","NASEM DRI"),h("selenium","Selenium",55,"ug","Adult RDA.","NASEM DRI"),h("copper","Copper",.9,"mg","Adult RDA.","NASEM DRI"),h("manganese","Manganese",e==="male"?2.3:1.8,"mg","Adult AI.","NASEM DRI"),h("chromium","Chromium",s,"ug","Adult AI.","NASEM DRI"),h("molybdenum","Molybdenum",45,"ug","Adult RDA.","NASEM DRI"),h("fluoride","Fluoride",e==="male"?4:3,"mg","Adult AI.","NASEM DRI"),h("chloride","Chloride",l,"mg","Adult AI.","NASEM DRI"),h("potassium","Potassium",e==="male"?3400:2600,"mg","Current adult AI for non-pregnant adults.","NASEM DRI"),h("sodium_limit","Sodium ceiling",2300,"mg max","Default daily ceiling unless medically individualized.","U.S. Dietary Guidelines")]}function Jt(e){const t=qt(e),n=Ot(e),r=he(e.weightTrend.latestWeightKg,80),s=Math.max(1,he(e.target.calorieTarget,2200)),l=he(e.target.proteinGramsTarget,r*1.8),{carbs:g,fat:c}=Qt({calorieTarget:s,currentWeightKg:r,protein:l,savedFat:_(e.target.fatGramsTarget)}),o=Ut(t,n,s,he(e.target.fiberGramsTarget,0)),u=_(e.energyModel.activeBurnKcal)??_(e.energyModel.activeEnergyCalories)??null,p=_(e.energyModel.movementCaloriesKcal),K=_(e.energyModel.restingEnergyCalories);return wa({sex:t,ageYears:n,currentWeightKg:r,calorieTarget:s,proteinGramsTarget:l,carbohydrateGramsTarget:g,fatGramsTarget:c,fiberGramsTarget:o,activeBurnKcal:u,movementCaloriesKcal:p,restingEnergyKcal:K})}function wa(e){const{sex:t,ageYears:n,currentWeightKg:r,calorieTarget:s,proteinGramsTarget:l,carbohydrateGramsTarget:g,fatGramsTarget:c,fiberGramsTarget:o,activeBurnKcal:u,movementCaloriesKcal:p,restingEnergyKcal:K}=e,k=u!=null?Math.min(4,Math.max(.1,u/500)):null,b=k!=null?k*.4:null,y=k!=null?k*.8:null,x=b!=null?b*500:null,N=y!=null?y*1e3:null,E=b!=null?b*78:null,R=y!=null?y*312:null,I=u!=null?Ht(u):null;return{profile:{sex:t,ageYears:n,currentWeightKg:r,calorieTarget:s,activeBurnKcal:u,movementCaloriesKcal:p,restingEnergyKcal:K},macros:[h("calories","Calories",s,"kcal","Plan target from BMR, active burn, and chosen weekly rate.","Forge plan"),h("protein","Protein",l,"g","Higher than the population RDA to preserve lean mass during weight change.","ISSN + Forge plan"),h("carbohydrate","Carbohydrate",g,"g","Remaining fuel after protein and fat. It may sit below the 130g/day adult DRI reference when needed to preserve the calorie target.","NASEM DRI + Forge plan"),h("fat","Total fat",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"),h("fiber","Fiber",o,"g","Uses 14g per 1000 kcal as the plan target; the sex/age adult AI remains a reference or stretch value when calories are low.","NASEM DRI"),h("saturated_fat","Saturated fat",s*.1/9,"g max","Keep below 10% of energy.","U.S. Dietary Guidelines"),h("added_sugar","Added sugar",s*.1/4,"g max","Keep below 10% of energy; lower is better when feasible.","U.S. Dietary Guidelines"),h("linoleic_acid","Linoleic acid",Zt(t,n),"g","Essential n-6 fatty acid AI.","NASEM DRI"),h("ala","ALA omega-3",t==="male"?1.6:1.1,"g","Essential n-3 fatty acid AI.","NASEM DRI"),h("water","Total water",t==="male"?3.7:2.7,"L","All beverages and food water before extra training replacement.","NASEM DRI")],vitamins:Vt(t,n),minerals:Yt(t,n),sportLosses:[h("training_time","Estimated training time",k??"n/a","h/day","Derived from active burn at roughly 500 kcal/h.","Forge sport-loss model"),h("sweat_fluid","Expected sweat fluid",b!=null&&y!=null?oe(b,y):"n/a","L/day","Planning range uses 0.4-0.8 L/h; measure body mass change to calibrate.","ACSM"),h("sweat_sodium","Expected sweat sodium",x!=null&&N!=null?oe(x,N):"n/a","mg/day","Sodium varies widely; this uses a conservative range around common sweat sodium values.","ACSM + Sports Medicine review"),h("sweat_potassium","Expected sweat potassium",E!=null&&R!=null?oe(E,R):"n/a","mg/day","Potassium is usually much smaller than sodium but useful for long/hot sessions.","Sports Medicine review"),h("gross_sport_equivalent","Gross sport burn equivalent",I??"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:k,fluidLossLiters:b!=null&&y!=null?oe(b,y):"n/a",sodiumLossMg:x!=null&&N!=null?oe(x,N):"n/a",potassiumLossMg:E!=null&&R!=null?oe(E,R):"n/a",grossSportWeightEquivalentKgPerWeek:I}}}function Pe({rows:e,compact:t=!1}){return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"grid gap-2 md:hidden",children:e.map(n=>a.jsxs("div",{className:"grid min-w-0 gap-2 rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-3",children:[a.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[a.jsx("div",{className:"min-w-0 break-words text-sm font-semibold text-[var(--ui-ink)]",children:n.label}),a.jsxs("div",{className:"shrink-0 text-right text-sm font-semibold text-[var(--ui-ink)]",children:[n.target,a.jsx("div",{className:"text-xs font-normal text-[var(--ui-ink-faint)]",children:n.unit})]})]}),a.jsx("p",{className:"min-w-0 break-words text-xs leading-5 text-[var(--ui-ink-muted)]",children:n.note}),t?null:a.jsx($,{tone:"meta",wrap:!0,className:"justify-self-start",children:n.source})]},n.id))}),a.jsx("div",{className:"hidden overflow-hidden rounded-[20px] border border-[var(--ui-border-subtle)] md:block",children:a.jsx("div",{className:"max-h-[460px] overflow-auto",children:a.jsxs("table",{className:"w-full min-w-[620px] border-collapse text-left text-sm",children:[a.jsx("thead",{className:"sticky top-0 bg-[var(--ui-surface-2)] text-xs uppercase text-[var(--ui-ink-faint)]",children:a.jsxs("tr",{children:[a.jsx("th",{className:"px-4 py-3 font-semibold",children:"Target"}),a.jsx("th",{className:"px-4 py-3 font-semibold",children:"Amount"}),a.jsx("th",{className:"px-4 py-3 font-semibold",children:"Rationale"}),t?null:a.jsx("th",{className:"px-4 py-3 font-semibold",children:"Source"})]})}),a.jsx("tbody",{className:"divide-y divide-[var(--ui-border-subtle)]",children:e.map(n=>a.jsxs("tr",{className:"bg-[var(--ui-surface-1)]",children:[a.jsx("td",{className:"px-4 py-3 font-medium text-[var(--ui-ink)]",children:n.label}),a.jsxs("td",{className:"px-4 py-3 text-[var(--ui-ink)]",children:[a.jsx("span",{className:"font-semibold",children:n.target})," ",a.jsx("span",{className:"text-[var(--ui-ink-faint)]",children:n.unit})]}),a.jsx("td",{className:"px-4 py-3 text-[var(--ui-ink-muted)]",children:n.note}),t?null:a.jsx("td",{className:"px-4 py-3",children:a.jsx($,{tone:"meta",children:n.source})})]},n.id))})]})})})]})}function me({title:e,description:t,children:n}){return a.jsxs(P,{children:[a.jsxs("div",{className:"mb-4",children:[a.jsx("h3",{className:"text-sm font-semibold text-[var(--ui-ink)]",children:e}),a.jsx("p",{className:"mt-1 text-sm text-[var(--ui-ink-muted)]",children:t})]}),n]})}function Xt({view:e}){const t=Jt(e),n=e.target.weeklyRateGoalKg??null,r=n!=null&&Number.isFinite(n)?ja(n):null,s=t.profile.restingEnergyKcal,l=t.profile.activeBurnKcal,g=s!=null&&l!=null?s+l:null,c=e.target.bodyGoal??"maintain",o=c.includes("lose")?2:c.includes("gain")?1.8:1.6,u=b=>{var N;const y=(N=t.macros.find(E=>E.id===b))==null?void 0:N.target,x=Number(y);return Number.isFinite(x)?x:null},p=t.profile.sex==="male"?t.profile.ageYears>=51?30:38:t.profile.ageYears>=51?21:25,K=Math.round(t.profile.calorieTarget/1e3*14),k=t.sportSummary.grossSportWeightEquivalentKgPerWeek!=null?`${t.sportSummary.grossSportWeightEquivalentKgPerWeek.toFixed(2)} kg/week`:"n/a";return a.jsx("section",{className:"grid gap-4",children:a.jsxs(q,{className:"p-5",children:[a.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-[var(--ui-ink)]",children:[a.jsx(Ja,{className:"size-4 text-[var(--ui-accent)]"}),"Macro And Micronutrient Targets",a.jsx(ka,{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:Q.label,rateModelHorizonDays:Q.defaultPlanningHorizonDays,calorieTarget:t.profile.calorieTarget,calorieFloor:t.profile.sex==="male"?1500:1200,proteinReferenceWeightKg:null,proteinFactor:o,proteinGrams:u("protein"),fatGrams:u("fat"),carbohydrateGrams:u("carbohydrate"),fiberGrams:u("fiber"),fiberEnergyAdjustedGrams:K,fiberDriGrams:p}})]}),a.jsx("p",{className:"mt-1 max-w-3xl text-sm text-[var(--ui-ink-muted)]",children:"Daily targets use Forge plan values first, then adult DRI/Dietary Guidelines defaults for nutrients the food log can score as catalog detail improves."})]}),a.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.jsxs($,{tone:"signal",children:[t.profile.calorieTarget.toFixed(0)," kcal"]}),a.jsxs($,{tone:"meta",children:[t.profile.sex,", ",t.profile.ageYears.toFixed(0),"y"]})]})]}),a.jsxs("div",{className:"mt-5 grid gap-4 2xl:grid-cols-[minmax(0,1fr)_minmax(320px,0.58fr)]",children:[a.jsxs("div",{className:"grid gap-4",children:[a.jsx(me,{title:"All macro targets",description:"Calories, protein, carbs, fat, fiber, sugar ceiling, saturated fat ceiling, essential fats, and water.",children:a.jsx(Pe,{rows:t.macros,compact:!0})}),a.jsx(me,{title:"Vitamins",description:"Adult daily vitamin targets from DRI values, adjusted for sex and age where the reference differs.",children:a.jsx(Pe,{rows:t.vitamins})})]}),a.jsxs("div",{className:"grid content-start gap-4",children:[a.jsxs(me,{title:"Expected sport losses",description:"Planning range from active burn. Calibrate with pre/post workout weight when possible.",children:[a.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[a.jsx(C,{label:"Active burn",value:t.profile.activeBurnKcal!=null?`${t.profile.activeBurnKcal.toFixed(0)} kcal`:"n/a"}),a.jsx(C,{label:"Sport equivalent",value:k}),a.jsx(C,{label:"Sweat fluid",value:`${t.sportSummary.fluidLossLiters} L`}),a.jsx(C,{label:"Sodium loss",value:`${t.sportSummary.sodiumLossMg} mg`})]}),a.jsxs("div",{className:"mt-4 flex items-start gap-3 rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-3 text-sm text-[var(--ui-ink-muted)]",children:[a.jsx(va,{className:"mt-0.5 size-4 shrink-0 text-[var(--ui-accent)]"}),a.jsx("span",{children:"Sport burn is shown as gross energy equivalent, not a promise of scale loss. The calorie plan may already include active burn, and replacement depends on appetite, heat, sodium loss, and actual intake."})]})]}),a.jsx(me,{title:"Minerals & oligoelements",description:"Daily mineral and trace-element targets including sodium ceiling and potassium AI.",children:a.jsx(Pe,{rows:t.minerals,compact:!0})}),a.jsx(me,{title:"Sport electrolyte model",description:"Use these as expected losses, not rigid supplement prescriptions.",children:a.jsx("div",{className:"grid gap-3",children:t.sportLosses.map(b=>a.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-[18px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-3",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-[var(--ui-ink)]",children:[b.id==="sweat_fluid"?a.jsx(Xa,{className:"size-4 text-[var(--ui-accent)]"}):a.jsx(et,{className:"size-4 text-[var(--ui-accent)]"}),b.label]}),a.jsx("p",{className:"mt-1 text-xs text-[var(--ui-ink-faint)]",children:b.note})]}),a.jsxs("div",{className:"shrink-0 text-right text-sm font-semibold text-[var(--ui-ink)]",children:[b.target,a.jsx("div",{className:"text-xs font-normal text-[var(--ui-ink-faint)]",children:b.unit})]})]},b.id))})})]})]})]})})}function 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 z(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>0?t:null}function Ca(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 Ma(e,t){return t==="gain"?e*1.03:t==="maintain"?e:e*.95}function Fa(e){return e.toFixed(1)}function en(e,t){return e==="male"?t>=51?30:38:t>=51?21:25}function an(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 oa(e,t){const n=e/100;return n>0?t*n*n:null}function tn(e){const t=e.goalMode==="lose"&&e.goalWeightKg!=null?Math.min(e.currentWeightKg,e.goalWeightKg):e.currentWeightKg,n=oa(e.heightCm,30),r=oa(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 nn(e,t){const n=z(e.currentWeightKg)??80;return{...e,goalMode:t,goalWeightKg:Fa(Ma(n,t)),weeklyRateKg:Ca(n,t).toFixed(2)}}function Re(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)??z(le(n.notes,"activity_kcal"))??0,c=n.bodyGoal??"",o=c.includes("gain")?"gain":c.includes("maintain")?"maintain":"lose",u=n.weightGoalKg??n.goalBodyWeightKg??null,p=t??80;return{goalMode:o,sex:r==="female"?"female":"male",ageYears:z(s)?String(s):"",heightCm:z(l)?String(l):"",currentWeightKg:t?t.toFixed(1):"",goalWeightKg:u?String(u):Fa(Ma(p,o)),weeklyRateKg:n.weeklyRateGoalKg!==null&&n.weeklyRateGoalKg!==void 0?String(Math.abs(n.weeklyRateGoalKg)):Ca(p,o).toFixed(2),activeCaloriesKcal:g.toFixed(0),restingCaloriesKcal:_(e.energyModel.formulaRestingKcal)!=null?String(_(e.energyModel.formulaRestingKcal)):"",dietStyle:n.dietStyle??""}}function rn(e){const t=z(le(e.target.notes,"age_years"))!=null,n=z(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 sn(e){const t=e.energyModel,n=t.activeBaselineEvidenceDays>0?`Forge is averaging ${t.activeBaselineEvidenceDays} measured prior day${t.activeBaselineEvidenceDays===1?"":"s"} inside the past ${t.activeBaselineWindowDays} days, excluding today and ignoring missing sync days instead of counting them as zero.`:`Forge has no measured prior-day active evidence in the past ${t.activeBaselineWindowDays} days, so it is falling back to the saved plan estimate.`,r=t.energySourceConfidence==="healthkit_daily_active_energy"?"HealthKit daily active energy is the active-burn source; workout and movement values are only visible evidence and are not added again.":t.energySourceConfidence==="workout_movement_fallback"?"HealthKit daily active energy is missing, so active burn already equals workout average plus movement-trip average.":"No measured active-burn stream is available, so Forge is using the saved plan estimate.";return`This is the baseline active allowance used when today has no same-day workout, movement, step, or active-energy evidence. ${n} ${r} Current evidence: active burn ${i(t.activeBurnKcal)} kcal/day, workout average ${i(t.workoutEnergyKcal)} kcal/day, movement average ${i(t.movementCaloriesKcal)} kcal/day, today's workout ${i(t.todayWorkoutEnergyKcal)} kcal, today's movement ${i(t.todayMovementCaloriesKcal)} kcal.`}function Ka(e){const t=Number(e.currentWeightKg)||80,n=Number(e.heightCm)||178,r=Number(e.ageYears)||35,s=z(e.goalWeightKg),l=Math.max(0,Number(e.activeCaloriesKcal)||0),g=an({sex:e.sex,ageYears:r,heightCm:n,weightKg:t})??10*t+6.25*n-5*r+5,c=g,o=c+l,u=Math.abs(Number(e.weeklyRateKg)||0),p=e.goalMode==="lose"?-u:e.goalMode==="gain"?u:0,K=ja(p)??0,k=zt(p)??0,b=e.sex==="male"?1500:1200,y=Math.round(o+K),x=Math.max(b,y),N=tn({currentWeightKg:t,goalWeightKg:s,heightCm:n,goalMode:e.goalMode}),E=e.goalMode==="lose"?2:e.goalMode==="gain"?1.8:1.6,R=Math.round(N*E),I=Math.floor(x*.45/4),Z=Math.max(1,Math.min(R,I)),W=N*.6,V=x*.25/9,O=Math.max(0,(x-Z*4)/9),J=Math.max(0,Math.floor(Math.min(O,x*.35/9,Math.max(W,V)))),X=Math.max(0,Math.floor((x-Z*4-J*9)/4)),ee=Math.round(x/1e3*14),ae=en(e.sex,r),te=ee,ne=Math.round(x*.1/9),ie=Math.round(x*.1/4);return{bmr:Math.round(g),restingCalories:Math.round(c),restingSource:"Mifflin-St Jeor baseline",activeCalories:Math.round(l),maintenanceCalories:Math.round(o),plannedCalorieTarget:y,minimumCalorieFloor:b,weeklyRateGoalKg:p,dailyEnergyAdjustment:Math.round(K),staticDailyEnergyAdjustment:Math.round(k),rateModel:Q.id,rateModelLabel:Q.label,rateModelPlanningHorizonDays:Q.defaultPlanningHorizonDays,calorieTarget:x,proteinReferenceWeight:Math.round(N*10)/10,proteinGramsTarget:Z,carbohydrateGramsTarget:X,fatGramsTarget:J,fiberGramsTarget:te,fiberEnergyAdjustedGrams:ee,fiberDriGrams:ae,saturatedFatLimitGrams:ne,addedSugarLimitGrams:ie}}function on(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,o=e.restingCaloriesKcal.trim()?Number(e.restingCaloriesKcal):null;return(!Number.isFinite(n)||n<13||n>100)&&t.push("- Enter the user's real age. Forge uses it in Mifflin-St Jeor resting metabolism."),(!Number.isFinite(r)||r<120||r>230)&&t.push("- Enter height in cm. Height changes BMR and protein reference weight."),(!Number.isFinite(s)||s<30||s>300)&&t.push("- Enter current weight in kg. Use the latest known body measure as the starting state."),e.goalMode!=="maintain"&&(!Number.isFinite(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."),o!=null&&(!Number.isFinite(o)||o<900||o>3500)&&t.push("- Formula resting baseline should stay in a plausible daily range."),t.length>0?t.join(`
|
|
2
|
-
`):null}function ln(e){const t=Ka(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 cn({open:e,onOpenChange:t,view:n,value:r,onChange:s,onSubmit:l,pending:g,error:c}){const o=F.useMemo(()=>Ka(r),[r]),u=z(r.ageYears)!=null&&z(r.heightCm)!=null&&z(r.currentWeightKg)!=null,p=u?String(o.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: ${o.bmr} kcal.`:"Forge will calculate this from real age, height, sex, and current weight. Complete HealthKit basal energy stays evidence/calibration, not the silent default.",k=F.useMemo(()=>wa({sex:r.sex,ageYears:Number(r.ageYears)||35,currentWeightKg:Number(r.currentWeightKg)||80,calorieTarget:o.calorieTarget,proteinGramsTarget:o.proteinGramsTarget,carbohydrateGramsTarget:o.carbohydrateGramsTarget,fatGramsTarget:o.fatGramsTarget,fiberGramsTarget:o.fiberGramsTarget,activeBurnKcal:o.activeCalories,movementCaloriesKcal:_(n.energyModel.movementCaloriesKcal),restingEnergyKcal:o.restingCalories}),[o,r,n.energyModel.movementCaloriesKcal]),b=[{id:"profile",eyebrow:"Current state",title:"Confirm the body data Forge knows",description:"These fields drive resting metabolism. Saved values are reused when Forge has them.",render:(y,x)=>a.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[a.jsx(j,{label:"Sex",children:a.jsx(ia,{value:y.sex,onChange:N=>x({sex:N}),options:[{value:"male",label:"Male"},{value:"female",label:"Female"}]})}),a.jsx(j,{label:"Age",children:a.jsx(w,{inputMode:"numeric",value:y.ageYears,onChange:N=>x({ageYears:N.target.value}),placeholder:"35"})}),a.jsx(j,{label:"Height cm",children:a.jsx(w,{inputMode:"decimal",value:y.heightCm,onChange:N=>x({heightCm:N.target.value}),placeholder:"178"})}),a.jsx(j,{label:"Current weight kg",children:a.jsx(w,{inputMode:"decimal",value:y.currentWeightKg,onChange:N=>x({currentWeightKg:N.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:(y,x)=>a.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[a.jsx("div",{className:"md:col-span-2",children:a.jsx(ia,{columns:3,value:y.goalMode,onChange:N=>x(nn(y,N)),options:[{value:"lose",label:"Lose fat",description:"Default: about 0.5% body weight per week."},{value:"gain",label:"Gain mass",description:"Default: small surplus around 0.25% per week."},{value:"maintain",label:"Maintain",description:"Hold weight while optimizing signals."}]})}),a.jsx(j,{label:"Target weight kg",hint:"Filled from the objective; change it anytime.",children:a.jsx(w,{inputMode:"decimal",value:y.goalWeightKg,onChange:N=>x({goalWeightKg:N.target.value}),placeholder:"75.0"})}),a.jsx(j,{label:"Weekly change kg",hint:"Loss/gain rate is converted to kcal/day with the Hall/NIDDK adult dynamic model over Forge's 12-week planning horizon.",children:a.jsx(w,{inputMode:"decimal",value:y.weeklyRateKg,onChange:N=>x({weeklyRateKg:N.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:(y,x)=>a.jsxs("div",{className:"grid gap-4",children:[a.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[a.jsx(j,{label:"Formula resting baseline/day",hint:K,children:a.jsx(w,{inputMode:"decimal",value:p,readOnly:!0,placeholder:"Calculated from profile"})}),a.jsx(j,{label:"Average active calories/day",hint:sn(n),children:a.jsx(w,{inputMode:"decimal",value:y.activeCaloriesKcal,onChange:N=>x({activeCaloriesKcal:N.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(C,{label:o.restingSource,value:`${o.restingCalories} kcal`}),a.jsx(C,{label:"Maintenance",value:`${o.maintenanceCalories} kcal`}),a.jsx(C,{label:"Daily adjustment",value:`${o.dailyEnergyAdjustment>0?"+":""}${o.dailyEnergyAdjustment} kcal`})]})]})},{id:"macros",eyebrow:"Macros",title:"Validate calories, macros, and limits",description:"Target intake equals resting burn plus active burn plus the objective adjustment. Macros are generated from protein-per-kg, a practical fat floor, remaining carbohydrates, fiber density, and dietary limits.",render:(y,x)=>a.jsxs("div",{className:"grid gap-4",children:[a.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-[20px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] px-4 py-3",children:[a.jsx("div",{className:"min-w-0 text-sm leading-6 text-[var(--ui-ink-muted)]",children:"Inspect the exact math behind the current calories, macro targets, and sport-loss preview."}),a.jsx(ka,{values:{sex:y.sex,ageYears:Number(y.ageYears)||null,currentWeightKg:Number(y.currentWeightKg)||null,heightCm:Number(y.heightCm)||null,bmrKcal:o.bmr,restingKcal:o.restingCalories,restingSource:o.restingSource,activeKcal:o.activeCalories,maintenanceKcal:o.maintenanceCalories,weeklyRateKg:o.weeklyRateGoalKg,dailyAdjustmentKcal:o.dailyEnergyAdjustment,rateModel:o.rateModelLabel,rateModelHorizonDays:o.rateModelPlanningHorizonDays,calorieTarget:o.calorieTarget,calorieFloor:o.minimumCalorieFloor,proteinReferenceWeightKg:o.proteinReferenceWeight,proteinFactor:y.goalMode==="lose"?2:y.goalMode==="gain"?1.8:1.6,proteinGrams:o.proteinGramsTarget,fatGrams:o.fatGramsTarget,carbohydrateGrams:o.carbohydrateGramsTarget,fiberGrams:o.fiberGramsTarget,fiberEnergyAdjustedGrams:o.fiberEnergyAdjustedGrams,fiberDriGrams:o.fiberDriGrams}})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-4 xl:grid-cols-7",children:[a.jsx(C,{label:"Calories",value:`${o.calorieTarget}`}),a.jsx(C,{label:"Protein",value:`${o.proteinGramsTarget}g`}),a.jsx(C,{label:"Carbs",value:`${o.carbohydrateGramsTarget}g`}),a.jsx(C,{label:"Fat",value:`${o.fatGramsTarget}g`}),a.jsx(C,{label:"Fiber",value:`${o.fiberGramsTarget}g`}),a.jsx(C,{label:"Sat fat max",value:`${o.saturatedFatLimitGrams}g`}),a.jsx(C,{label:"Added sugar max",value:`${o.addedSugarLimitGrams}g`})]}),a.jsxs("div",{className:"grid gap-4 rounded-[24px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-4",children:[a.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-sm font-semibold text-[var(--ui-ink)]",children:"Micronutrient and sport-loss preview"}),a.jsx("div",{className:"mt-1 text-sm leading-6 text-[var(--ui-ink-muted)]",children:"The dashboard will track vitamin, mineral, trace-element, water, sodium-ceiling, essential-fat, and sport-loss targets from this plan."})]}),a.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.jsxs($,{tone:"meta",children:[k.vitamins.length," vitamins"]}),a.jsxs($,{tone:"meta",children:[k.minerals.length," minerals"]}),a.jsxs($,{tone:"signal",children:[k.sportSummary.fluidLossLiters," L sweat"]})]})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[a.jsx(C,{label:"Sport sodium loss",value:`${k.sportSummary.sodiumLossMg} mg`}),a.jsx(C,{label:"Sport potassium loss",value:`${k.sportSummary.potassiumLossMg} mg`}),a.jsx(C,{label:"Water baseline",value:r.sex==="male"?"3.7 L":"2.7 L"}),a.jsx(C,{label:"Essential fats",value:r.sex==="male"?"17g LA / 1.6g ALA":"12g LA / 1.1g ALA"})]})]}),a.jsx(j,{label:"Diet style or constraints",children:a.jsx(Ce,{value:y.dietStyle,onChange:N=>x({dietStyle:N.target.value}),placeholder:"Mediterranean, high protein, no lactose, low FODMAP trial..."})})]})}];return a.jsx(Fe,{open:e,onOpenChange:t,eyebrow:"Weight plan",title:"Set weight objective",description:"Build an editable calorie and macro plan.",value:r,onChange:s,steps:b,onSubmit:l,submitLabel:"Save plan",pending:g,pendingLabel:"Saving plan",error:c,draftPersistenceKey:"weight-loss-plan"})}const dn={tsp:5,tbsp:15,cup:240};function Ne(){return{mealLabel:"",notes:"",source:"search",selectedItems:[]}}function A(e,t,n){return typeof e!="number"||!Number.isFinite(e)?null:Ga(n)==="grams"?e:t>0?Math.round(e/t*10)/10:e}function un(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 gn(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 mn(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 be(e){return typeof e.servingGrams=="number"&&Number.isFinite(e.servingGrams)&&e.servingGrams>0?e.servingGrams:mn(e.servingLabel)}function hn(e){const t=be(e);return t!=null?`${i(t)} g`:e.servingLabel??"serving"}function Sa(e){const t=Number(e.amount)||0;if(t<=0)return null;const n=be(e.food);return e.unit==="grams"?t:e.unit==="tsp"||e.unit==="tbsp"||e.unit==="cup"?t*dn[e.unit]:n!=null?t*n:null}function la(e){return!(e.unit==="grams"||e.unit==="tsp"||e.unit==="tbsp"||e.unit==="cup")||be(e.food)!=null?null:"Add base grams before using grams or household measures. Without a denominator, Forge will not guess a ratio."}function Ga(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 pn(e){switch(e){case"manual":case"search":case"barcode":case"chatgpt":case"photo":case"saved_meal":return e;default:return"manual"}}function bn(e){return{mealLabel:e.mealLabel??"",notes:e.notes??"",loggedAt:e.loggedAt,dayKey:e.dayKey,source:pn(e.source),selectedItems:e.items.map(t=>({localId:t.id,food:un(t),amount:String(t.quantity||1),unit:t.unit??"serving"}))}}function xn(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:gn(n,r,t),amount:String(n.quantity||1),unit:Ga(n.unit)}))}}function Aa(){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 fn(){return{mealLabel:"",notes:"",source:"manual",selectedItems:[{localId:`custom-${Date.now()}`,food:Aa(),amount:"100",unit:"grams"}]}}function vn({open:e,onOpenChange:t,value:n,onChange:r,foodResults:s,searchPending:l,chatGptPending:g=!1,chatGptError:c=null,logPending:o,onSearch:u,onParseWithChatGpt:p,onSubmit:K,mode:k="create",intent:b="search",initialStepId:y}){const[x,N]=F.useState(""),[E,R]=F.useState(""),[I,Z]=F.useState(null),W=F.useMemo(()=>Cn(n.selectedItems),[n.selectedItems]),V=f=>r({...n,...f}),O=f=>{V({selectedItems:[...n.selectedItems,{localId:`${f.id}-${Date.now()}`,food:f,amount:"1",unit:"serving"}]}),Z(null)},J=()=>{O(Aa())},X=async()=>{const f=E.trim();!f||!p||(await p(f),R(""))},ee=(f,v)=>{V({selectedItems:n.selectedItems.map(S=>S.localId===f?{...S,...v}:S)})},ae=(f,v)=>{V({selectedItems:n.selectedItems.map(S=>S.localId===f?{...S,food:{...S.food,...v}}:S)})},te=f=>{V({selectedItems:n.selectedItems.filter(v=>v.localId!==f)})},ne=async()=>{n.selectedItems.length!==0&&await K()},ie=a.jsxs(P,{className:"grid gap-3",children:[a.jsx(j,{label:"Ask ChatGPT",labelHelp:"Uses the connected OpenAI Codex OAuth / ChatGPT subscription model to create a reviewable candidate meal draft. It does not use the metered OpenAI Platform API.",children:a.jsx(Ce,{value:E,onChange:f=>R(f.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.jsxs(G,{type:"button",variant:b==="chatgpt"?"primary":"secondary",pending:g,pendingLabel:"Parsing",disabled:!E.trim()||!p,onClick:()=>void X(),children:[a.jsx(pa,{className:"size-4"}),"Parse with ChatGPT"]})]}),ue=a.jsx(P,{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:J,children:[a.jsx(ze,{className:"size-4"}),"Add custom"]})]})}),Ke=b==="chatgpt"?[ie,ue]:[ue,ie],xe=[{id:"search",eyebrow:b==="chatgpt"?"ChatGPT food parser":"Food",title:b==="chatgpt"?"Describe the meal, then review every item":"Search, create, or ask ChatGPT",description:b==="chatgpt"?"ChatGPT creates a candidate meal through the subscription-backed connection; you still review quantities and nutrients before saving.":"Search the catalog, create a custom food, or use ChatGPT to turn rough meal text into editable items.",render:()=>a.jsxs("div",{className:"grid gap-4",children:[a.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_auto]",children:[a.jsx(j,{label:"Food search",labelHelp:"Search returns food candidates with per-serving nutrition. Click a result to inspect macros before adding it to the meal draft.",children:a.jsx(w,{value:x,onChange:f=>N(f.target.value),placeholder:"Search eggs, yogurt, sourdough..."})}),a.jsxs(G,{type:"button",variant:"secondary",pending:l,disabled:!x.trim(),onClick:()=>u(x),children:[a.jsx(ba,{className:"size-4"}),"Search"]})]}),a.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:Ke.map((f,v)=>a.jsx("div",{children:f},`${b}-assistant-panel-${v}`))}),I?a.jsx(wn,{food:I,onAdd:()=>O(I)}):null,a.jsx("div",{className:"grid gap-3",children:s.map(f=>a.jsx(P,{interactive:!0,className:"p-0",children:a.jsx("button",{type:"button",className:"block w-full rounded-[22px] p-4 text-left",onClick:()=>Z(f),children:a.jsxs("div",{className:"flex items-start justify-between gap-3",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsx("div",{className:"truncate text-sm font-semibold text-[var(--ui-ink-strong)]",children:f.name}),a.jsx("div",{className:"mt-1 truncate text-xs text-[var(--ui-ink-faint)]",children:[f.brand,f.servingLabel,f.source].filter(Boolean).join(" · ")})]}),a.jsxs($,{tone:"meta",children:[i(f.calories)," kcal"]})]})})},f.id))})]})},{id:"amounts",eyebrow:b==="custom"?"Custom food":"Quantity",title:b==="custom"?"Define the food and exact dose":"Set exactly how much you ate",description:"Scale by grams, servings, household measures, or units before saving the meal.",render:f=>a.jsxs("div",{className:"grid gap-4",children:[f.selectedItems.length===0?a.jsx("div",{className:"rounded-[22px] border border-dashed border-[var(--ui-border-strong)] bg-[var(--ui-surface-1)] p-5 text-sm text-[var(--ui-ink-soft)]",children:"Add at least one food from the search step."}):null,f.selectedItems.map(v=>a.jsxs(P,{className:"grid gap-3",children:[a.jsxs("div",{className:"flex items-start justify-between gap-3",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-sm font-semibold text-[var(--ui-ink-strong)]",children:v.food.name}),a.jsxs("div",{className:"text-xs text-[var(--ui-ink-faint)]",children:["Base: ",i(v.food.calories)," kcal per"," ",hn(v.food)]})]}),a.jsxs(G,{type:"button",size:"sm",variant:"ghost",onClick:()=>te(v.localId),children:[a.jsx(fa,{className:"size-4"}),"Remove"]})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto]",children:[a.jsx(j,{label:"Quantity",labelHelp:"This is the amount actually eaten. Forge converts the selected unit to an eaten gram equivalent when base grams are known, then scales every nutrient by eaten grams divided by base grams.",children:a.jsx(w,{inputMode:"decimal",value:v.amount,onChange:S=>ee(v.localId,{amount:S.target.value}),placeholder:"1"})}),a.jsx(j,{label:"Unit",labelHelp:"Servings multiply the base serving. Grams, teaspoons, tablespoons, and cups use a gram conversion table and require base grams.",children:a.jsxs("select",{className:"interactive-tap w-full rounded-[22px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-4 py-3 text-[15px] text-[var(--ui-ink-strong)] outline-none",value:v.unit,onChange:S=>ee(v.localId,{unit:S.target.value}),children:[a.jsx("option",{value:"serving",children:"serving"}),a.jsx("option",{value:"grams",children:"grams"}),a.jsx("option",{value:"unit",children:"unit"}),a.jsx("option",{value:"tsp",children:"teaspoon"}),a.jsx("option",{value:"tbsp",children:"tablespoon"}),a.jsx("option",{value:"cup",children:"cup"})]})}),a.jsxs($,{tone:"signal",children:[i(Me(v).calories)," kcal"]})]}),la(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:la(v)}):a.jsxs("div",{className:"text-xs text-[var(--ui-ink-faint)]",children:[i(Number(v.amount)||0)," ",v.unit," ="," ",i(Sa(v))," g eaten; ratio ="," ",i(Me(v).scale),"x the base nutrition."]}),a.jsx(Nn,{item:v,onChange:S=>ae(v.localId,S)})]},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(C,{label:"Calories",value:i(W.calories)}),a.jsx(C,{label:"Protein",value:`${i(W.proteinGrams)}g`}),a.jsx(C,{label:"Carbs",value:`${i(W.carbohydrateGrams)}g`}),a.jsx(C,{label:"Fat",value:`${i(W.fatGrams)}g`})]})]})},{id:"context",eyebrow:"Context",title:"Meal label and notes",description:"Add how it felt, where it happened, or anything relevant to future pattern detection.",render:(f,v)=>a.jsxs("div",{className:"grid gap-4",children:[a.jsxs(j,{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(S=>a.jsx(G,{type:"button",size:"sm",variant:f.mealLabel===S?"primary":"secondary",onClick:()=>v({mealLabel:S}),children:S},S)),a.jsx(G,{type:"button",size:"sm",variant:"ghost",onClick:()=>v({mealLabel:""}),children:"Clear"})]}),a.jsx(w,{value:f.mealLabel,onChange:S=>v({mealLabel:S.target.value}),placeholder:"Breakfast, lunch, snack, dinner, or blank"})]}),a.jsx(j,{label:"Notes",labelHelp:"Use notes for context the numbers do not capture: hunger, cravings, gut comfort, energy, timing, place, or workout relationship.",children:a.jsx(Ce,{value:f.notes,onChange:S=>v({notes:S.target.value}),placeholder:"Energy, cravings, gut comfort, training effect..."})})]})}];return a.jsx(Fe,{open:e,onOpenChange:t,eyebrow:"Food log",title:k==="edit"?"Edit food":"Add food",description:"Search, inspect, scale, edit nutrition parameters, and save meal items.",value:n,onChange:r,steps:xe,initialStepId:y,onSubmit:ne,submitLabel:k==="edit"?"Update meal":"Save meal",pending:o,pendingLabel:"Saving meal",resolveError:f=>f!=="search"&&n.selectedItems.length===0?"Select at least one food before saving.":null,draftPersistenceKey:`weight-loss-food-log.${k}.${b}`})}function Da(e,t={}){return{loggedAt:e.loggedAt,dayKey:e.dayKey??t.dateKey??null,timeZone:e.timeZone??t.timeZone,mealLabel:ca(e.mealLabel),source:e.source??"search",confirmationState:"confirmed",notes:ca(e.notes),items:e.selectedItems.map(n=>{const r=Me(n);return{foodId:yn(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 ca(e,t=""){return typeof e=="string"?e:t}function yn(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 jn(e,t={}){return Da(e,t)}function kn(e){const t=Number(e);return Number.isFinite(t)?t:null}function Nn({item:e,onChange:t}){const n=e.food,r=(s,l)=>t({[s]:kn(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(j,{label:"Base label",labelHelp:"Human-readable denominator shown for the nutrition values, such as 100 g, 220 g, one burger, or one scoop.",children:a.jsx(w,{value:n.servingLabel??"",onChange:s=>t({servingLabel:s.target.value||null}),placeholder:"100 g"})}),a.jsx(j,{label:"Base grams",labelHelp:"Gram denominator for the base nutrition values. If kcal is per 220 g, enter 220. If kcal is per 100 g, enter 100.",children:a.jsx(w,{inputMode:"decimal",value:n.servingGrams??"",onChange:s=>r("servingGrams",s.target.value),placeholder:"100"})}),a.jsx(j,{label:"Food name",labelHelp:"Rename the item when the database result is too generic or wrong.",children:a.jsx(w,{value:n.name,onChange:s=>t({name:s.target.value})})}),a.jsx(j,{label:"Brand",labelHelp:"Optional brand or preparation source, useful when the same food has different nutrition.",children:a.jsx(w,{value:n.brand??"",onChange:s=>t({brand:s.target.value||null})})})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[a.jsx(j,{label:"kcal",labelHelp:"Kilocalories for the base amount above. Forge multiplies this by eaten grams divided by base grams, so 2 g of a 220 g base is not treated as 2 servings.",children:a.jsx(w,{inputMode:"decimal",value:n.calories??"",onChange:s=>r("calories",s.target.value)})}),a.jsx(j,{label:"Protein g",labelHelp:"Protein grams for the base amount above. This is scaled by the same gram ratio as calories.",children:a.jsx(w,{inputMode:"decimal",value:n.proteinGrams??"",onChange:s=>r("proteinGrams",s.target.value)})}),a.jsx(j,{label:"Carbs g",labelHelp:"Carbohydrate grams for the base amount above. Carbs are training fuel after protein and fat are allocated.",children:a.jsx(w,{inputMode:"decimal",value:n.carbohydrateGrams??"",onChange:s=>r("carbohydrateGrams",s.target.value)})}),a.jsx(j,{label:"Fat g",labelHelp:"Fat grams for the base amount above. Fat supports the practical floor and AMDR context in the plan.",children:a.jsx(w,{inputMode:"decimal",value:n.fatGrams??"",onChange:s=>r("fatGrams",s.target.value)})}),a.jsx(j,{label:"Fiber g",labelHelp:"Fiber grams for the base amount above. Forge compares this to the 14g per 1000 kcal planning target.",children:a.jsx(w,{inputMode:"decimal",value:n.fiberGrams??"",onChange:s=>r("fiberGrams",s.target.value)})}),a.jsx(j,{label:"Sugar g",labelHelp:"Sugar grams for the base amount above. Added sugar is tracked as a ceiling, not a goal.",children:a.jsx(w,{inputMode:"decimal",value:n.sugarGrams??"",onChange:s=>r("sugarGrams",s.target.value)})}),a.jsx(j,{label:"Sodium mg",labelHelp:"Sodium milligrams for the base amount above. Sodium affects daily ceiling, sport loss replacement, and water retention hypotheses.",children:a.jsx(w,{inputMode:"decimal",value:n.sodiumMg??"",onChange:s=>r("sodiumMg",s.target.value)})})]})]})}function wn({food:e,onAdd:t}){return a.jsxs(q,{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(ze,{className:"size-4"}),"Add"]})]}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[a.jsx(C,{label:"Calories",value:i(e.calories)}),a.jsx(C,{label:"Protein",value:`${i(e.proteinGrams)}g`}),a.jsx(C,{label:"Carbs",value:`${i(e.carbohydrateGrams)}g`}),a.jsx(C,{label:"Fat",value:`${i(e.fatGrams)}g`}),a.jsx(C,{label:"Fiber",value:`${i(e.fiberGrams)}g`}),a.jsx(C,{label:"Sugar",value:`${i(e.sugarGrams)}g`}),a.jsx(C,{label:"Sodium",value:`${i(e.sodiumMg)}mg`}),a.jsx(C,{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(at,{className:"size-4"}),"Base grams: ",i(be(e)),". Adjust exact intake in the next step."]})]})}function Me(e){const t=Number(e.amount)||0,n=be(e.food),r=Sa(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 Cn(e){return e.reduce((t,n)=>{const r=Me(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 da(){return{weightKg:"",waistCm:"",bodyFatPercent:"",energy:"",hunger:"",cravings:"",bloating:"",facePuffiness:"",leanness:"",notes:""}}function Mn({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,o)=>a.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[a.jsx(j,{label:"Weight kg",children:a.jsx(w,{inputMode:"decimal",value:c.weightKg,onChange:u=>o({weightKg:u.target.value})})}),a.jsx(j,{label:"Waist cm",children:a.jsx(w,{inputMode:"decimal",value:c.waistCm,onChange:u=>o({waistCm:u.target.value})})}),a.jsx(j,{label:"Body fat %",children:a.jsx(w,{inputMode:"decimal",value:c.bodyFatPercent,onChange:u=>o({bodyFatPercent:u.target.value})})})]})},{id:"state",eyebrow:"State",title:"Energy, appetite, and gut",description:"These subjective signals are what make the view more useful than a calorie ledger.",render:(c,o)=>a.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[a.jsx(j,{label:"Energy 0-10",children:a.jsx(w,{inputMode:"decimal",value:c.energy,onChange:u=>o({energy:u.target.value})})}),a.jsx(j,{label:"Hunger 0-10",children:a.jsx(w,{inputMode:"decimal",value:c.hunger,onChange:u=>o({hunger:u.target.value})})}),a.jsx(j,{label:"Cravings 0-10",children:a.jsx(w,{inputMode:"decimal",value:c.cravings,onChange:u=>o({cravings:u.target.value})})}),a.jsx(j,{label:"Bloating 0-10",children:a.jsx(w,{inputMode:"decimal",value:c.bloating,onChange:u=>o({bloating:u.target.value})})}),a.jsx(j,{label:"Face puffiness 0-10",children:a.jsx(w,{inputMode:"decimal",value:c.facePuffiness,onChange:u=>o({facePuffiness:u.target.value})})}),a.jsx(j,{label:"Leanness 0-10",children:a.jsx(w,{inputMode:"decimal",value:c.leanness,onChange:u=>o({leanness:u.target.value})})})]})},{id:"notes",eyebrow:"Context",title:"Notes",description:"Capture anything that explains the signal.",render:(c,o)=>a.jsx(j,{label:"Notes",children:a.jsx(Ce,{value:c.notes,onChange:u=>o({notes:u.target.value}),placeholder:"Sleep, sodium, workout soreness, stressful day..."})})}];return a.jsx(Fe,{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 Fn(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 Kn(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 Sn(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 Gn({open:e,onOpenChange:t,meals:n,onLogAgain:r,onEdit:s,onDelete:l,pending:g}){return a.jsx(Fe,{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(P,{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:Kn(c)}),a.jsxs("div",{className:"mt-1 text-xs text-[var(--ui-ink-faint)]",children:[c.loggedAt.slice(0,10)," ·"," ",Sn(c)||c.mealLabel||"No quantity recorded"]})]}),a.jsxs($,{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 An(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 Dn(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 _n(e){const t=e.energyModel,n=t.recentFoodLogDayCount>0?`${t.recentFoodLogCount} recent food log${t.recentFoodLogCount===1?"":"s"} across ${t.recentFoodLogDayCount} logged day${t.recentFoodLogDayCount===1?"":"s"}`:"no recent logged food days";if(t.estimatedTdeeKcal==null)return`No TDEE estimate yet. Average logged intake is ${i(t.averageCalorieIntake)} kcal/day from ${n}.`;const r=`Recent average balance: intake ${i(t.averageCalorieIntake)} - TDEE ${i(t.estimatedTdeeKcal)} = ${H(t.estimatedDailyEnergyBalanceKcal)} kcal/day.`,s=t.restingEnergyCalories!=null&&t.activeBurnKcal!=null?`TDEE = formula resting baseline ${i(t.restingEnergyCalories)} + active burn ${i(t.activeBurnKcal)}.`:`TDEE is falling back to the configured plan estimate ${i(t.inferredTdee)}.`,l=t.energySourceConfidence==="healthkit_daily_active_energy"?`Active burn uses HealthKit daily active energy ${i(t.activeBurnKcal)}; workout and movement are evidence only.`:t.energySourceConfidence==="workout_movement_fallback"?`Active burn fallback = workout ${i(t.workoutEnergyKcal)} + movement ${i(t.movementCaloriesKcal)} = ${i(t.activeBurnKcal)}, so movement is not added again.`:"Active burn is not measured yet.";return`${r} ${s} ${l} Food window: ${n}. Negative means estimated deficit; this is not today's remaining calories.`}function En(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 = ${i(t.activeBurnKcal)} kcal/day`:t.energySourceConfidence==="workout_movement_fallback"?`active burn = workout average ${i(t.workoutEnergyKcal)} + movement-trip average ${i(t.movementCaloriesKcal)} = ${i(t.activeBurnKcal)} kcal/day`:"active burn is not measured; Forge falls back to plan inference",g=t.restingEnergyCalories!=null&&t.activeBurnKcal!=null?`TDEE = formula resting baseline ${i(t.restingEnergyCalories)} + active burn average ${i(t.activeBurnKcal)} = ${i(t.estimatedTdeeKcal)} kcal/day.`:`TDEE = ${i(t.estimatedTdeeKcal)} kcal/day from the configured plan because complete resting + active energy is not available.`,c=t.estimatedTdeeKcal!=null?`Energy gap = average logged intake - TDEE = ${i(t.averageCalorieIntake)} - ${i(t.estimatedTdeeKcal)} = ${H(t.estimatedDailyEnergyBalanceKcal)} kcal/day.`:"Energy gap cannot be computed until Forge has either measured expenditure or an inferred TDEE.",o=t.energySourceConfidence==="healthkit_daily_active_energy"?`selected active burn = HealthKit daily active energy average = ${i(t.activeBurnKcal)} kcal/day. Workout and movement are visible as evidence but are not added.`:t.energySourceConfidence==="workout_movement_fallback"?`selected active burn = workout average ${i(t.workoutEnergyKcal)} + movement-trip average ${i(t.movementCaloriesKcal)} = ${i(t.activeBurnKcal)} kcal/day. This is why movement can appear next to active burn: it is a component of active burn here, not a separate add-on.`:"selected active burn is unavailable, so TDEE falls back to the configured plan estimate.",u=t.restingEnergyCalories!=null&&t.activeBurnKcal!=null&&t.estimatedTdeeKcal!=null?t.energySourceConfidence==="healthkit_daily_active_energy"?`Arithmetic shown here: active burn ${i(t.activeBurnKcal)} = HealthKit daily active energy average; TDEE ${i(t.estimatedTdeeKcal)} = formula resting baseline ${i(t.restingEnergyCalories)} + active burn ${i(t.activeBurnKcal)}; energy gap ${H(t.estimatedDailyEnergyBalanceKcal)} = intake ${i(t.averageCalorieIntake)} - TDEE ${i(t.estimatedTdeeKcal)}.`:t.energySourceConfidence==="workout_movement_fallback"?`Arithmetic shown here: active burn ${i(t.activeBurnKcal)} = workout ${i(t.workoutEnergyKcal)} + movement ${i(t.movementCaloriesKcal)}; TDEE ${i(t.estimatedTdeeKcal)} = formula resting baseline ${i(t.restingEnergyCalories)} + active burn ${i(t.activeBurnKcal)}; energy gap ${H(t.estimatedDailyEnergyBalanceKcal)} = intake ${i(t.averageCalorieIntake)} - TDEE ${i(t.estimatedTdeeKcal)}.`:`Arithmetic shown here: TDEE ${i(t.estimatedTdeeKcal)} = formula resting baseline ${i(t.restingEnergyCalories)} + active burn ${i(t.activeBurnKcal)}; energy gap ${H(t.estimatedDailyEnergyBalanceKcal)} = intake ${i(t.averageCalorieIntake)} - TDEE ${i(t.estimatedTdeeKcal)}.`:"Arithmetic shown here uses the available expenditure branch; some terms are unavailable because Forge does not yet have both resting and active energy evidence.",p=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.",k=`Today is separate: today's target = baseline plan target plus the day-specific active adjustment. Today active evidence currently uses ${_a(t.todayActiveCaloriesSource)}: ${i(t.todayActiveCaloriesKcal)} kcal. Default active calories: ${i(t.baselineActiveCaloriesKcal)} kcal. Eat-back fraction ${i(t.activityEatBackFraction*100,0)}%; target adjustment ${H(t.todayTargetAdjustmentKcal)} kcal. Automatic low or early same-day activity cannot reduce the target; a manual override can raise or lower it for this date.`,b=t.energySourceConfidence==="healthkit_daily_active_energy"?"Data path: recent food logs provide intake; HealthKit daily active-energy rows provide active burn; Mifflin-St Jeor provides the stable resting baseline. Complete HealthKit basal rows are shown as calibration evidence.":t.energySourceConfidence==="workout_movement_fallback"?"Data path: recent food logs provide intake; Mifflin-St Jeor provides the stable resting baseline; workout-session energy plus movement-trip calories provide fallback active burn.":"Data path: recent food logs provide intake; expenditure is using the configured plan inference because measured expenditure streams are incomplete.";return a.jsxs("span",{className:"grid gap-2",children:[a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"What this card means:"})," ","this is a historical energy-balance estimate, not the remaining food budget for today. Negative means estimated deficit; positive means estimated surplus."]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Formula:"})," ",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:"})," ",o]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Arithmetic:"})," ",u]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Why these numbers:"})," ","The displayed movement value is therefore"," ",t.energySourceConfidence==="workout_movement_fallback"?"part of the active-burn calculation":"supporting evidence only",", and it is not the same thing as today's editable active-calorie budget."]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Current data:"})," ","intake ",i(t.averageCalorieIntake)," kcal/day; TDEE"," ",i(t.estimatedTdeeKcal)," kcal/day; formula resting"," ",i(t.restingEnergyCalories)," kcal/day; active burn"," ",i(t.activeBurnKcal)," kcal/day; workout"," ",i(t.workoutEnergyKcal)," kcal/day; movement"," ",i(t.movementCaloriesKcal)," kcal/day."," ",t.energySourceConfidence==="workout_movement_fallback"?"On this branch, active burn already equals workout plus movement, so movement is not an extra add-on after active burn.":"On this branch, movement is shown as evidence and is not added on top of active burn."]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Data lineage:"})," ",b]}),a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-[var(--ui-ink-strong)]",children:"Food window:"})," ",p," 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:"})," ",An(t.energySourceConfidence)," across"," ",t.evidenceDays," expenditure evidence day",t.evidenceDays===1?"":"s"," ending the selected day (",r,"). Available streams: ",Dn(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:"})," ",k]})]})}function $n(e){const t=H(e);return t==="n/a"?t:`${t} kcal/d`}function _a(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 ua(e){return`${e>=0?"+":""}${e.toFixed(0)} kcal`}function Tn(e){return e>=0?`${e.toFixed(0)} kcal left`:`${Math.abs(e).toFixed(0)} kcal over`}function ga(e){return e.trim()===""?"0":e}function ma(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,o=e.todayLedger.plannedTargetCalories??e.todayLedger.targetCalories-c,u=Math.max(0,Math.round(o+g)),p=Math.round(e.todayLedger.totals.calories-u),K=Math.round(u-e.todayLedger.totals.calories),k=Math.max(0,l),b=Math.round(k*s);return{...e,summary:{...e.summary,targetCalories:u,todayCalorieDelta:p,remainingCalories:K},todayLedger:{...e.todayLedger,plannedTargetCalories:o,targetCalories:u,activeAdjustmentCalories:g,activeCaloriesSource:"user_override",calorieDelta:p,remainingCalories:K},energyModel:{...e.energyModel,todayActiveCaloriesKcal:t,todayActiveCaloriesSource:"user_override",todayTargetAdjustmentKcal:g,todayActiveDeltaKcal:Math.round(l),todayActiveSurplusKcal:Math.round(k),todayActivityBufferKcal:b,todayActiveOverride:n}}}function Ln(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 ha(e,t){const[n,r,s]=e.split("-").map(Number);return we(new Date(n,r-1,s+t))}function In(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 Pn(){const e=new Date,t=new Date(e);return t.setHours(24,0,2,0),Math.max(1e3,t.getTime()-e.getTime())}function Yn(){const e=ut(),t=lt(),n=e.selectedUserIds,r=F.useMemo(()=>wt(),[]),s=we(),[l,g]=F.useState(()=>we()),c=F.useMemo(()=>Ln(l),[l]),o=F.useMemo(()=>["forge-weight-loss-view",l,r,...n],[l,r,n]),u=l===s,[p,K]=F.useState(!1),[k,b]=F.useState(!1),[y,x]=F.useState(!1),[N,E]=F.useState(!1),[R,I]=F.useState(!1),[Z,W]=F.useState(null),[V,O]=F.useState(null),[J,X]=F.useState(""),[ee,ae]=F.useState(null),[te,ne]=F.useState(null),[ie,ue]=F.useState("search"),[Ke,xe]=F.useState(void 0),[f,v]=F.useState(()=>Ne()),[S,Oe]=F.useState(()=>da()),re=ct({queryKey:o,queryFn:async()=>(await Nt(n,{dateKey:l,...c,timeZone:r})).weightLoss}),T=re.data;F.useEffect(()=>{const d=()=>{u&&g(D=>{const ge=we();return ge===D?D:ge})},m=window.setTimeout(d,Pn());return window.addEventListener("focus",d),document.addEventListener("visibilitychange",d),()=>{window.clearTimeout(m),window.removeEventListener("focus",d),document.removeEventListener("visibilitychange",d)}},[l,u]),F.useEffect(()=>{!T||k||p||rn(T)||(b(!0),ae(Re(T)),W(`Forge needs the missing profile fields before the calorie and macro plan can be trusted.
|
|
3
|
-
|
|
4
|
-
- Confirm age, height, current weight, objective, weekly rate, and active calories.
|
|
5
|
-
- Known HealthKit and movement values are prefilled when available.`),K(!0))},[k,T,p]),F.useEffect(()=>{T&&(X(String(Math.round(T.energyModel.todayActiveCaloriesKcal??0))),O(null))},[T==null?void 0:T.generatedAt,T==null?void 0:T.energyModel.todayActiveCaloriesKcal]);const se=()=>t.invalidateQueries({queryKey:o}),Ea=d=>{X(ga(d))},Se=U({mutationFn:async d=>(await vt({query:d,userIds:n})).foods}),fe=U({mutationFn:async d=>ft({text:d,userIds:n,commitCandidate:!1}),onSuccess:({candidate:d})=>{v({...xn(d,"chatgpt"),dayKey:l,timeZone:r})}}),Ue=U({mutationFn:async d=>ra(Da(d,{dateKey:l,timeZone:r}),n),onSuccess:()=>{v(Ne()),x(!1),se()}}),Qe=U({mutationFn:async({foodLogId:d,draft:m})=>xt(d,jn(m,{dateKey:l,timeZone:r}),n),onSuccess:()=>{v(Ne()),ne(null),x(!1),se()}}),Ge=U({mutationFn:async d=>ht(d.id,n),onSuccess:()=>{se()}}),Ae=U({mutationFn:async d=>pt({dayKey:T==null?void 0:T.todayLedger.dateKey,timeZone:r,activeCaloriesKcal:d,notes:d==null?"":"Manual active-calorie override from the weight-loss view"},n),onMutate:d=>{if(d==null)return null;const m=t.getQueryData(o);return t.setQueryData(o,D=>{var aa,ta;if(!D)return D;const ge=new Date().toISOString();return ma(D,d,{id:((aa=D.energyModel.todayActiveOverride)==null?void 0:aa.id)??"optimistic",userId:D.userId,dayKey:D.todayLedger.dateKey,activeCaloriesKcal:d,notes:"Manual active-calorie override from the weight-loss view",createdAt:((ta=D.energyModel.todayActiveOverride)==null?void 0:ta.createdAt)??ge,updatedAt:ge})}),m?{previous:m}:null},onSuccess:(d,m)=>{O(null),m!=null&&t.setQueryData(o,D=>D&&ma(D,m,d.override)),se()},onError:(d,m,D)=>{D!=null&&D.previous&&t.setQueryData(o,D.previous),O(d instanceof Error?d.message:"Could not save active calories")}}),ve=U({mutationFn:async d=>{const m=Number(d.currentWeightKg);await bt(ln(d),n),Number.isFinite(m)&&await sa({weightKg:m,notes:"Updated from weight-plan setup."},n)},onSuccess:()=>{K(!1),se()}}),Ze=U({mutationFn:async d=>{const m=Fn(d);await Promise.all([m.body.weightKg!==null||m.body.waistCm!==null||m.body.bodyFatPercent!==null?sa(m.body,n):Promise.resolve(),m.subjective.energy!==null||m.subjective.hunger!==null||m.subjective.cravings!==null?yt(m.subjective,n):Promise.resolve(),m.gut.bloating!==null?jt(m.gut,n):Promise.resolve(),m.appearance.facePuffiness!==null||m.appearance.leanness!==null?kt(m.appearance,n):Promise.resolve()])},onSuccess:()=>{Oe(da()),E(!1),se()}}),ye=U({mutationFn:async d=>ra({dayKey:l,timeZone:r,mealLabel:d.mealLabel??"",source:"saved_meal",confirmationState:"confirmed",notes:d.notes??"",items:d.items.map(m=>({foodId:m.foodId,name:m.name,brand:m.brand,quantity:m.quantity,unit:m.unit,grams:m.grams,calories:m.calories,proteinGrams:m.proteinGrams,carbohydrateGrams:m.carbohydrateGrams,fatGrams:m.fatGrams,fiberGrams:m.fiberGrams,sugarGrams:m.sugarGrams,sodiumMg:m.sodiumMg,potassiumMg:m.potassiumMg,caffeineMg:m.caffeineMg,alcoholGrams:m.alcoholGrams,glycemicIndex:m.glycemicIndex,novaGroup:m.novaGroup,fermented:m.fermented,probiotic:m.probiotic,fodmapLevel:m.fodmapLevel,tags:m.tags,confidence:m.confidence??.85}))},n),onSuccess:()=>{se()}});if(re.isLoading)return a.jsx(gt,{title:"Loading weight-loss signals",description:"Combining food logs, HealthKit, movement, workouts, body check-ins, subjective state, and gut signals."});if(re.isError||!re.data)return a.jsx(mt,{error:re.error??new Error("Weight-loss view unavailable"),onRetry:()=>void re.refetch()});const M=re.data,L=M.todayLedger,Ve=L.totals,De=Ve.calories,_e=Number.isFinite(L.remainingCalories)?L.remainingCalories:L.targetCalories-De,$a=L.plannedTargetCalories??L.targetCalories,Ee=M.energyModel.todayActiveCaloriesKcal??M.energyModel.activeBurnKcal??M.energyModel.activeEnergyCalories??M.energyModel.movementCaloriesKcal??0,Ta=M.energyModel.baselineActiveCaloriesKcal??Ee,Ye=L.activeAdjustmentCalories??0,La=Ye===0?"no day-specific active adjustment":`${ua(Ye)} active adjustment from ${_a(L.activeCaloriesSource)}`,Ia=L.targetCalories>0?Math.min(140,Math.max(0,De/L.targetCalories*100)):0,Pa=M.energyModel,Je=M.weightTrend,je=M.foodQuality,$e=M.trainingFuel,Ra=M.subjective,Wa=M.gut,Ba=Mt(M.hypotheses),Te=ee??Re(M),Ha=()=>{W(null),ae(Re(M)),K(!0)},Le=(d="search")=>{ne(null),ue(d),xe(d==="custom"?"amounts":"search");const m=d==="custom"?fn():Ne();v({...m,dayKey:l,timeZone:r}),x(!0)},Xe=d=>{ne(d.id),ue("search"),xe("amounts"),v({...bn(d),timeZone:r}),x(!0),I(!1)},ea=d=>{typeof window<"u"&&!window.confirm(`Delete ${d.mealLabel??"this meal"} from the food log?`)||Ge.mutate(d)},za=()=>{const d=ga(J);X(d);const m=Number(d);if(!Number.isFinite(m)||m<0){O("Enter a valid active-calorie value.");return}Ae.mutate(Math.round(m))},qa=()=>{Ae.mutate(null)};return a.jsxs("div",{className:"mx-auto grid w-full max-w-[1500px] gap-5",children:[a.jsx(dt,{title:"Weight Loss",description:"A guided Forge body composition lab: editable goals, science-based calorie and macro planning, exact food quantities, body measures, energy, gut comfort, look, and testable food hypotheses.",badge:`${L.targetCalories.toFixed(0)} kcal budget · ${M.summary.loggedMealCount} food logs`}),a.jsxs(q,{className:"grid gap-4 border-[var(--ui-border-subtle)] bg-[var(--ui-surface-1)] p-4 md:grid-cols-[minmax(0,1fr)_auto] md:items-center",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.16em] text-[var(--ui-ink-faint)]",children:[a.jsx(tt,{className:"size-4"}),"Food day"]}),a.jsx("div",{className:"mt-1 text-2xl font-semibold text-[var(--ui-ink-strong)]",children:u?"Today":In(l)}),a.jsxs("div",{className:"mt-1 text-sm leading-6 text-[var(--ui-ink-soft)]",children:["Local day ",l," in ",r,". Food logs, manual active calories, target, and kcal left are scoped to this day."]})]}),a.jsxs("div",{className:"grid min-w-0 gap-2 sm:grid-cols-[auto_minmax(0,11rem)_auto_auto]",children:[a.jsx(G,{type:"button",variant:"secondary",onClick:()=>g(ha(l,-1)),"aria-label":"Previous day",children:a.jsx(nt,{className:"size-4"})}),a.jsx("input",{type:"date",value:l,onChange:d=>{d.target.value&&g(d.target.value)},"aria-label":"Selected food day",className:"interactive-tap min-h-10 min-w-0 rounded-[8px] border border-[var(--ui-border-subtle)] bg-[var(--ui-surface-2)] px-3 text-sm font-medium text-[var(--ui-ink-strong)] outline-none"}),a.jsx(G,{type:"button",variant:"secondary",disabled:u,onClick:()=>g(s),children:"Today"}),a.jsx(G,{type:"button",variant:"secondary",onClick:()=>g(ha(l,1)),"aria-label":"Next day",children:a.jsx(rt,{className:"size-4"})})]})]}),a.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(340px,0.85fr)]",children:[a.jsx(It,{ledger:L,remainingCalories:_e,intakePercent:Ia,logSavedPending:ye.isPending||Ge.isPending,onLogAgain:d=>ye.mutate(d),onEditMeal:Xe,onDeleteMeal:ea}),a.jsxs("div",{className:"grid min-w-0 gap-4",children:[a.jsx(Ct,{view:M,onOpenPlan:Ha,onOpenFoodSearch:()=>Le("search"),onOpenCustomFood:()=>Le("custom"),onOpenChatGptFood:()=>Le("chatgpt"),onOpenCheckin:()=>E(!0),onOpenHistory:()=>I(!0)}),a.jsx(At,{view:M,draftValue:J,pending:Ae.isPending,error:V,onDraftChange:Ea,onSave:za,onReset:qa})]})]}),a.jsxs("section",{className:"grid gap-4 xl:grid-cols-4",children:[a.jsx(Y,{label:u?"Today":"Selected day",value:`${De.toFixed(0)} / ${L.targetCalories.toFixed(0)} kcal`,detail:`${Tn(_e)}. Target uses ${Ee.toFixed(0)} active kcal for this day; ${La}.`,icon:na,tone:_e>=0?"green":"rose",help:`Today's target = baseline plan target plus the day-specific active adjustment. Here: ${$a.toFixed(0)} ${ua(M.energyModel.todayTargetAdjustmentKcal)} = ${L.targetCalories.toFixed(0)} kcal. Same-day evidence is ${Ee.toFixed(0)} kcal versus default ${Ta.toFixed(0)} kcal. Automatic partial evidence can only add above the baseline; a manual override can raise or lower today's target for this date.`}),a.jsx(Y,{label:"Protein",value:`${Ve.proteinGrams.toFixed(0)}g`,detail:`${M.target.proteinGramsTarget.toFixed(0)}g target. Protein anchors the plan while cutting or gaining.`,icon:st,help:"Protein grams are compared with the plan target, which uses g/kg body-weight logic and caps impossible values inside the calorie target."}),a.jsx(Y,{label:"Energy gap",value:$n(Pa.estimatedDailyEnergyBalanceKcal),detail:_n(M),icon:it,tone:"amber",help:En(M),helpMaxWidthPx:560}),a.jsx(Y,{label:"Weight trend",value:H(Je.sevenDayRateKg,2),detail:`Latest ${i(Je.latestWeightKg,1)} kg. Trend uses check-ins, not noisy single weigh-ins.`,icon:We,tone:"green",help:"Weight trend uses recent body check-ins to estimate direction. Single weigh-ins can jump from water, sodium, gut content, and training inflammation."})]}),a.jsx(Wt,{view:M}),a.jsx(Xt,{view:M}),a.jsxs("section",{className:"grid gap-4 xl:grid-cols-4",children:[a.jsx(Y,{label:"Food quality",value:ke(je.qualityScore),detail:`Fiber density ${i(je.fiberPer1000Kcal,1)}g/1000 kcal, protein density ${i(je.proteinPer1000Kcal,1)}g/1000 kcal, ultra-processed share ${i(je.ultraProcessedShare,0)}%.`,icon:na,tone:"green",help:"Food quality combines density and exposure signals such as fiber per 1000 kcal, protein per 1000 kcal, ultra-processed share, sodium, sugar, and available micronutrient evidence."}),a.jsx(Y,{label:"Training fuel",value:ke($e.fuelingScore),detail:`Recent workout load ${i($e.recentTrainingLoad)} with ${i($e.carbsPerTrainingLoad,1)}g carbs per load unit.`,icon:va,tone:"amber",help:"Training fuel relates carbohydrate and protein timing to recent workout load. It is meant to find performance and recovery patterns, not force a fixed carb rule."}),a.jsx(Y,{label:"Subjective",value:ke(Ra.averageFocus),detail:"Focus, energy, hunger, cravings, and performance are tracked as food-effect evidence.",icon:We,help:"Subjective signals are self-rated energy, focus, hunger, cravings, and performance. Forge uses them to discover food and timing effects."}),a.jsx(Y,{label:"Gut",value:ke(Wa.averageBloating),detail:"Bloating, reflux, stool type, and suspected triggers connect food choices to comfort and look.",icon:ot,tone:"rose",help:"Gut signals include bloating, reflux, stool type, and suspected triggers. They help connect foods to comfort, water retention, and appearance hypotheses."})]}),a.jsxs("section",{className:"grid gap-4 xl:grid-cols-[minmax(0,1fr)_minmax(360px,0.8fr)]",children:[a.jsx(Pt,{hypotheses:Ba}),a.jsx(Rt,{experiments:M.experiments})]}),a.jsx(cn,{open:p,onOpenChange:K,view:M,value:Te,onChange:d=>{ae(d),W(null)},pending:ve.isPending,error:Z??(ve.error instanceof Error?ve.error.message:null),onSubmit:async()=>{const d=on(Te);if(d){W(d);return}await ve.mutateAsync(Te)}}),a.jsx(vn,{open:y,onOpenChange:x,value:f,onChange:v,foodResults:Se.data??[],searchPending:Se.isPending,chatGptPending:fe.isPending,chatGptError:fe.error instanceof Error?fe.error.message:null,logPending:Ue.isPending||Qe.isPending,intent:ie,initialStepId:Ke,onSearch:d=>Se.mutate(d),onParseWithChatGpt:d=>fe.mutateAsync(d).then(()=>{}),mode:te?"edit":"create",onSubmit:async()=>{if(te){await Qe.mutateAsync({foodLogId:te,draft:f});return}await Ue.mutateAsync(f)}}),a.jsx(Mn,{open:N,onOpenChange:E,value:S,onChange:Oe,pending:Ze.isPending,onSubmit:async()=>{await Ze.mutateAsync(S)}}),a.jsx(Gn,{open:R,onOpenChange:I,meals:M.recentMeals,pending:ye.isPending||Ge.isPending,onLogAgain:d=>ye.mutate(d),onEdit:Xe,onDelete:ea})]})}export{Yn as WeightLossPage};
|