Rotate back to portrait RepTotal is built for portrait on mobile.
RepTotal RepTotal

Macro Calculator

Calculate daily calories and macros with science-backed formulas. Includes BMR, TDEE, macro split logic, per-meal planning, and practical coaching guidance.

Basic info

Goal and activity

How this is calculated

Step 1: BMR (Mifflin-St Jeor)
Mifflin-St Jeor uses sex, weight, height, and age. Males: 10*kg + 6.25*cm - 5*age + 5. Females: 10*kg + 6.25*cm - 5*age - 161.

Step 2: TDEE
Total Daily Energy Expenditure is your BMR multiplied by your activity factor.

Step 3: Calorie target
A deficit means eating below maintenance. A surplus means eating above maintenance. Maintenance uses your estimated TDEE.

Step 4: Macro split
Protein is set by bodyweight and goal. Fat is set as a % of calories. Carbs use remaining calories.

RepTotal Macro Targets
RepTotal
RepTotal Your macro target export

Daily macro targets

Generated from the RepTotal Macro Calculator using your current inputs. This export is for guidance and planning, not medical advice.

${escapeHtml(exportDate)} ${escapeHtml(result.goalLabel)} ${escapeHtml(result.activityLabel)} ${escapeHtml(result.trainingLabel)}
Calories
${escapeHtml(result.calories)} kcal per day
Protein
${escapeHtml(result.protein)} ${escapeHtml(result.proteinKg)}
Carbs
${escapeHtml(result.carbs)} ${escapeHtml(result.carbsPct)} of intake
Fat
${escapeHtml(result.fat)} ${escapeHtml(result.fatPct)} of intake

Macro split

Protein${escapeHtml(result.proteinPct)}
Carbs${escapeHtml(result.carbsPct)}
Fat${escapeHtml(result.fatPct)}

Daily support targets

${escapeHtml(result.fiber)}Fiber
${escapeHtml(result.water)}Water

Per meal

${escapeHtml(result.mealCalories)}Calories
${escapeHtml(result.mealProtein)}Protein
${escapeHtml(result.mealCarbs)}Carbs
${escapeHtml(result.mealFat)}Fat

Calculation summary

${escapeHtml(result.bmr)}${escapeHtml(result.bmrMethod)}
${escapeHtml(result.tdee)}TDEE
${escapeHtml(adjustmentText)}${escapeHtml(result.adjustmentLabel)}
${escapeHtml(result.meals)}Meals per day
Disclaimer: This calculator provides estimates for informational purposes only and does not constitute medical or dietary advice.
`; } function drawRoundedRect(doc, x, y, w, h, fillColor, radius = 6) { doc.setFillColor(...fillColor); doc.setDrawColor(...fillColor); doc.roundedRect(x, y, w, h, radius, radius, "F"); } function drawTargetIcon(doc, centerX, centerY, strokeColor) { doc.setDrawColor(...strokeColor); doc.setLineWidth(0.7); doc.circle(centerX, centerY, 5.2); doc.circle(centerX, centerY, 2.8); doc.line(centerX - 7, centerY, centerX - 3.8, centerY); doc.line(centerX + 3.8, centerY, centerX + 7, centerY); doc.line(centerX, centerY - 7, centerX, centerY - 3.8); doc.line(centerX, centerY + 3.8, centerX, centerY + 7); } function hexToRgb(hex) { const value = String(hex || "").replace("#", ""); if (value.length !== 6) return [255, 255, 255]; return [ parseInt(value.slice(0, 2), 16), parseInt(value.slice(2, 4), 16), parseInt(value.slice(4, 6), 16) ]; } function loadStaticImageDataUrl(src, options = {}) { return new Promise((resolve) => { const img = new Image(); img.crossOrigin = "anonymous"; img.onload = () => { try { const canvas = document.createElement("canvas"); canvas.width = img.naturalWidth; canvas.height = img.naturalHeight; const ctx = canvas.getContext("2d"); if (options.rounded) { const radius = Math.max(18, Math.floor(Math.min(canvas.width, canvas.height) * 0.18)); ctx.beginPath(); ctx.moveTo(radius, 0); ctx.lineTo(canvas.width - radius, 0); ctx.quadraticCurveTo(canvas.width, 0, canvas.width, radius); ctx.lineTo(canvas.width, canvas.height - radius); ctx.quadraticCurveTo(canvas.width, canvas.height, canvas.width - radius, canvas.height); ctx.lineTo(radius, canvas.height); ctx.quadraticCurveTo(0, canvas.height, 0, canvas.height - radius); ctx.lineTo(0, radius); ctx.quadraticCurveTo(0, 0, radius, 0); ctx.closePath(); ctx.clip(); } ctx.drawImage(img, 0, 0); resolve(canvas.toDataURL("image/png")); } catch (_error) { resolve(""); } }; img.onerror = () => resolve(""); img.src = src; }); } function loadLogoDataUrl() { if (logoDataUrlPromise) return logoDataUrlPromise; logoDataUrlPromise = loadStaticImageDataUrl("/static/images/reptotal-icon-512.png?v=0.1.0%2B14eb3aeb&logo_v=settings-purple-20260622", { rounded: true }); return logoDataUrlPromise; } function validateInputs() { const missing = []; if (!e.sex.value) missing.push("sex"); if (!e.age.value) missing.push("age"); if (!e.height.value) missing.push("height"); if (!e.weight.value) missing.push("weight"); if (!e.activity.value) missing.push("activity level"); if (!e.goal.value) missing.push("goal"); if (!e.training.value) missing.push("training preference"); if (!e.meals.value) missing.push("meal frequency"); if (missing.length) { setFeedback(`Please complete: ${missing.join(", ")}.`); return false; } return true; } function calculate(shouldScroll = true) { const age = Number(e.age.value || 0); const heightRaw = Number(e.height.value || 0); const weightRaw = Number(e.weight.value || 0); if (!validateInputs()) return; if (!age || !heightRaw || !weightRaw) { setFeedback("Age, height, and weight must be valid numbers."); return; } if (age < 16 || age > 80) { setFeedback("Age must be between 16 and 80."); return; } setFeedback(""); const heightCm = useImperial ? heightRaw * 2.54 : heightRaw; const weightKg = useImperial ? weightRaw * 0.453592 : weightRaw; const bodyFatPct = Number(e.bodyFat.value || 0); const goal = e.goal.value; const training = e.training.value; let bmr = 0; let bmrMethod = "mifflin"; if (advanced && bodyFatPct > 0) { const leanMass = weightKg * (1 - (bodyFatPct / 100)); bmr = 370 + (21.6 * leanMass); bmrMethod = "katch"; } else { const base = (10 * weightKg) + (6.25 * heightCm) - (5 * age); bmr = e.sex.value === "male" ? base + 5 : base - 161; } const tdee = bmr * ACTIVITY_MULTIPLIERS[e.activity.value]; let adjustment = goal === "maintenance" ? 0 : getAdjustment(goal, e.intensity.value); if (advanced && e.customAdjustEnabled.checked) { adjustment = Number(e.customAdjustSlider.value || 0); } const calories = Math.round(tdee * (1 + (adjustment / 100))); let proteinPerKg = getProteinPerKg(goal, training); if (advanced && e.proteinOverrideEnabled.checked) { proteinPerKg = Number(e.proteinOverride.value); } const proteinG = Math.round(weightKg * proteinPerKg); const proteinCals = proteinG * 4; let fatPct = 25; if (advanced && e.fatOverrideEnabled.checked) { fatPct = Number(e.fatOverride.value); } const fatCals = calories * (fatPct / 100); const fatG = Math.round(fatCals / 9); const carbsCals = Math.max(0, calories - proteinCals - fatCals); const carbsG = Math.round(carbsCals / 4); const totalCals = Math.max(1, (proteinG * 4) + (carbsG * 4) + (fatG * 9)); const proteinPct = Math.round((proteinG * 4 / totalCals) * 100); const fatPctCalc = Math.round((fatG * 9 / totalCals) * 100); const carbsPct = Math.max(0, 100 - proteinPct - fatPctCalc); const fiberMin = Math.round((calories / 1000) * 12); const fiberMax = Math.round((calories / 1000) * 16); const water = (Math.round((weightKg * 0.035) * 10) / 10).toFixed(1); const meals = Number(e.meals.value || 3); const perMealCalories = Math.round(calories / meals); const perMealProtein = Math.round(proteinG / meals); const perMealCarbs = Math.round(carbsG / meals); const perMealFat = Math.round(fatG / meals); setText("macropro-result-calories", calories.toLocaleString()); setText("macropro-result-protein", `${proteinG}g`); setText("macropro-result-carbs", `${carbsG}g`); setText("macropro-result-fat", `${fatG}g`); setText("macropro-result-protein-kg", `${proteinPerKg.toFixed(1)}g/kg`); setText("macropro-pct-protein", `${proteinPct}%`); setText("macropro-pct-carbs", `${carbsPct}%`); setText("macropro-pct-fat", `${fatPctCalc}%`); macroRingSet(proteinPct, carbsPct, fatPctCalc); setText("macropro-fiber", `${fiberMin}-${fiberMax}g`); setText("macropro-water", `${water}L`); setText("macropro-meal-count-label", `(${meals} meals/day)`); setText("macropro-meal-calories", `${perMealCalories}`); setText("macropro-meal-protein", `${perMealProtein}g`); setText("macropro-meal-carbs", `${perMealCarbs}g`); setText("macropro-meal-fat", `${perMealFat}g`); setText("macropro-bmr", `${Math.round(bmr)}`); setText("macropro-bmr-method", bmrMethod === "katch" ? "Katch-McArdle" : "Mifflin-St Jeor"); setText("macropro-tdee", `${Math.round(tdee)}`); setText("macropro-adjustment", `${adjustment > 0 ? "+" : ""}${adjustment}%`); setText("macropro-adjustment-label", adjustment < 0 ? "deficit" : (adjustment > 0 ? "surplus" : "maintenance")); const guide = document.getElementById("macropro-training-guide"); const guideConfig = goal === "fat_loss" ? { eyebrow: "Fat-loss guidance", title: "Cut with control", summary: "Keep output sustainable, protein anchored, and training quality high so weight loss does not come at the cost of muscle retention.", chips: ["Protect muscle", "Track trends", "Sustainable deficit"], cards: [ { kicker: "Rate", title: "Steady weekly loss", body: "Aim for roughly 0.5-1% bodyweight loss per week for a result you can hold onto." }, { kicker: "Protein", title: "Keep intake high", body: "A strong protein target helps preserve lean mass and keeps meals more satisfying while dieting." }, { kicker: "Training", title: "Lift to retain shape", body: "Run resistance training 3-4 times per week so your body has a reason to keep muscle." }, { kicker: "Review", title: "Judge trends, not days", body: "Use a 2+ week view of bodyweight, photos, and performance instead of reacting to one off-scale reading." } ] } : goal === "muscle_gain" ? { eyebrow: "Muscle-gain guidance", title: "Grow with quality", summary: "Use a measured surplus, progressive overload, and recovery habits that support performance instead of chasing weight too fast.", chips: ["Controlled surplus", "Performance first", "Recovery matters"], cards: [ { kicker: "Rate", title: "Slow gain wins", body: "Aim for around 0.25-0.5% bodyweight gain per month to bias progress toward muscle instead of excess fat." }, { kicker: "Performance", title: "Track progression", body: "Use progressive overload and compare lifts, reps, and execution from week to week." }, { kicker: "Fuel", title: "Keep carbs available", body: "Carbs support higher-quality training sessions and help you recover between hard efforts." }, { kicker: "Recovery", title: "Sleep like it matters", body: "Prioritize 7-9 hours of sleep so growth, recovery, and appetite regulation stay on your side." } ] } : { eyebrow: "Maintenance guidance", title: "Hold your baseline", summary: "Maintenance is where consistency compounds. Use it to support training quality, sharpen habits, and keep performance steady.", chips: ["Consistency phase", "Performance support", "Habit quality"], cards: [ { kicker: "Purpose", title: "Build consistency", body: "Maintenance is ideal when you want better performance, steadier energy, and less friction in day-to-day nutrition." }, { kicker: "Habits", title: "Clean up the basics", body: "Use this phase to tighten meal structure, food quality, hydration, and routine rather than chasing scale changes." }, { kicker: "Adjust", title: "Nudge, don’t overhaul", body: "If bodyweight drifts for 2-3 weeks, adjust by roughly 100-150 kcal rather than making a large jump." } ] }; guide.innerHTML = `

${guideConfig.eyebrow}

${guideConfig.title}

${guideConfig.summary}

${guideConfig.chips.map((chip) => `${chip}`).join("")}
${guideConfig.cards.map((card) => `

${card.kicker}

${card.title}

${card.body}

`).join("")}
`; const breakdownHtml = `

Step 1: BMR (${bmrMethod === "katch" ? "Katch-McArdle" : "Mifflin-St Jeor"})
${bmrMethod === "katch" ? INFO.katch : INFO.mifflin}

Step 2: TDEE
${INFO.tdee}
Your TDEE: ${Math.round(tdee)} kcal

Step 3: Calorie target
${adjustment < 0 ? INFO.deficit : (adjustment > 0 ? INFO.surplus : "Maintenance uses your estimated TDEE.")}
Target: ${calories} kcal

Step 4: Macro split
Protein: ${proteinPerKg.toFixed(1)}g/kg = ${proteinG}g. Fat: ${fatPct}% of calories = ${fatG}g. Carbs: remaining calories = ${carbsG}g.

`; e.breakdown.innerHTML = breakdownHtml; if (e.previewBreakdown) e.previewBreakdown.innerHTML = breakdownHtml; e.results.hidden = false; if (shouldScroll) { e.results.scrollIntoView({ behavior: "smooth", block: "start" }); } lastResultText = [ "RepTotal Macro Calculator Results", "", `Calories: ${calories} kcal`, `Protein: ${proteinG}g (${proteinPct}%)`, `Carbs: ${carbsG}g (${carbsPct}%)`, `Fat: ${fatG}g (${fatPctCalc}%)`, "", `BMR: ${Math.round(bmr)} kcal (${bmrMethod})`, `TDEE: ${Math.round(tdee)} kcal`, `Adjustment: ${adjustment > 0 ? "+" : ""}${adjustment}%`, `Fiber: ${fiberMin}-${fiberMax}g`, `Water: ${water}L`, "", `Per meal (${meals} meals): ${perMealCalories} kcal / ${perMealProtein}g P / ${perMealCarbs}g C / ${perMealFat}g F` ].join("\\n"); lastExportHtml = buildExportHtml({ calories: calories.toLocaleString(), protein: `${proteinG}g`, proteinKg: `${proteinPerKg.toFixed(1)}g/kg`, carbs: `${carbsG}g`, fat: `${fatG}g`, proteinPct: `${proteinPct}%`, carbsPct: `${carbsPct}%`, fatPct: `${fatPctCalc}%`, fiber: `${fiberMin}-${fiberMax}g`, water: `${water}L`, mealCalories: `${perMealCalories} kcal`, mealProtein: `${perMealProtein}g`, mealCarbs: `${perMealCarbs}g`, mealFat: `${perMealFat}g`, bmr: `${Math.round(bmr)}`, bmrMethod: bmrMethod === "katch" ? "Katch-McArdle" : "Mifflin-St Jeor", tdee: `${Math.round(tdee)} kcal`, adjustment, adjustmentLabel: adjustment < 0 ? "Deficit" : (adjustment > 0 ? "Surplus" : "Maintenance"), meals: `${meals}`, goalLabel: e.goal.options[e.goal.selectedIndex]?.text || "Goal", activityLabel: e.activity.options[e.activity.selectedIndex]?.text || "Activity", trainingLabel: e.training.options[e.training.selectedIndex]?.text || "Training" }); lastExportData = { calories: calories.toLocaleString(), protein: `${proteinG}g`, proteinKg: `${proteinPerKg.toFixed(1)}g/kg`, carbs: `${carbsG}g`, fat: `${fatG}g`, proteinPct: `${proteinPct}%`, carbsPct: `${carbsPct}%`, fatPct: `${fatPctCalc}%`, fiber: `${fiberMin}-${fiberMax}g`, water: `${water}L`, mealCalories: `${perMealCalories} kcal`, mealProtein: `${perMealProtein}g`, mealCarbs: `${perMealCarbs}g`, mealFat: `${perMealFat}g`, bmr: `${Math.round(bmr)}`, bmrMethod: bmrMethod === "katch" ? "Katch-McArdle" : "Mifflin-St Jeor", tdee: `${Math.round(tdee)} kcal`, adjustment: `${adjustment > 0 ? "+" : ""}${adjustment}%`, adjustmentLabel: adjustment < 0 ? "Deficit" : (adjustment > 0 ? "Surplus" : "Maintenance"), meals: `${meals}`, goalLabel: e.goal.options[e.goal.selectedIndex]?.text || "Goal", activityLabel: e.activity.options[e.activity.selectedIndex]?.text || "Activity", trainingLabel: e.training.options[e.training.selectedIndex]?.text || "Training", guide: guideConfig, exportDate: new Date().toLocaleDateString(undefined, { day: "2-digit", month: "short", year: "numeric" }) }; } e.metricBtn.addEventListener("click", () => { useImperial = false; updateUnitUI(); }); e.imperialBtn.addEventListener("click", () => { useImperial = true; updateUnitUI(); }); e.advancedBtn.addEventListener("click", () => { advanced = !advanced; updateAdvancedUI(); }); e.goal.addEventListener("change", () => { fillIntensityOptions(); updateCustomAdjustRange(); updateAdvancedUI(); }); [e.sex, e.age, e.height, e.weight, e.activity, e.goal, e.training, e.meals].forEach((el) => { el.addEventListener("change", () => { if (!e.results.hidden) calculate(false); }); }); e.intensity.addEventListener("change", updateCustomAdjustRange); e.customAdjustEnabled.addEventListener("change", updateAdvancedUI); e.proteinOverrideEnabled.addEventListener("change", updateAdvancedUI); e.fatOverrideEnabled.addEventListener("change", updateAdvancedUI); e.customAdjustSlider.addEventListener("input", updateSliderLabels); e.proteinOverride.addEventListener("input", updateSliderLabels); e.fatOverride.addEventListener("input", updateSliderLabels); e.calculate.addEventListener("click", calculate); e.copyBtn.addEventListener("click", async () => { if (!lastResultText) return; try { await navigator.clipboard.writeText(lastResultText); e.copyBtn.innerHTML = ' Copied'; if (window.lucide && typeof window.lucide.createIcons === "function") window.lucide.createIcons(); applyMacroIconPalette(); setTimeout(() => { e.copyBtn.innerHTML = ' Copy results'; if (window.lucide && typeof window.lucide.createIcons === "function") window.lucide.createIcons(); applyMacroIconPalette(); }, 1800); } catch (_e) {} }); e.exportBtn.addEventListener("click", async () => { if (!lastExportData) return; const originalHtml = e.exportBtn.innerHTML; const jsPDF = (window.jspdf && window.jspdf.jsPDF) || window.jsPDF || (window.jspdf && window.jspdf.default) || null; if (!jsPDF) { e.exportBtn.innerHTML = ' Export unavailable'; if (window.lucide && typeof window.lucide.createIcons === "function") { window.lucide.createIcons(); } window.setTimeout(() => { e.exportBtn.innerHTML = originalHtml; if (window.lucide && typeof window.lucide.createIcons === "function") { window.lucide.createIcons(); } }, 1800); return; } const previewWindow = window.open("", "_blank"); e.exportBtn.innerHTML = ' Exporting...'; if (window.lucide && typeof window.lucide.createIcons === "function") { window.lucide.createIcons(); } try { const doc = new jsPDF({ unit: "mm", format: "a4", orientation: "portrait" }); const pageWidth = doc.internal.pageSize.getWidth(); const pageHeight = doc.internal.pageSize.getHeight(); const margin = 12; const contentWidth = pageWidth - (margin * 2); const colors = { bg: hexToRgb("#071225"), panel: hexToRgb("#122546"), panelSoft: hexToRgb("#0d1b34"), border: hexToRgb("#243b63"), text: hexToRgb("#eff5ff"), muted: hexToRgb("#9bb0d1"), accent: hexToRgb("#5dd6ff"), accent2: hexToRgb("#49e2b5"), protein: hexToRgb("#ff4d6d"), carbs: hexToRgb("#22c55e"), fat: hexToRgb("#f97316") }; doc.setFillColor(...colors.bg); doc.rect(0, 0, pageWidth, pageHeight, "F"); drawRoundedRect(doc, margin, margin, contentWidth, pageHeight - (margin * 2), colors.panelSoft, 9); drawRoundedRect(doc, margin, margin, contentWidth, 42, [14, 29, 55], 9); const logoDataUrl = await loadLogoDataUrl(); if (logoDataUrl) { doc.addImage(logoDataUrl, "PNG", margin + 6, margin + 6, 12, 12); } doc.setTextColor(...colors.text); doc.setFont("helvetica", "bold"); doc.setFontSize(16); doc.text("RepTotal", margin + 22, margin + 13); doc.setFont("helvetica", "normal"); doc.setTextColor(...colors.muted); doc.setFontSize(9); doc.text("Daily macro target export", margin + 22, margin + 18); doc.setTextColor(...colors.text); doc.setFont("helvetica", "bold"); doc.setFontSize(24); doc.text("Your daily targets", margin + 6, margin + 30); doc.setFont("helvetica", "normal"); doc.setTextColor(...colors.muted); doc.setFontSize(10); doc.text("Generated from the RepTotal Macro Calculator.", margin + 6, margin + 36); const badgeY = margin + 46; const badges = [ lastExportData.exportDate, lastExportData.goalLabel, lastExportData.activityLabel, lastExportData.trainingLabel ]; drawRoundedRect(doc, margin + 6, badgeY, contentWidth - 12, 10, [18, 37, 70], 5); doc.setTextColor(...colors.muted); doc.setFontSize(8); const metaText = badges.join(" | "); doc.text(metaText, margin + 12, badgeY + 6.2); doc.setFont("helvetica", "bold"); doc.setTextColor(...colors.text); doc.setFontSize(10.8); doc.text("Macro planning overview", margin + 6, badgeY + 16); doc.setFont("helvetica", "normal"); doc.setTextColor(...colors.muted); doc.setFontSize(7.8); const overviewLines = doc.splitTextToSize( "Use this report to align daily intake, meal structure, and training recovery.", 120 ); doc.text(overviewLines, margin + 6, badgeY + 22.5); const cardY = badgeY + 32; const cardGap = 4; const cardWidth = (contentWidth - 12 - (cardGap * 3)) / 4; const metricCards = [ { title: "Calories", value: lastExportData.calories, meta: "kcal per day", tone: colors.accent }, { title: "Protein", value: lastExportData.protein, meta: lastExportData.proteinKg, tone: colors.protein }, { title: "Carbs", value: lastExportData.carbs, meta: lastExportData.carbsPct, tone: colors.carbs }, { title: "Fat", value: lastExportData.fat, meta: lastExportData.fatPct, tone: colors.fat } ]; metricCards.forEach((card, index) => { const x = margin + 6 + (index * (cardWidth + cardGap)); drawRoundedRect(doc, x, cardY, cardWidth, 26, colors.panel, 6); doc.setTextColor(...card.tone); doc.setFont("helvetica", "bold"); doc.setFontSize(8); doc.text(card.title.toUpperCase(), x + 5, cardY + 6); doc.setTextColor(...colors.text); doc.setFontSize(18); doc.text(card.value, x + 5, cardY + 15); doc.setTextColor(...colors.muted); doc.setFont("helvetica", "normal"); doc.setFontSize(8); doc.text(card.meta, x + 5, cardY + 21); }); const panelY = cardY + 32; const leftWidth = (contentWidth - 12 - 4) * 0.52; const rightWidth = (contentWidth - 12 - 4) - leftWidth; drawRoundedRect(doc, margin + 6, panelY, leftWidth, 34, colors.panel, 6); drawRoundedRect(doc, margin + 6 + leftWidth + 4, panelY, rightWidth, 34, colors.panel, 6); doc.setFont("helvetica", "bold"); doc.setTextColor(...colors.text); doc.setFontSize(11); doc.text("Macro split", margin + 11, panelY + 7); const splitRows = [ { label: "Protein", value: lastExportData.proteinPct, tone: colors.protein }, { label: "Carbs", value: lastExportData.carbsPct, tone: colors.carbs }, { label: "Fat", value: lastExportData.fatPct, tone: colors.fat } ]; splitRows.forEach((row, index) => { const y = panelY + 14 + (index * 6.5); doc.setFillColor(...row.tone); doc.circle(margin + 12, y - 1.3, 1.3, "F"); doc.setTextColor(...colors.muted); doc.setFont("helvetica", "normal"); doc.setFontSize(9); doc.text(row.label, margin + 16, y); doc.setTextColor(...colors.text); doc.setFont("helvetica", "bold"); doc.text(row.value, margin + leftWidth - 6, y, { align: "right" }); }); const supportX = margin + 6 + leftWidth + 4; doc.setTextColor(...colors.text); doc.setFont("helvetica", "bold"); doc.setFontSize(11); doc.text("Daily support", supportX + 5, panelY + 7); drawRoundedRect(doc, supportX + 5, panelY + 12, (rightWidth - 15) / 2, 16, [18, 31, 57], 5); drawRoundedRect(doc, supportX + 10 + ((rightWidth - 15) / 2), panelY + 12, (rightWidth - 15) / 2, 16, [18, 31, 57], 5); doc.setTextColor(...colors.text); doc.setFontSize(12); doc.text(lastExportData.fiber, supportX + 10, panelY + 21); doc.text(lastExportData.water, supportX + 15 + ((rightWidth - 15) / 2), panelY + 21); doc.setTextColor(...colors.muted); doc.setFontSize(8); doc.text("Fiber", supportX + 10, panelY + 26); doc.text("Water", supportX + 15 + ((rightWidth - 15) / 2), panelY + 26); const lowerY = panelY + 40; drawRoundedRect(doc, margin + 6, lowerY, leftWidth, 40, colors.panel, 6); drawRoundedRect(doc, margin + 6 + leftWidth + 4, lowerY, rightWidth, 40, colors.panel, 6); doc.setTextColor(...colors.text); doc.setFont("helvetica", "bold"); doc.setFontSize(11); doc.text(`Per meal (${lastExportData.meals}/day)`, margin + 11, lowerY + 7); const mealRows = [ ["Calories", lastExportData.mealCalories], ["Protein", lastExportData.mealProtein], ["Carbs", lastExportData.mealCarbs], ["Fat", lastExportData.mealFat] ]; mealRows.forEach((row, index) => { const col = index % 2; const rowIndex = Math.floor(index / 2); const x = margin + 11 + (col * ((leftWidth - 10) / 2)); const y = lowerY + 15 + (rowIndex * 10); doc.setTextColor(...colors.muted); doc.setFont("helvetica", "normal"); doc.setFontSize(8); doc.text(row[0], x, y); doc.setTextColor(...colors.text); doc.setFont("helvetica", "bold"); doc.setFontSize(11); doc.text(row[1], x, y + 5); }); doc.setTextColor(...colors.text); doc.setFont("helvetica", "bold"); doc.setFontSize(11); doc.text("Calculation summary", supportX + 5, lowerY + 7); const summaryRows = [ ["BMR", lastExportData.bmr], ["Method", lastExportData.bmrMethod], ["TDEE", lastExportData.tdee], ["Adjustment", `${lastExportData.adjustment} ${lastExportData.adjustmentLabel}`] ]; summaryRows.forEach((row, index) => { const y = lowerY + 15 + (index * 7.25); doc.setTextColor(...colors.muted); doc.setFont("helvetica", "normal"); doc.setFontSize(8); doc.text(row[0], supportX + 5, y); doc.setTextColor(...colors.text); doc.setFont("helvetica", "bold"); doc.text(row[1], supportX + rightWidth - 5, y, { align: "right" }); }); doc.setTextColor(...colors.muted); doc.setFont("helvetica", "normal"); doc.setFontSize(7.5); const disclaimer = doc.splitTextToSize( "Disclaimer: This calculator provides estimates for informational purposes only and does not constitute medical or dietary advice.", contentWidth - 12 ); doc.text(disclaimer, margin, pageHeight - 5); doc.addPage(); doc.setFillColor(...colors.bg); doc.rect(0, 0, pageWidth, pageHeight, "F"); const guideY = margin + 10; const guideFooterReserve = 18; const guideHeight = pageHeight - (margin * 2) - guideFooterReserve; const guideTitle = lastExportData.guide?.title || "Training guidance"; const guideEyebrow = (lastExportData.guide?.eyebrow || "Training guidance").toUpperCase(); const guideSummary = lastExportData.guide?.summary || "Use these targets as a practical planning baseline and adjust with your training response over time."; const guideCards = Array.isArray(lastExportData.guide?.cards) ? lastExportData.guide.cards : []; const guideChips = Array.isArray(lastExportData.guide?.chips) ? lastExportData.guide.chips : []; drawRoundedRect(doc, margin + 8, guideY, contentWidth - 16, guideHeight, colors.panel, 10); const guideInnerX = margin + 18; const guideInnerWidth = contentWidth - 36; doc.setFont("helvetica", "bold"); doc.setTextColor(...colors.accent); doc.setFontSize(7.6); doc.text(guideEyebrow, guideInnerX, guideY + 18); doc.setTextColor(...colors.text); doc.setFontSize(16); doc.text(guideTitle, guideInnerX, guideY + 27); doc.setFont("helvetica", "normal"); doc.setTextColor(...colors.muted); doc.setFontSize(8.2); const summaryLines = doc.splitTextToSize(guideSummary, guideInnerWidth); doc.text(summaryLines, guideInnerX, guideY + 35); const focusBlockY = guideY + 51; doc.setFont("helvetica", "bold"); doc.setTextColor(...colors.text); doc.setFontSize(8.5); doc.text("Key focus", guideInnerX, focusBlockY); doc.setFont("helvetica", "normal"); doc.setTextColor(...colors.muted); doc.setFontSize(7.7); const focusLines = (guideChips.length ? guideChips : ["Use the targets consistently", "Review trends over time", "Adjust only when progress stalls"]).map((chip) => `- ${chip}`); doc.text(focusLines, guideInnerX, focusBlockY + 7); const guideGridY = focusBlockY + 22; const guideSectionWidth = guideInnerWidth; guideCards.forEach((card, index) => { const x = guideInnerX; const y = guideGridY + (index * 27.5); if (index > 0) { doc.setDrawColor(...colors.border); doc.setLineWidth(0.35); doc.line(x, y - 5, x + guideSectionWidth, y - 5); } doc.setFont("helvetica", "bold"); doc.setTextColor(...colors.accent2); doc.setFontSize(6.8); doc.text(String(card.kicker || "").toUpperCase(), x, y + 4.5); doc.setTextColor(...colors.text); doc.setFontSize(10.6); const titleLines = doc.splitTextToSize(card.title || "", guideSectionWidth); doc.text(titleLines.slice(0, 1), x, y + 10.5); doc.setFont("helvetica", "normal"); doc.setTextColor(...colors.muted); doc.setFontSize(7.6); const bodyLines = doc.splitTextToSize(card.body || "", guideSectionWidth); doc.text(bodyLines.slice(0, 2), x, y + 16.5); }); doc.text(disclaimer, margin, pageHeight - 5); const pdfBlob = doc.output("blob"); const pdfUrl = URL.createObjectURL(pdfBlob); if (previewWindow) { previewWindow.location.href = pdfUrl; e.exportBtn.innerHTML = ' Opened'; window.setTimeout(() => { URL.revokeObjectURL(pdfUrl); }, 60000); } else { const link = document.createElement("a"); link.href = pdfUrl; link.download = "reptotal-macro-targets.pdf"; link.click(); e.exportBtn.innerHTML = ' Downloaded'; window.setTimeout(() => { URL.revokeObjectURL(pdfUrl); }, 2000); } } catch (_error) { if (previewWindow && !previewWindow.closed) { previewWindow.close(); } e.exportBtn.innerHTML = ' Export failed'; } finally { if (window.lucide && typeof window.lucide.createIcons === "function") { window.lucide.createIcons(); } window.setTimeout(() => { e.exportBtn.innerHTML = originalHtml; if (window.lucide && typeof window.lucide.createIcons === "function") { window.lucide.createIcons(); } }, 1800); } }); fillIntensityOptions(); updateUnitUI(); updateAdvancedUI(); updateCustomAdjustRange(); updateSliderLabels(); setTips(); setFeedback(""); if (e.previewBreakdown && !e.previewBreakdown.innerHTML.trim()) e.previewBreakdown.innerHTML = DEFAULT_BREAKDOWN_HTML; if (e.breakdown && !e.breakdown.innerHTML.trim()) e.breakdown.innerHTML = DEFAULT_BREAKDOWN_HTML; applyMacroIconPalette(); document.addEventListener("click", (event) => { if (!activeTipButton || !tipPopover || tipPopover.hidden) return; const target = event.target; if (activeTipButton.contains(target) || tipPopover.contains(target)) return; closeTipPopover(); }); document.addEventListener("keydown", (event) => { if (event.key === "Escape") closeTipPopover(); }); window.addEventListener("resize", closeTipPopover); window.addEventListener("scroll", closeTipPopover, true); })();