Total Cost: ${formatCurrency(r.totalCost)}
Est. Cash to Close: ${formatCurrency(r.cashToClose)}
`;
resultsCardsContainer.appendChild(card);
}
// Chart
const chartCtx = document.getElementById('total-cost-chart').getContext('2d');
if(totalCostChartInstance) totalCostChartInstance.destroy();
totalCostChartInstance = new Chart(chartCtx, {
type: 'bar',
data: {
labels: Object.keys(results),
datasets: [{
label: 'Total Cost Over Term',
data: Object.values(results).map(r => r.totalCost),
backgroundColor: ['#3b82f6', '#6366f1', '#8b5cf6', '#ec4899'],
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
plugins: { legend: { display: false } },
scales: { y: { beginAtZero: true } }
}
});
};
const downloadPdf = () => {
const r = calculationResults;
const i = getInputs();
const { jsPDF } = window.jspdf;
const doc = new jsPDF({ orientation: 'portrait', unit: 'pt', format: 'a4' });
const margin = 50;
let y = margin;
const addText = (text, options) => {
const fontSize = options.fontSize || 10;
doc.setFont(options.font || 'helvetica', options.fontStyle || 'normal');
doc.setFontSize(fontSize);
if (options.color) doc.setTextColor(options.color[0], options.color[1], options.color[2]);
doc.text(text, options.x || margin, y);
if(options.yAdd) y += options.yAdd;
};
addText('First-Time Homebuyer Mortgage Comparison', { fontSize: 18, fontStyle: 'bold', yAdd: 20 });
addText(`Based on a Home Price of ${formatCurrency(i['home-price'])} with a ${i['down-payment']}% Down Payment`, { fontSize: 10, fontStyle: 'italic', yAdd: 30 });
for (const loanName in r) {
const data = r[loanName];
addText(loanName, { fontSize: 14, fontStyle: 'bold', color: [13, 148, 136], yAdd: 20 });
addText(`Estimated Monthly Payment:`, { yAdd: 15 });
addText(formatCurrency(data.totalMonthlyPayment), { x: 250, fontStyle: 'bold' });
addText(`Estimated Cash to Close:`, { yAdd: 15 });
addText(formatCurrency(data.cashToClose), { x: 250 });
addText(`Total Cost Over Term:`, { yAdd: 15 });
addText(formatCurrency(data.totalCost), { x: 250 });
y += 15;
if (y > 750) { doc.addPage(); y = margin; }
}
doc.save('Mortgage-Comparison.pdf');
};
// Event Listeners
calculateBtn.addEventListener('click', performCalculations);
pdfDownloadBtn.addEventListener('click', downloadPdf);
});