// loan-mortgage-calculator.js

document.addEventListener('DOMContentLoaded', function() {
  // Event Listeners
  document.getElementById('loan-mortgage-calculator-form').addEventListener('submit', calculateResults);
  document.getElementById('reset-btn').addEventListener('click', resetCalculator);
  document.getElementById('loan-amount').addEventListener('input', formatLoanAmount);
  document.getElementById('payment-frequency').addEventListener('change', updateAdditionalPaymentLabel);

  const inputs = document.querySelectorAll('#loan-mortgage-calculator-form input, #loan-mortgage-calculator-form select');
  inputs.forEach(input => input.addEventListener('input', removeError));

  // Update the label for "Additional Payment" based on the selected payment frequency
  function updateAdditionalPaymentLabel() {
    const paymentFrequency = document.getElementById('payment-frequency').value;
    const additionalPaymentLabel = document.querySelector('label[for="loan-extra-payment"]');

    switch (paymentFrequency) {
      case 'bi-weekly':
        additionalPaymentLabel.textContent = 'Additional Bi-weekly Payment:';
        break;
      case 'quarterly':
        additionalPaymentLabel.textContent = 'Additional Quarterly Payment:';
        break;
      default:
        additionalPaymentLabel.textContent = 'Additional Monthly Payment:';
    }
  }

  // Format Loan Amount with commas while typing, allowing decimals
  function formatLoanAmount(e) {
    let value = e.target.value.replace(/[^0-9.]/g, '');
    const parts = value.split('.');
    if (parts.length > 2) value = `${parts[0]}.${parts[1]}`;
    parts[0] = new Intl.NumberFormat('en-US').format(parts[0]);
    value = parts.join('.');
    e.target.value = value;
  }

  // Calculate Results
  function calculateResults(e) {
    e.preventDefault();
    const amountUI = document.getElementById('loan-amount');
    const loanAmount = parseFloat(amountUI.value.replace(/,/g, ''));
    const interestUI = document.getElementById('loan-interest');
    const termUI = document.getElementById('loan-term');
    const termUnitUI = document.getElementById('term-unit');
    const extraPaymentUI = document.getElementById('loan-extra-payment');
    const paymentFrequencyUI = document.getElementById('payment-frequency');

    const principal = loanAmount;
    const annualInterestRate = parseFloat(interestUI.value);
    const term = parseFloat(termUI.value);
    const termUnit = termUnitUI.value;
    const extraPayment = parseFloat(extraPaymentUI.value) || 0;
    const paymentFrequency = paymentFrequencyUI.value;

    if (
      isNaN(principal) ||
      isNaN(annualInterestRate) ||
      isNaN(term) ||
      principal <= 0 ||
      annualInterestRate <= 0 ||
      term <= 0
    ) {
      showError('Please ensure all inputs are valid.');
      return;
    }

    let paymentsPerYear;
    let frequencyLabel;
    switch (paymentFrequency) {
      case 'bi-weekly':
        paymentsPerYear = 26;
        frequencyLabel = 'Bi-weekly Payment';
        break;
      case 'quarterly':
        paymentsPerYear = 4;
        frequencyLabel = 'Quarterly Payment';
        break;
      default:
        paymentsPerYear = 12;
        frequencyLabel = 'Monthly Payment';
    }

    // Adjust the total number of payments based on frequency and loan term in months/years
    let numberOfPayments;
    if (termUnit === 'years') {
      numberOfPayments = term * paymentsPerYear;
    } else {
      numberOfPayments = (term / 12) * paymentsPerYear; // Convert months to years, then to number of payments
    }
    numberOfPayments = Math.ceil(numberOfPayments); // Round up to the next whole number

    // Correct Interest Rate Calculations
    const compoundingPeriodsPerYear = 12; // Assuming monthly compounding
    const nominalRate = annualInterestRate / 100;

    // Calculate Effective Annual Rate (EAR)
    const effectiveAnnualRate = Math.pow(
      1 + nominalRate / compoundingPeriodsPerYear,
      compoundingPeriodsPerYear
    ) - 1;

    // Calculate Interest Rate Per Payment Period
    const interestRatePerPeriod = Math.pow(
      1 + effectiveAnnualRate,
      1 / paymentsPerYear
    ) - 1;

    // Calculate payment per period using the corrected interest rate per period
    const x = Math.pow(1 + interestRatePerPeriod, numberOfPayments);
    const paymentPerPeriod = (principal * x * interestRatePerPeriod) / (x - 1);

    if (isFinite(paymentPerPeriod)) {
      const schedule = generateAmortizationSchedule(
        principal,
        interestRatePerPeriod,
        numberOfPayments,
        paymentPerPeriod,
        extraPayment
      );
      const totalPayment = schedule.reduce((sum, payment) => sum + parseFloat(payment.payment), 0);
      const totalInterest = schedule.reduce((sum, payment) => sum + parseFloat(payment.interestPayment), 0);

      document.getElementById(
        'monthly-payment'
      ).innerHTML = `<strong>${frequencyLabel}:</strong> ${formatCurrency(paymentPerPeriod + extraPayment)}`;
      document.getElementById(
        'total-payment'
      ).innerHTML = `<strong>Total Payment:</strong> ${formatCurrency(totalPayment)}`;
      document.getElementById(
        'total-interest'
      ).innerHTML = `<strong>Total Interest:</strong> ${formatCurrency(totalInterest)}`;
      document.getElementById('loan-results').classList.remove('hidden');

      displayAmortizationSchedule(schedule, paymentFrequency);

      // User Interface Enhancements
      displayAdditionalMessages(schedule, numberOfPayments, term, termUnit, paymentsPerYear, paymentFrequency);
    } else {
      showError('Calculation error. Please check your inputs.');
    }
  }

  // Generate Amortization Schedule
  function generateAmortizationSchedule(
    principal,
    interestRatePerPeriod,
    numberOfPayments,
    paymentPerPeriod,
    extraPayment
  ) {
    const schedule = [];
    let balance = principal;
    let totalInterestPaid = 0;
    let totalPaymentMade = 0;

    for (let i = 1; balance > 0 && i <= numberOfPayments; i++) {
      const interestPayment = balance * interestRatePerPeriod;
      let principalPayment = paymentPerPeriod - interestPayment + extraPayment;
      let totalPayment = paymentPerPeriod + extraPayment;

      // Adjust the final payment if the principal payment exceeds the remaining balance
      if (principalPayment > balance) {
        principalPayment = balance;
        totalPayment = principalPayment + interestPayment;
      }

      balance -= principalPayment;

      // Accumulate the total interest and payments made
      totalInterestPaid += interestPayment;
      totalPaymentMade += totalPayment;

      schedule.push({
        paymentNumber: i,
        payment: totalPayment.toFixed(2),
        principalPayment: principalPayment.toFixed(2),
        interestPayment: interestPayment.toFixed(2),
        balance: balance > 0 ? balance.toFixed(2) : '0.00', // Ensure we never show negative balance
        isFinalPayment: balance <= 0,
      });
    }

    // Attach additional information to the schedule
    schedule.loanPaidOffEarly = schedule.length < numberOfPayments;
    schedule.actualNumberOfPayments = schedule.length;

    return schedule;
  }

  // Display Amortization Schedule
  function displayAmortizationSchedule(schedule, paymentFrequency) {
    const amortizationBody = document.getElementById('amortization-body');
    amortizationBody.innerHTML = '';
    const frequencyLabel = {
      monthly: 'Month',
      'bi-weekly': 'Bi-Week',
      quarterly: 'Quarter',
    }[paymentFrequency] || 'Month';
    schedule.forEach(payment => {
      const row = `
        <tr${payment.isFinalPayment ? ' class="final-payment"' : ''}>
          <td>${frequencyLabel} ${payment.paymentNumber}</td>
          <td>${formatCurrency(payment.payment)}</td>
          <td>${formatCurrency(payment.principalPayment)}</td>
          <td>${formatCurrency(payment.interestPayment)}</td>
          <td>${formatCurrency(payment.balance)}</td>
        </tr>
      `;
      amortizationBody.insertAdjacentHTML('beforeend', row);
    });
    document.getElementById('amortization-schedule').classList.remove('hidden');
  }

  // Display Additional Messages
  function displayAdditionalMessages(schedule, numberOfPayments, term, termUnit, paymentsPerYear, paymentFrequency) {
    const messagesContainer = document.getElementById('additional-messages');
    messagesContainer.innerHTML = '';
    let messages = '';

    // Message for adjusted final payment
    if (schedule[schedule.length - 1].isFinalPayment && schedule[schedule.length - 1].principalPayment < schedule[0].principalPayment) {
      messages += `<p>Note: The final payment has been adjusted to fully pay off the loan.</p>`;
    }

    // Message for early loan payoff
    const expectedTotalPayments = numberOfPayments;
    const actualTotalPayments = schedule.actualNumberOfPayments;
    if (actualTotalPayments < expectedTotalPayments) {
      const originalTerm = termUnit === 'years' ? term : term / 12;
      const actualTerm = (actualTotalPayments / paymentsPerYear).toFixed(2);
      messages += `<p>Good news! With your additional payments, you will pay off your loan in ${actualTerm} years instead of ${originalTerm} years.</p>`;
    }

    if (messages) {
      messagesContainer.innerHTML = messages;
      messagesContainer.classList.remove('hidden');
    } else {
      messagesContainer.classList.add('hidden');
    }
  }

  // Format Currency
  function formatCurrency(amount) {
    const options = {
      style: 'currency',
      currency: 'USD',
    };
    if (Math.abs(amount) < 1 && amount !== 0) {
      options.minimumFractionDigits = 4;
      options.maximumFractionDigits = 4;
    }
    return new Intl.NumberFormat('en-US', options).format(amount);
  }

  // Remove Error Styling on Input
  function removeError(e) {
    e.target.classList.remove('error');
  }

  // Show Error Message
  function showError(errorMessage) {
    const existingError = document.querySelector('.error-message');
    if (existingError) existingError.remove();
    const errorDiv = document.createElement('div');
    errorDiv.className = 'error error-message';
    errorDiv.textContent = errorMessage;
    const calculatorContainer = document.querySelector('.calculator-container');
    const form = document.getElementById('loan-mortgage-calculator-form');
    calculatorContainer.insertBefore(errorDiv, form);
    setTimeout(() => {
      errorDiv.remove();
    }, 5000);
  }

  // Reset Calculator
  function resetCalculator() {
    document.getElementById('loan-mortgage-calculator-form').reset();
    document.getElementById('loan-results').classList.add('hidden');
    document.getElementById('amortization-schedule').classList.add('hidden');
    document.getElementById('additional-messages').classList.add('hidden');
    inputs.forEach(input => input.classList.remove('error'));
    updateAdditionalPaymentLabel(); // Reset the label back to "Additional Monthly Payment"
  }
});


document.addEventListener("DOMContentLoaded", function() {
  const timeElements = document.querySelectorAll('.post-published time');
  timeElements.forEach(function(timeElement) {
    const dateTime = timeElement.getAttribute('datetime');
    if (!dateTime) return;

    // Create a Date object from the datetime attribute
    const dateObj = new Date(dateTime);
    
    // Set options for EST time formatting
    const options = {
      timeZone: 'America/New_York', // Setting to EST time zone
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
      hour12: true // 12-hour format
    };

    // Format date to EST and append "EST" explicitly
    const formattedDate = dateObj.toLocaleDateString('en-US', options) + ' EST';
    
    // Update the text content of the <time> element
    timeElement.innerHTML = `Published <b>${formattedDate}</b>`;
  });
});
