﻿        function InvestmentCalculator() {
            const [mode, setMode] = useState('simple');
            const [principal, setPrincipal] = useState('');
            const [rate, setRate] = useState('');
            const [years, setYears] = useState('');
            const [periods, setPeriods] = useState([{ year: 1, amount: '', rate: '' }]);
            const [result, setResult] = useState(null);

            const calculateSimple = () => {
                if (principal && rate && years) {
                    const p = parseFloat(principal);
                    const r = parseFloat(rate);
                    const y = parseFloat(years);
                    const amount = p * Math.pow((1 + r / 100), y);
                    const interest = amount - p;
                    setResult({ type: 'simple', principal: p, totalAmount: amount, totalInterest: interest, rate: r, years: y });
                }
            };

            const calculateAdvanced = () => {
                let currentAmount = 0;
                let totalInvested = 0;
                let breakdown = [];

                periods.forEach((period, index) => {
                    const amt = parseFloat(period.amount) || 0;
                    const r = parseFloat(period.rate) || 0;

                    if (index === 0) {
                        currentAmount = amt;
                        totalInvested = amt;
                    } else {
                        const prevRate = parseFloat(periods[index - 1].rate) || 0;
                        currentAmount = currentAmount * (1 + prevRate / 100) + amt;
                        totalInvested += amt;
                    }

                    const grownAmount = currentAmount * (1 + r / 100);
                    const interest = grownAmount - currentAmount;

                    breakdown.push({ year: period.year, invested: amt, rate: r, startAmount: currentAmount, endAmount: grownAmount, interest });
                    currentAmount = grownAmount;
                });

                setResult({ type: 'advanced', totalInvested, totalAmount: currentAmount, totalInterest: currentAmount - totalInvested, breakdown });
            };

            const addPeriod = () => setPeriods([...periods, { year: periods.length + 1, amount: '', rate: '' }]);
            const removePeriod = (index) => {
                if (periods.length > 1) {
                    const newPeriods = periods.filter((_, i) => i !== index).map((p, i) => ({ ...p, 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 Investment Calculator</h3>
                    <p style={{ color: 'var(--text-secondary)', fontSize: '14px', marginBottom: '16px' }}>
                        Calculate returns 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 (Variable Rates)</button>
                    </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">Principal Amount (₹)</label>
                                    <input type="number" className="form-input" value={principal} onChange={(e) => setPrincipal(e.target.value)} placeholder="100000" />
                                </div>
                                <div className="form-group" style={{ marginBottom: '0' }}>
                                    <label className="form-label">Annual Interest Rate (%)</label>
                                    <input type="number" className="form-input" value={rate} onChange={(e) => setRate(e.target.value)} placeholder="8" step="0.1" />
                                </div>
                                <div className="form-group" style={{ marginBottom: '0', gridColumn: 'span 2' }}>
                                    <label className="form-label">Investment Period (Years)</label>
                                    <input type="number" className="form-input" value={years} onChange={(e) => setYears(e.target.value)} placeholder="10" />
                                </div>
                            </div>
                            <button className="btn btn-primary mt-4" onClick={calculateSimple}>Calculate</button>
                        </div>
                    ) : (
                        <div>
                            <div style={{ background: 'var(--bg-tertiary)', padding: '12px', borderRadius: '8px', marginBottom: '16px', fontSize: '13px' }}>
                                <strong>How it works:</strong> Add different investment amounts and rates for each year. Previous year's amount compounds and new investments are added.
                            </div>

                            {periods.map((period, index) => (
                                <div key={index} style={{ marginBottom: '16px', padding: '16px', background: 'var(--bg-secondary)', borderRadius: '8px', position: 'relative' }}>
                                    <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 style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '12px' }}>
                                        <div className="form-group" style={{ marginBottom: '0' }}>
                                            <label className="form-label" style={{ fontSize: '13px' }}>{index === 0 ? 'Initial Investment (₹)' : 'Additional Investment (₹)'}</label>
                                            <input type="number" className="form-input" value={period.amount} onChange={(e) => updatePeriod(index, 'amount', e.target.value)} placeholder={index === 0 ? "100000" : "50000"} />
                                        </div>
                                        <div className="form-group" style={{ marginBottom: '0' }}>
                                            <label className="form-label" style={{ fontSize: '13px' }}>Interest Rate (%)</label>
                                            <input type="number" className="form-input" value={period.rate} onChange={(e) => updatePeriod(index, 'rate', e.target.value)} placeholder="8" step="0.1" />
                                        </div>
                                    </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 Investment</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' }}>Principal Amount</div>
                                <div style={{ fontSize: '20px', fontWeight: '600' }}>₹{result.principal.toLocaleString('en-IN', { maximumFractionDigits: 2 })}</div>
                            </div>
                            <div style={{ marginBottom: '12px' }}>
                                <div style={{ fontSize: '14px', color: 'var(--text-secondary)', marginBottom: '4px' }}>Total Interest Earned</div>
                                <div style={{ fontSize: '20px', fontWeight: '600', color: 'var(--success)' }}>₹{result.totalInterest.toLocaleString('en-IN', { maximumFractionDigits: 2 })}</div>
                            </div>
                            <div style={{ paddingTop: '12px', borderTop: '1px solid var(--border-color)' }}>
                                <div style={{ fontSize: '14px', color: 'var(--text-secondary)', marginBottom: '4px' }}>Maturity Amount</div>
                                <div style={{ fontSize: '28px', fontWeight: '700', color: 'var(--primary)' }}>₹{result.totalAmount.toLocaleString('en-IN', { maximumFractionDigits: 2 })}</div>
                            </div>
                            <div style={{ marginTop: '12px', fontSize: '13px', color: 'var(--text-secondary)' }}>At {result.rate}% p.a. for {result.years} years</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' }}>Total Invested</div>
                                    <div style={{ fontSize: '20px', fontWeight: '600' }}>₹{result.totalInvested.toLocaleString('en-IN', { maximumFractionDigits: 2 })}</div>
                                </div>
                                <div style={{ marginBottom: '12px' }}>
                                    <div style={{ fontSize: '14px', color: 'var(--text-secondary)', marginBottom: '4px' }}>Total Interest Earned</div>
                                    <div style={{ fontSize: '20px', fontWeight: '600', color: 'var(--success)' }}>₹{result.totalInterest.toLocaleString('en-IN', { maximumFractionDigits: 2 })}</div>
                                </div>
                                <div style={{ paddingTop: '12px', borderTop: '1px solid var(--border-color)' }}>
                                    <div style={{ fontSize: '14px', color: 'var(--text-secondary)', marginBottom: '4px' }}>Final Amount</div>
                                    <div style={{ fontSize: '28px', fontWeight: '700', color: 'var(--primary)' }}>₹{result.totalAmount.toLocaleString('en-IN', { maximumFractionDigits: 2 })}</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' }}>
                                                {item.invested > 0 && <div>New Investment: ₹{item.invested.toLocaleString('en-IN')}</div>}
                                                <div>Start: ₹{item.startAmount.toLocaleString('en-IN', { maximumFractionDigits: 0 })}</div>
                                                <div style={{ color: 'var(--success)' }}>Interest: +₹{item.interest.toLocaleString('en-IN', { maximumFractionDigits: 0 })}</div>
                                                <div style={{ fontWeight: '600', color: 'var(--primary)' }}>End: ₹{item.endAmount.toLocaleString('en-IN', { maximumFractionDigits: 0 })}</div>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            );
        }

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