function LoanCalculator() { const [mode, setMode] = useState('simple'); const [loanAmount, setLoanAmount] = useState(''); const [interestRate, setInterestRate] = useState(''); const [tenure, setTenure] = useState(''); const [periods, setPeriods] = useState([{ year: 1, rate: '', description: 'Year 1' }]); const [result, setResult] = useState(null); const calculateSimple = () => { if (loanAmount && interestRate && tenure) { const principal = parseFloat(loanAmount); const annualRate = parseFloat(interestRate); const months = parseFloat(tenure) * 12; const monthlyRate = annualRate / (12 * 100); const emi = (principal * monthlyRate * Math.pow(1 + monthlyRate, months)) / (Math.pow(1 + monthlyRate, months) - 1); const totalAmount = emi * months; const totalInterest = totalAmount - principal; setResult({ type: 'simple', emi, totalAmount, totalInterest, principal, rate: annualRate, tenure: parseFloat(tenure) }); } }; const calculateAdvanced = () => { const principal = parseFloat(loanAmount); if (!principal) return; let remainingPrincipal = principal; let totalInterestPaid = 0; let breakdown = []; let currentYear = 1; periods.forEach((period) => { const rate = parseFloat(period.rate) || 0; const monthlyRate = rate / (12 * 100); const months = 12; if (remainingPrincipal > 0) { // Calculate EMI for this period const yearsRemaining = periods.length - (currentYear - 1); const monthsRemaining = yearsRemaining * 12; const emi = (remainingPrincipal * monthlyRate * Math.pow(1 + monthlyRate, monthsRemaining)) / (Math.pow(1 + monthlyRate, monthsRemaining) - 1); let yearInterest = 0; let yearPrincipal = 0; let startingBalance = remainingPrincipal; // Calculate for 12 months for (let month = 0; month < months && remainingPrincipal > 0; month++) { const monthInterest = remainingPrincipal * monthlyRate; const monthPrincipal = emi - monthInterest; yearInterest += monthInterest; yearPrincipal += monthPrincipal; remainingPrincipal -= monthPrincipal; } totalInterestPaid += yearInterest; breakdown.push({ year: currentYear, rate: rate, emi: emi, startingBalance: startingBalance, principalPaid: yearPrincipal, interestPaid: yearInterest, endingBalance: Math.max(0, remainingPrincipal) }); currentYear++; } }); setResult({ type: 'advanced', principal: principal, totalInterest: totalInterestPaid, totalAmount: principal + totalInterestPaid, breakdown: breakdown }); }; const addPeriod = () => setPeriods([...periods, { year: periods.length + 1, rate: '', description: `Year ${periods.length + 1}` }]); const removePeriod = (index) => { if (periods.length > 1) { const newPeriods = periods.filter((_, i) => i !== index).map((p, i) => ({ ...p, year: i + 1, description: `Year ${i + 1}` })); setPeriods(newPeriods); } }; const updatePeriod = (index, field, value) => { const newPeriods = [...periods]; newPeriods[index][field] = value; setPeriods(newPeriods); }; return (
Calculate EMI with variable interest rates