<script>
function calculateEnhancedMortgage() {
  const homePriceInput = document.getElementById('homePrice').value;
  const homePrice = parseFloat(homePriceInput.replace(/,/g, ''));

  const downPaymentAmountInput = document.getElementById('downPaymentAmount').value;
  const downPaymentPercentInput = document.getElementById('downPaymentPercent').value;

  const downPaymentAmount = parseFloat(downPaymentAmountInput) || 0;
  const downPaymentPercent = parseFloat(downPaymentPercentInput) || 0;

  const loanTerm = parseInt(document.getElementById('loanTerm').value);
  const loanTermMonths = loanTerm * 12;

  const interestRate = parseFloat(document.getElementById('interestRate').value) / 100 / 12;

  if (isNaN(homePrice) || homePrice <= 0) {
    alert("Please enter a valid home price.");
    return;
  }

  if (isNaN(loanTerm) || loanTerm <= 0) {
    alert("Please enter a valid loan term.");
    return;
  }

  if (isNaN(interestRate) || interestRate <= 0) {
    alert("Please enter a valid interest rate.");
    return;
  }

  const downPayment =
    downPaymentAmount || (downPaymentPercent / 100) * homePrice;

  if (downPayment >= homePrice) {
    alert("Down payment cannot be greater than or equal to the home price.");
    return;
  }

  const loanAmount = homePrice - downPayment;

  const monthlyPayment =
    (loanAmount * interestRate * Math.pow(1 + interestRate, loanTermMonths)) /
    (Math.pow(1 + interestRate, loanTermMonths) - 1);

  const totalPayments = monthlyPayment * loanTermMonths;
  const totalInterest = totalPayments - loanAmount;

  const mortgagePayoffDate = new Date();
  mortgagePayoffDate.setFullYear(mortgagePayoffDate.getFullYear() + loanTerm);

  const resultHTML = `
    <div style="text-align: center; margin-bottom: 20px;">
      <h3 style="color: green;">Monthly Pay: $${monthlyPayment.toFixed(2)}</h3>
      <canvas id="paymentChart" style="max-width: 300px; margin: auto;"></canvas>
    </div>
    <table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
      <tr><td><strong>House Price</strong></td><td style="text-align: right;">$${homePrice.toFixed(2)}</td></tr>
      <tr><td><strong>Loan Amount</strong></td><td style="text-align: right;">$${loanAmount.toFixed(2)}</td></tr>
      <tr><td><strong>Down Payment</strong></td><td style="text-align: right;">$${downPayment.toFixed(2)}</td></tr>
      <tr><td><strong>Total of ${loanTermMonths} Mortgage Payments</strong></td><td style="text-align: right;">$${totalPayments.toFixed(2)}</td></tr>
      <tr><td><strong>Total Interest</strong></td><td style="text-align: right;">$${totalInterest.toFixed(2)}</td></tr>
      <tr><td><strong>Mortgage Payoff Date</strong></td><td style="text-align: right;">${mortgagePayoffDate.toLocaleString('default', { month: 'short' })} ${mortgagePayoffDate.getFullYear()}</td></tr>
    </table>
  `;

  document.getElementById('result').innerHTML = resultHTML;

  const ctx = document.getElementById('paymentChart').getContext('2d');
  new Chart(ctx, {
    type: 'pie',
    data: {
      labels: ['Principal', 'Interest'],
      datasets: [
        {
          data: [loanAmount, totalInterest],
          backgroundColor: ['#007BFF', '#28A745'],
        },
      ],
    },
    options: {
      plugins: {
        legend: {
          position: 'top',
        },
      },
    },
  });
}
</script>
