﻿        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 (
                <div className="card">
                    <h3 style={{ marginBottom: '16px' }}>🏦 Advanced Loan EMI Calculator</h3>
                    <p style={{ color: 'var(--text-secondary)', fontSize: '14px', marginBottom: '16px' }}>
                        Calculate EMI with variable interest rates
                    </p>

                    <div style={{ marginBottom: '20px', display: 'flex', gap: '8px' }}>
                        <button onClick={() => setMode('simple')} style={{ padding: '8px 16px', border: 'none', background: mode === 'simple' ? 'var(--primary)' : 'var(--bg-secondary)', color: mode === 'simple' ? 'white' : 'var(--text-primary)', borderRadius: '6px', cursor: 'pointer', fontSize: '13px', fontWeight: mode === 'simple' ? '600' : '400' }}>Simple Mode</button>
                        <button onClick={() => setMode('advanced')} style={{ padding: '8px 16px', border: 'none', background: mode === 'advanced' ? 'var(--primary)' : 'var(--bg-secondary)', color: mode === 'advanced' ? 'white' : 'var(--text-primary)', borderRadius: '6px', cursor: 'pointer', fontSize: '13px', fontWeight: mode === 'advanced' ? '600' : '400' }}>Advanced (Floating Rates)</button>
                    </div>

                    <div className="form-group">
                        <label className="form-label">Loan Amount (₹)</label>
                        <input type="number" className="form-input" value={loanAmount} onChange={(e) => setLoanAmount(e.target.value)} placeholder="1000000" />
                    </div>

                    {mode === 'simple' ? (
                        <div>
                            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '16px' }}>
                                <div className="form-group" style={{ marginBottom: '0' }}>
                                    <label className="form-label">Interest Rate (% p.a.)</label>
                                    <input type="number" className="form-input" value={interestRate} onChange={(e) => setInterestRate(e.target.value)} placeholder="9.5" step="0.1" />
                                </div>
                                <div className="form-group" style={{ marginBottom: '0' }}>
                                    <label className="form-label">Loan Tenure (Years)</label>
                                    <input type="number" className="form-input" value={tenure} onChange={(e) => setTenure(e.target.value)} placeholder="20" />
                                </div>
                            </div>
                            <button className="btn btn-primary mt-4" onClick={calculateSimple}>Calculate EMI</button>
                        </div>
                    ) : (
                        <div>
                            <div style={{ background: 'var(--bg-tertiary)', padding: '12px', borderRadius: '8px', marginBottom: '16px', fontSize: '13px' }}>
                                <strong>How it works:</strong> Set different interest rates for each year. EMI is recalculated each year based on remaining principal and new rate.
                            </div>

                            {periods.map((period, index) => (
                                <div key={index} style={{ marginBottom: '16px', padding: '16px', background: 'var(--bg-secondary)', borderRadius: '8px' }}>
                                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
                                        <strong style={{ fontSize: '14px' }}>Year {period.year}</strong>
                                        {periods.length > 1 && (
                                            <button onClick={() => removePeriod(index)} style={{ background: 'none', border: 'none', color: 'var(--danger)', cursor: 'pointer', fontSize: '18px', padding: '0', lineHeight: '1' }} title="Remove">×</button>
                                        )}
                                    </div>
                                    <div className="form-group" style={{ marginBottom: '0' }}>
                                        <label className="form-label" style={{ fontSize: '13px' }}>Interest Rate (% p.a.)</label>
                                        <input type="number" className="form-input" value={period.rate} onChange={(e) => updatePeriod(index, 'rate', e.target.value)} placeholder="9.5" step="0.1" />
                                    </div>
                                </div>
                            ))}

                            <button className="btn btn-secondary" onClick={addPeriod} style={{ width: '100%', marginBottom: '16px' }}>+ Add Year</button>
                            <button className="btn btn-primary" onClick={calculateAdvanced} style={{ width: '100%' }}>Calculate Loan</button>
                        </div>
                    )}

                    {result && result.type === 'simple' && (
                        <div className="mt-4" style={{ padding: '20px', background: 'var(--bg-tertiary)', borderRadius: '8px' }}>
                            <div style={{ marginBottom: '12px' }}>
                                <div style={{ fontSize: '14px', color: 'var(--text-secondary)', marginBottom: '4px' }}>Monthly EMI</div>
                                <div style={{ fontSize: '28px', fontWeight: '700', color: 'var(--primary)' }}>₹{result.emi.toLocaleString('en-IN', { maximumFractionDigits: 0 })}</div>
                            </div>
                            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '12px', paddingTop: '12px', borderTop: '1px solid var(--border-color)' }}>
                                <div>
                                    <div style={{ fontSize: '13px', color: 'var(--text-secondary)', marginBottom: '4px' }}>Principal</div>
                                    <div style={{ fontSize: '16px', fontWeight: '600' }}>₹{result.principal.toLocaleString('en-IN', { maximumFractionDigits: 0 })}</div>
                                </div>
                                <div>
                                    <div style={{ fontSize: '13px', color: 'var(--text-secondary)', marginBottom: '4px' }}>Total Interest</div>
                                    <div style={{ fontSize: '16px', fontWeight: '600', color: 'var(--danger)' }}>₹{result.totalInterest.toLocaleString('en-IN', { maximumFractionDigits: 0 })}</div>
                                </div>
                                <div style={{ gridColumn: 'span 2' }}>
                                    <div style={{ fontSize: '13px', color: 'var(--text-secondary)', marginBottom: '4px' }}>Total Amount Payable</div>
                                    <div style={{ fontSize: '18px', fontWeight: '600' }}>₹{result.totalAmount.toLocaleString('en-IN', { maximumFractionDigits: 0 })}</div>
                                </div>
                            </div>
                            <div style={{ marginTop: '12px', fontSize: '13px', color: 'var(--text-secondary)' }}>
                                {result.rate}% p.a. for {result.tenure} years ({result.tenure * 12} months)
                            </div>
                        </div>
                    )}

                    {result && result.type === 'advanced' && (
                        <div className="mt-4">
                            <div style={{ padding: '20px', background: 'var(--bg-tertiary)', borderRadius: '8px', marginBottom: '16px' }}>
                                <div style={{ marginBottom: '12px' }}>
                                    <div style={{ fontSize: '14px', color: 'var(--text-secondary)', marginBottom: '4px' }}>Principal Amount</div>
                                    <div style={{ fontSize: '20px', fontWeight: '600' }}>₹{result.principal.toLocaleString('en-IN', { maximumFractionDigits: 0 })}</div>
                                </div>
                                <div style={{ marginBottom: '12px' }}>
                                    <div style={{ fontSize: '14px', color: 'var(--text-secondary)', marginBottom: '4px' }}>Total Interest Paid</div>
                                    <div style={{ fontSize: '20px', fontWeight: '600', color: 'var(--danger)' }}>₹{result.totalInterest.toLocaleString('en-IN', { maximumFractionDigits: 0 })}</div>
                                </div>
                                <div style={{ paddingTop: '12px', borderTop: '1px solid var(--border-color)' }}>
                                    <div style={{ fontSize: '14px', color: 'var(--text-secondary)', marginBottom: '4px' }}>Total Amount Payable</div>
                                    <div style={{ fontSize: '28px', fontWeight: '700', color: 'var(--primary)' }}>₹{result.totalAmount.toLocaleString('en-IN', { maximumFractionDigits: 0 })}</div>
                                </div>
                            </div>

                            <div style={{ background: 'var(--bg-secondary)', padding: '16px', borderRadius: '8px' }}>
                                <strong style={{ fontSize: '15px', marginBottom: '12px', display: 'block' }}>Year-by-Year Breakdown</strong>
                                <div style={{ maxHeight: '300px', overflowY: 'auto' }}>
                                    {result.breakdown.map((item, index) => (
                                        <div key={index} style={{ padding: '12px', background: 'var(--bg-tertiary)', borderRadius: '6px', marginBottom: '8px' }}>
                                            <div style={{ fontWeight: '600', marginBottom: '8px' }}>Year {item.year} @ {item.rate}%</div>
                                            <div style={{ fontSize: '13px', display: 'grid', gap: '4px' }}>
                                                <div>Monthly EMI: ₹{item.emi.toLocaleString('en-IN', { maximumFractionDigits: 0 })}</div>
                                                <div>Opening Balance: ₹{item.startingBalance.toLocaleString('en-IN', { maximumFractionDigits: 0 })}</div>
                                                <div>Principal Paid: ₹{item.principalPaid.toLocaleString('en-IN', { maximumFractionDigits: 0 })}</div>
                                                <div style={{ color: 'var(--danger)' }}>Interest Paid: ₹{item.interestPaid.toLocaleString('en-IN', { maximumFractionDigits: 0 })}</div>
                                                <div style={{ fontWeight: '600', color: 'var(--primary)' }}>Closing Balance: ₹{item.endingBalance.toLocaleString('en-IN', { maximumFractionDigits: 0 })}</div>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            );
        }

// Export to global registry
window.LoanCalculator = LoanCalculator;
