Please enter valid numbers in all fields.
';
return;
}
// --- Lease-to-Own Calculations ---
const leaseTermMonths = leaseTermYears * 12;
const totalRentPaid = monthlyRent * leaseTermMonths;
const totalRentCredit = totalRentPaid * (rentCreditPercent / 100);
const finalBuyoutPrice = purchasePrice - totalRentCredit;
const totalLeasePathCost = totalRentPaid + finalBuyoutPrice;
// --- Immediate Purchase Calculations ---
const downPaymentAmount = purchasePrice * (downPaymentPercent / 100);
const loanAmount = purchasePrice - downPaymentAmount;
const monthlyInterestRate = (configData.interestRate / 100) / 12;
const mortgageTermMonths = 30 * 12; // Assuming 30-year mortgage
const mortgagePayment = loanAmount * (monthlyInterestRate * Math.pow(1 + monthlyInterestRate, mortgageTermMonths)) / (Math.pow(1 + monthlyInterestRate, mortgageTermMonths) - 1);
const totalMortgagePayments = mortgagePayment * leaseTermMonths;
const totalTaxes = (purchasePrice * (configData.propertyTaxRate / 100) / 12) * leaseTermMonths;
const totalInsurance = (configData.homeInsurance / 12) * leaseTermMonths;
const totalMaintenance = (purchasePrice * (configData.maintenance / 100) / 12) * leaseTermMonths;
const totalBuyPathCostDuringLeasePeriod = downPaymentAmount + totalMortgagePayments + totalTaxes + totalInsurance + totalMaintenance;
// --- Equity & Appreciation ---
const futureHomeValue = purchasePrice * Math.pow(1 + (configData.appreciationRate / 100), leaseTermYears);
const equityFromBuying = futureHomeValue - (loanAmount - (mortgagePayment * leaseTermMonths - (loanAmount * monthlyInterestRate * leaseTermMonths))); // Simplified equity calc
renderResults(totalLeasePathCost, totalBuyPathCostDuringLeasePeriod, totalRentCredit, equityFromBuying);
updateChart(totalLeasePathCost, totalBuyPathCostDuringLeasePeriod);
}
function renderResults(leaseCost, buyCost, rentCredit, equity) {
const difference = buyCost - leaseCost;
let recommendation = '';
let recommendationClass = '';
if (difference > 0) {
recommendation = `Lease-to-Own appears to be
$${difference.toLocaleString('en-US', {maximumFractionDigits: 0})} cheaper over the lease term.`;
recommendationClass = 'lease';
} else {
recommendation = `Buying immediately appears to be
$${Math.abs(difference).toLocaleString('en-US', {maximumFractionDigits: 0})} cheaper over the same period.`;
recommendationClass = 'buy';
}
resultsContent.innerHTML = `
Total Cost: Lease-to-Own Path
$${leaseCost.toLocaleString('en-US', {maximumFractionDigits: 0})}
Includes rent paid + final buyout price
Total Cost: Immediate Purchase Path
$${buyCost.toLocaleString('en-US', {maximumFractionDigits: 0})}
Includes down payment, mortgage, taxes, etc. over same period
Recommendation
${recommendation}
Note: Buying immediately builds ~$${equity.toLocaleString('en-US', {maximumFractionDigits: 0})} in equity, which is not factored into the cost comparison.
`;
}
function updateChart(leaseCost, buyCost) {
const ctx = document.getElementById('comparisonChart').getContext('2d');
if (comparisonChart) {
comparisonChart.destroy();
}
comparisonChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Lease-to-Own Path', 'Immediate Purchase Path'],
datasets: [{
label: 'Total Cost Over Lease Term ($)',
data: [leaseCost, buyCost],
backgroundColor: ['rgba(255, 112, 67, 0.7)', 'rgba(40, 53, 147, 0.7)'],
borderColor: ['rgba(255, 112, 67, 1)', 'rgba(40, 53, 147, 1)'],
borderWidth: 1
}]
},
options: {
indexAxis: 'y',
scales: { x: { beginAtZero: true } },
plugins: { legend: { display: false } }
}
});
}
function renderConfig() {
configTbody.innerHTML = `
Mortgage Interest Rate (%)
Annual Property Tax Rate (%)
Annual Home Insurance ($)
Annual Maintenance (% of Home Value)
Annual Home Appreciation Rate (%)
`;
}
window.updateConfig = function(element) {
const { prop } = element.dataset;
const value = parseFloat(element.value);
if (isNaN(value)) return;
configData[prop] = value;
analyze();
}
// --- TAB & NAVIGATION ---
window.openTab = function(evt, tabName) {
const tabContents = document.getElementsByClassName("tab-content");
Array.from(tabContents).forEach(tab => tab.style.display = "none");
const tabButtons = document.getElementsByClassName("tab-btn");
Array.from(tabButtons).forEach(btn => btn.classList.remove("active"));
document.getElementById(tabName).style.display = "block";
if (evt) {
evt.currentTarget.classList.add("active");
} else {
const btnToActivate = Array.from(tabButtons).find(btn => btn.getAttribute('onclick').includes(`'${tabName}'`));
if (btnToActivate) btnToActivate.classList.add("active");
}
updateNavButtons();
}
window.navigateTabs = function(direction) {
const tabs = Array.from(document.querySelectorAll('.tab-btn'));
const activeTabIndex = tabs.findIndex(tab => tab.classList.contains('active'));
let newIndex = (direction === 'next')
? (activeTabIndex + 1) % tabs.length
: (activeTabIndex - 1 + tabs.length) % tabs.length;
tabs[newIndex].click();
}
function updateNavButtons() {
const tabs = Array.from(document.querySelectorAll('.tab-btn'));
const activeTabIndex = tabs.findIndex(tab => tab.classList.contains('active'));
document.getElementById('prev-btn').style.visibility = activeTabIndex === 0 ? 'hidden' : 'visible';
document.getElementById('next-btn').style.visibility = activeTabIndex === tabs.length - 1 ? 'hidden' : 'visible';
}
// --- PDF DOWNLOAD ---
if(downloadPdfBtn) {
downloadPdfBtn.addEventListener('click', function() {
const { jsPDF } = window.jspdf;
const contentToDownload = document.getElementById('results-to-download');
if (!contentToDownload || !document.querySelector('.value')) {
console.warn("Please generate an analysis before downloading.");
return;
}
const originalButtonText = downloadPdfBtn.innerHTML;
downloadPdfBtn.innerHTML = 'Generating...';
downloadPdfBtn.disabled = true;
html2canvas(contentToDownload, { scale: 2, useCORS: true }).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF({ orientation: 'p', unit: 'mm', format: 'a4' });
const pdfWidth = pdf.internal.pageSize.getWidth();
const imgProps = pdf.getImageProperties(imgData);
const imgHeight = (imgProps.height * pdfWidth) / imgProps.width;
pdf.addImage(imgData, 'PNG', 10, 10, pdfWidth - 20, imgHeight > 0 ? imgHeight - 20 : 0);
pdf.save('Lease-to-Own-Analysis.pdf');
}).catch(err => {
console.error("Error generating PDF:", err);
}).finally(() => {
downloadPdfBtn.innerHTML = originalButtonText;
downloadPdfBtn.disabled = false;
});
});
}
// --- INITIALIZATION ---
function initializeTool() {
analyze();
renderConfig();
updateNavButtons();
}
initializeTool();
});