`;
}
function calculateTotalMacros(dayPlan) {
const allMeals = [dayPlan.breakfast, dayPlan.lunch, dayPlan.dinner, ...dayPlan.snacks];
return allMeals.reduce((acc, meal) => {
acc.calories += meal.calories;
acc.p += meal.p;
acc.c += meal.c;
acc.f += meal.f;
return acc;
}, { calories: 0, p: 0, c: 0, f: 0 });
}
// --- PDF Generation ---
function generatePdf() {
if (!currentPlan) { alert('Please generate a meal plan first.'); return; }
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
const pageWidth = doc.internal.pageSize.width;
let yPos = 20;
doc.setFont('helvetica', 'bold');
doc.setFontSize(20);
doc.setTextColor(44, 62, 80);
doc.text('Your 7-Day Carb Cycling Plan', pageWidth / 2, yPos, { align: 'center' });
yPos += 15;
currentPlan.forEach(dayData => {
const totalMacros = calculateTotalMacros(dayData.plan);
const isHighCarb = dayData.type === 'highCarb';
const headerColor = isHighCarb ? [219, 234, 254] : [209, 250, 229]; // Blue or Green
const headerText = `Day ${dayData.day}: ${isHighCarb ? 'High-Carb' : 'Low-Carb'} Day (Approx. ${totalMacros.calories} kcal)`;
const allMeals = [
{ type: 'Breakfast', ...dayData.plan.breakfast },
{ type: 'Lunch', ...dayData.plan.lunch },
{ type: 'Dinner', ...dayData.plan.dinner },
...dayData.plan.snacks.map(s => ({ type: 'Snack', ...s }))
];
const tableData = allMeals.map(m => [m.type, m.name, m.calories, m.p, m.c, m.f]);
if (yPos > doc.internal.pageSize.height - 80) { doc.addPage(); yPos = 20; }
doc.autoTable({
startY: yPos,
head: [
[{ content: headerText, colSpan: 6, styles: { halign: 'center', fillColor: headerColor, textColor: [44, 62, 80] } }],
['Meal', 'Food Item', 'Cals', 'P(g)', 'C(g)', 'F(g)']
],
body: tableData,
theme: 'grid',
headStyles: { fontStyle: 'bold', fillColor: [107, 114, 128], textColor: 255 },
columnStyles: { 2: { halign: 'right' }, 3: { halign: 'right' }, 4: { halign: 'right' }, 5: { halign: 'right' } }
});
yPos = doc.autoTable.previous.finalY + 12;
});
const disclaimerText = document.querySelector('.disclaimer-box p').textContent;
const disclaimerLines = doc.splitTextToSize(disclaimerText, pageWidth - 28);
doc.setFontSize(8);
doc.setTextColor(150);
doc.text(disclaimerLines, 14, doc.internal.pageSize.height - 15);
doc.save('Carb_Cycling_Meal_Plan.pdf');
}
});
