{% extends 'base.html' %}
{% load i18n %}
{% load static %}

{% block title %}{% trans "FIRE Planning Calculator" %} - {% trans "Mini Apps" %}{% endblock %}

{% block extra_css %}
<style>
    .fire-container {
        max-width: 1600px;
        margin: 0 auto;
        padding: 1rem;
    }

    .fire-header {
        text-align: center;
        margin-bottom: 1rem;
    }

    .fire-title {
        font-size: 1.75rem;
        font-weight: 700;
        background: linear-gradient(135deg, #27ae60 0%, #2ecc71 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        margin-bottom: 0.25rem;
    }

    .fire-subtitle {
        color: #6b7280;
        font-size: 0.875rem;
    }

    .input-card {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        padding: 1rem;
        margin-bottom: 1rem;
    }

    .compact-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
        gap: 0.75rem;
    }

    .input-group {
        margin-bottom: 0;
    }

    .input-label {
        display: block;
        font-weight: 600;
        color: #374151;
        margin-bottom: 0.25rem;
        font-size: 0.75rem;
    }

    .input-field {
        width: 100%;
        padding: 0.5rem;
        border: 1px solid #d1d5db;
        border-radius: 4px;
        font-size: 0.875rem;
        transition: border-color 0.2s ease;
    }

    .input-field:focus {
        outline: none;
        border-color: #27ae60;
        box-shadow: 0 0 0 2px rgba(39, 174, 96, 0.1);
    }

    .btn-calculate {
        background: linear-gradient(135deg, #27ae60 0%, #2ecc71 100%);
        color: white;
        padding: 0.5rem 1.5rem;
        border-radius: 6px;
        font-weight: 600;
        border: none;
        cursor: pointer;
        transition: transform 0.2s ease, box-shadow 0.2s ease;
        font-size: 0.875rem;
    }

    .btn-calculate:hover {
        transform: translateY(-1px);
        box-shadow: 0 6px 12px rgba(39, 174, 96, 0.3);
    }

    .btn-reset {
        background: #6b7280;
        color: white;
        padding: 0.5rem 1.5rem;
        border-radius: 6px;
        font-weight: 600;
        border: none;
        cursor: pointer;
        transition: background 0.2s ease;
        font-size: 0.875rem;
    }

    .btn-reset:hover {
        background: #4b5563;
    }

    .results-card {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        padding: 1rem;
        margin-bottom: 1rem;
    }

    .results-card.show {
        display: block;
        animation: fadeIn 0.3s ease;
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .summary-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 0.75rem;
        margin-bottom: 1rem;
    }

    .summary-card {
        background: linear-gradient(135deg, #f3f4f6 0%, #e5e7eb 100%);
        padding: 0.75rem;
        border-radius: 6px;
        text-align: center;
    }

    .summary-card.success {
        background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
    }

    .summary-card.warning {
        background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
    }

    .summary-label {
        font-size: 0.7rem;
        color: #6b7280;
        font-weight: 600;
        text-transform: uppercase;
        margin-bottom: 0.25rem;
    }

    .summary-value {
        font-size: 1.25rem;
        font-weight: 700;
        color: #1f2937;
    }

    .chart-container {
        margin-bottom: 1rem;
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        padding: 1rem;
    }

    .chart-title {
        font-size: 1rem;
        font-weight: 600;
        color: #1f2937;
        margin-bottom: 0.5rem;
    }

    .input-help {
        font-size: 0.65rem;
        color: #6b7280;
        margin-top: 0.125rem;
        display: none; /* Hide to save space */
    }

    .section-title {
        font-size: 1.125rem;
        font-weight: 700;
        color: #1f2937;
        margin-bottom: 0.75rem;
        display: flex;
        align-items: center;
    }

    .section-title i {
        margin-right: 0.5rem;
        color: #27ae60;
    }

    .info-box {
        background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
        border-radius: 8px;
        padding: 1rem;
        margin-bottom: 1rem;
    }

    .scenario-tabs {
        display: flex;
        gap: 0.5rem;
        margin-bottom: 0.75rem;
        flex-wrap: wrap;
    }

    .scenario-tab {
        padding: 0.375rem 0.75rem;
        border-radius: 4px;
        border: 1px solid #e5e7eb;
        background: white;
        cursor: pointer;
        font-weight: 600;
        font-size: 0.75rem;
        transition: all 0.2s ease;
    }

    .scenario-tab.active {
        background: #27ae60;
        color: white;
        border-color: #27ae60;
    }

    table {
        width: 100%;
        border-collapse: collapse;
        font-size: 0.75rem;
    }

    th {
        background: #f3f4f6;
        padding: 0.5rem 0.375rem;
        text-align: left;
        font-weight: 600;
        color: #374151;
        border-bottom: 2px solid #e5e7eb;
        font-size: 0.7rem;
    }

    td {
        padding: 0.375rem;
        border-bottom: 1px solid #e5e7eb;
        white-space: nowrap;
    }

    tr:hover {
        background: #f9fafb;
    }

    .fire-achieved {
        background: #d1fae5 !important;
    }

    .net-worth-cell {
        font-weight: 600;
        color: #2563eb;
        cursor: pointer;
        text-decoration: underline;
        text-decoration-style: dotted;
        text-decoration-color: #93c5fd;
    }

    .net-worth-cell:hover {
        color: #1d4ed8;
        background-color: #dbeafe;
    }

    /* Modal Styles */
    .modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.6);
        z-index: 1000;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 1rem;
    }

    .modal-content {
        background: white;
        border-radius: 12px;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
        max-width: 600px;
        width: 100%;
        max-height: 90vh;
        overflow-y: auto;
        animation: modalSlideIn 0.3s ease-out;
    }

    @keyframes modalSlideIn {
        from {
            opacity: 0;
            transform: translateY(-20px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .modal-header {
        padding: 1.25rem 1.5rem;
        border-bottom: 2px solid #e5e7eb;
        display: flex;
        align-items: center;
        justify-content: space-between;
        background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
        border-radius: 12px 12px 0 0;
    }

    .modal-title {
        font-size: 1.25rem;
        font-weight: 700;
        color: white;
        margin: 0;
        display: flex;
        align-items: center;
    }

    .modal-close {
        background: rgba(255, 255, 255, 0.2);
        border: none;
        color: white;
        width: 32px;
        height: 32px;
        border-radius: 6px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: background 0.2s ease;
        font-size: 1.25rem;
    }

    .modal-close:hover {
        background: rgba(255, 255, 255, 0.3);
    }

    .modal-body {
        padding: 1.5rem;
    }

    .calculation-step {
        background: #f9fafb;
        border-left: 4px solid #3b82f6;
        padding: 0.75rem 1rem;
        margin-bottom: 0.75rem;
        border-radius: 4px;
        font-size: 0.95rem;
    }

    .calculation-step.highlight {
        background: #dbeafe;
        border-left-color: #1d4ed8;
        font-weight: 600;
    }

    .calculation-label {
        color: #6b7280;
        font-size: 0.85rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .calculation-value {
        color: #1f2937;
        font-size: 1.1rem;
        font-weight: 700;
        font-family: 'Courier New', monospace;
    }

    .calculation-formula {
        background: #fef3c7;
        border: 1px solid #fbbf24;
        padding: 0.75rem;
        border-radius: 6px;
        margin: 1rem 0;
        font-family: 'Courier New', monospace;
        font-size: 0.9rem;
        color: #92400e;
    }

</style>
{% endblock %}

{% block content %}
<div class="fire-container">
    <!-- Compact Header -->
    <div class="fire-header">
        <h1 class="fire-title">
            <i class="fas fa-chart-line"></i>
            When Can I Retire? Early Retirement FIRE Calculator
        </h1>
    </div>

    <!-- Compact Input Form -->
    <div class="input-card">
        <div class="compact-grid">
            <div class="input-group">
                <label class="input-label" for="currentAge">Current Age</label>
                <input type="number" id="currentAge" class="input-field" value="35" min="18" max="100">
            </div>

            <div class="input-group">
                <label class="input-label" for="targetAge">Target FIRE Age</label>
                <input type="number" id="targetAge" class="input-field" value="50" min="18" max="100">
            </div>

            <div class="input-group">
                <label class="input-label" for="currentNetWorth">Current Net Worth (excl. home)</label>
                <input type="number" id="currentNetWorth" class="input-field" value="200000" step="1000">
            </div>

            <div class="input-group">
                <label class="input-label" for="totalNetWorth">Total Net Worth (incl. home)</label>
                <input type="number" id="totalNetWorth" class="input-field" value="900000" step="1000">
            </div>

            <div class="input-group">
                <label class="input-label" for="annualExpenses">Annual Expenses (AUD)</label>
                <input type="number" id="annualExpenses" class="input-field" value="130000" step="1000">
            </div>

            <div class="input-group">
                <label class="input-label" for="annualIncome">Annual Income (AUD)</label>
                <input type="number" id="annualIncome" class="input-field" value="300000" step="1000">
            </div>

            <div class="input-group">
                <label class="input-label" for="savingsRate">Savings Rate (%)</label>
                <input type="number" id="savingsRate" class="input-field" value="40" min="0" max="100" step="1">
            </div>

            <div class="input-group">
                <label class="input-label" for="returnRate">Expected Return (%)</label>
                <input type="number" id="returnRate" class="input-field" value="8" min="0" max="30" step="0.1">
            </div>

            <div class="input-group">
                <label class="input-label" for="inflationRate">Inflation Rate (%)</label>
                <input type="number" id="inflationRate" class="input-field" value="2.5" min="0" max="20" step="0.1">
            </div>

            <div class="input-group">
                <label class="input-label" for="incomeGrowthRate">Income Growth (%)</label>
                <input type="number" id="incomeGrowthRate" class="input-field" value="0" min="0" max="20" step="0.1">
            </div>
        </div>

        <div class="flex gap-2 mt-3 items-center">
            <button class="btn-calculate" onclick="calculateFIRE()">
                <i class="fas fa-calculator mr-1"></i>
                Calculate Plan
            </button>
            <button class="btn-reset" onclick="resetForm()">
                <i class="fas fa-redo mr-1"></i>
                Reset
            </button>
            <p class="text-xs text-gray-500 flex-1">
                <i class="fas fa-info-circle mr-1"></i>
                Results update automatically as you type
            </p>
        </div>
    </div>

    <!-- Results Summary -->
    <div id="resultsSection" class="results-card">
        <h2 class="section-title" style="font-size: 1rem; margin-bottom: 0.5rem;">
            <i class="fas fa-trophy"></i>
            Your FIRE Journey Summary
        </h2>

        <!-- Summary Cards -->
        <div class="summary-grid" id="summaryCards" style="margin-bottom: 0.75rem;">
            <!-- Summary cards will be inserted here by JavaScript -->
        </div>

        <!-- Calculation Methodology Explanation -->
        <div class="bg-blue-50 border-l-4 border-blue-500 p-3 mb-4 rounded">
            <h4 class="font-semibold text-blue-900 mb-1.5 flex items-center text-sm">
                <i class="fas fa-calculator mr-2"></i>
                How We Calculate Your FIRE Journey
            </h4>
            <div class="text-xs text-blue-800 space-y-0.5">
                <p><strong>1. Annual Savings:</strong> Income × Savings Rate = <span id="calcAnnualSavings" class="font-mono bg-blue-100 px-1 rounded">...</span></p>
                <p><strong>2. FIRE Target (4% Rule):</strong> Annual Expenses × 25 = <span id="calcFireTarget" class="font-mono bg-blue-100 px-1 rounded">...</span></p>
                <p><strong>3. Yearly Growth:</strong> (Net Worth + Annual Savings) × (1 + Return Rate)</p>
                <p><strong>4. Inflation-Adjusted Target:</strong> FIRE Target × (1 + Inflation)<sup>years</sup></p>
                <p><strong>5. Progress:</strong> (Current Net Worth ÷ Inflation-Adjusted Target) × 100%</p>
                <p class="pt-1 text-xs italic">
                    <i class="fas fa-info-circle mr-1"></i>
                    FIRE is achieved when your net worth reaches or exceeds your inflation-adjusted target (≥100% progress)
                </p>
            </div>
        </div>

        <!-- Monte Carlo Percentile Chart -->
        <div class="chart-container">
            <h3 class="chart-title">
                <i class="fas fa-chart-area mr-2"></i>
                Monte Carlo Simulation (Percentile Ranges)
            </h3>
            <p class="text-sm text-gray-600 mb-3">
                <i class="fas fa-dice mr-1"></i>
                This chart shows probability ranges from <strong>100 simulated scenarios</strong> with market volatility (±15%).
                The shaded bands represent different likelihood outcomes:
                <span class="text-orange-600 font-semibold">10th-90th percentile</span> (80% of outcomes) and
                <span class="text-green-600 font-semibold">25th-75th percentile</span> (50% of outcomes).
            </p>
            <div class="text-sm text-gray-700 mb-3">
                <div class="mt-1">
                    <span class="font-semibold">In <span id="cycleCount">100</span> simulations:</span>
                </div>
                <div class="mt-1">
                    <span class="font-semibold">Median time to FIRE: <span id="medianAge" class="text-blue-600">18.8 years</span></span>
                </div>
                <div class="mt-1">
                    <span class="text-orange-600 font-semibold">10th to 90th %ile: <span id="range1090">15.2 to 24.5 years</span></span>
                </div>
                <div>
                    <span class="text-green-600 font-semibold">25th to 75th %ile: <span id="range2575">17 to 21 years</span></span>
                </div>
            </div>
            <canvas id="monteCarloChart" style="max-height: 350px;"></canvas>
        </div>

        <!-- Quick Adjustment Panel - Compact Version -->
        <div class="input-card" style="margin-bottom: 1rem;">
            <h3 class="text-sm font-semibold text-gray-700 mb-2 flex items-center">
                <i class="fas fa-sliders-h mr-2 text-blue-600"></i>
                Quick Adjustments - See Impact Instantly
            </h3>

            <div class="grid grid-cols-2 md:grid-cols-5 gap-2">
                <!-- Annual Expenses Adjustment -->
                <div class="bg-gradient-to-br from-blue-50 to-blue-100 p-2 rounded border border-blue-200">
                    <div class="flex items-center justify-between mb-1">
                        <label class="text-xs font-semibold text-gray-700">
                            <i class="fas fa-shopping-cart mr-1 text-blue-600"></i>
                            Expenses
                        </label>
                        <span id="quickExpensesValue" class="text-xs font-mono bg-white px-1 py-0.5 rounded">$60,000</span>
                    </div>
                    <div class="flex gap-1 flex-wrap">
                        <button onclick="adjustValue('annualExpenses', -10000)" class="px-2 py-0.5 bg-white text-gray-700 rounded text-xs hover:bg-blue-200 transition border border-blue-300">-$10k</button>
                        <button onclick="adjustValue('annualExpenses', 10000)" class="px-2 py-0.5 bg-white text-gray-700 rounded text-xs hover:bg-blue-200 transition border border-blue-300">+$10k</button>
                    </div>
                </div>

                <!-- Expected Return Adjustment -->
                <div class="bg-gradient-to-br from-green-50 to-green-100 p-2 rounded border border-green-200">
                    <div class="flex items-center justify-between mb-1">
                        <label class="text-xs font-semibold text-gray-700">
                            <i class="fas fa-chart-line mr-1 text-green-600"></i>
                            Return
                        </label>
                        <span id="quickReturnValue" class="text-xs font-mono bg-white px-1 py-0.5 rounded">8.0%</span>
                    </div>
                    <div class="flex gap-1 flex-wrap">
                        <button onclick="adjustValue('returnRate', -1)" class="px-2 py-0.5 bg-white text-gray-700 rounded text-xs hover:bg-green-200 transition border border-green-300">-1%</button>
                        <button onclick="adjustValue('returnRate', 1)" class="px-2 py-0.5 bg-white text-gray-700 rounded text-xs hover:bg-green-200 transition border border-green-300">+1%</button>
                    </div>
                </div>

                <!-- Annual Income Adjustment -->
                <div class="bg-gradient-to-br from-purple-50 to-purple-100 p-2 rounded border border-purple-200">
                    <div class="flex items-center justify-between mb-1">
                        <label class="text-xs font-semibold text-gray-700">
                            <i class="fas fa-dollar-sign mr-1 text-purple-600"></i>
                            Income
                        </label>
                        <span id="quickIncomeValue" class="text-xs font-mono bg-white px-1 py-0.5 rounded">$100,000</span>
                    </div>
                    <div class="flex gap-1 flex-wrap">
                        <button onclick="adjustValue('annualIncome', -20000)" class="px-2 py-0.5 bg-white text-gray-700 rounded text-xs hover:bg-purple-200 transition border border-purple-300">-$20k</button>
                        <button onclick="adjustValue('annualIncome', 20000)" class="px-2 py-0.5 bg-white text-gray-700 rounded text-xs hover:bg-purple-200 transition border border-purple-300">+$20k</button>
                    </div>
                </div>

                <!-- Target FIRE Age Adjustment -->
                <div class="bg-gradient-to-br from-orange-50 to-orange-100 p-2 rounded border border-orange-200">
                    <div class="flex items-center justify-between mb-1">
                        <label class="text-xs font-semibold text-gray-700">
                            <i class="fas fa-calendar-alt mr-1 text-orange-600"></i>
                            FIRE Age
                        </label>
                        <span id="quickTargetAgeValue" class="text-xs font-mono bg-white px-1 py-0.5 rounded">50</span>
                    </div>
                    <div class="flex gap-1 flex-wrap">
                        <button onclick="adjustValue('targetAge', -1)" class="px-2 py-0.5 bg-white text-gray-700 rounded text-xs hover:bg-orange-200 transition border border-orange-300">-1y</button>
                        <button onclick="adjustValue('targetAge', 1)" class="px-2 py-0.5 bg-white text-gray-700 rounded text-xs hover:bg-orange-200 transition border border-orange-300">+1y</button>
                    </div>
                </div>

                <!-- Income Growth Rate Adjustment -->
                <div class="bg-gradient-to-br from-teal-50 to-teal-100 p-2 rounded border border-teal-200">
                    <div class="flex items-center justify-between mb-1">
                        <label class="text-xs font-semibold text-gray-700">
                            <i class="fas fa-arrow-trend-up mr-1 text-teal-600"></i>
                            Income Growth
                        </label>
                        <span id="quickIncomeGrowthValue" class="text-xs font-mono bg-white px-1 py-0.5 rounded">0.0%</span>
                    </div>
                    <div class="flex gap-1 flex-wrap">
                        <button onclick="adjustValue('incomeGrowthRate', -1)" class="px-2 py-0.5 bg-white text-gray-700 rounded text-xs hover:bg-teal-200 transition border border-teal-300">-1%</button>
                        <button onclick="adjustValue('incomeGrowthRate', 1)" class="px-2 py-0.5 bg-white text-gray-700 rounded text-xs hover:bg-teal-200 transition border border-teal-300">+1%</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Original Net Worth Growth Chart -->
        <div class="chart-container">
            <h3 class="chart-title">
                <i class="fas fa-chart-line mr-2"></i>
                Net Worth Growth Projection
            </h3>
            <p class="text-sm text-gray-600 mb-3">
                <i class="fas fa-info-circle mr-1"></i>
                <strong class="text-green-600">Green line</strong> shows your projected net worth with compound growth.
                <strong class="text-red-600">Red dashed line</strong> shows inflation-adjusted FIRE target.
                When green crosses red, you've achieved FIRE! 🎉
            </p>
            <canvas id="netWorthChart" style="max-height: 400px;"></canvas>
        </div>

        <!-- Year-by-Year Data Table -->
        <div class="chart-container">
            <h3 class="chart-title">
                <i class="fas fa-table mr-2"></i>
                Year-by-Year Projection
            </h3>
            <p class="text-sm text-gray-600 mb-3">
                <i class="fas fa-info-circle mr-1"></i>
                Detailed year-by-year breakdown showing your income, savings, investment returns, and net worth growth.
                <strong class="text-blue-600">Click on any Net Worth value</strong> to see the detailed calculation with actual numbers.
                <strong class="text-green-600">Green rows</strong> indicate years where you've achieved FIRE (≥100% progress).
            </p>
            <div class="overflow-x-auto">
                <table id="projectionTable">
                    <thead>
                        <tr>
                            <th>Age</th>
                            <th>Year</th>
                            <th>Annual Income</th>
                            <th>Annual Savings</th>
                            <th>Investment Return</th>
                            <th>Net Worth (End)</th>
                            <th>FIRE Target</th>
                            <th>Progress</th>
                        </tr>
                    </thead>
                    <tbody id="projectionTableBody">
                        <!-- Table rows will be inserted here by JavaScript -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Net Worth Calculation Modal -->
    <div id="netWorthModal" class="modal-overlay" style="display: none;">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">
                    <i class="fas fa-calculator mr-2"></i>
                    Net Worth Calculation Details
                </h3>
                <button class="modal-close" onclick="closeNetWorthModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body" id="modalCalculationContent">
                <!-- Calculation details will be inserted here -->
            </div>
        </div>
    </div>

    <!-- Educational Content (Moved to Bottom) -->
    <div class="info-box mt-4">
        <div class="flex items-start">
            <div class="flex-shrink-0 mr-3">
                <i class="fas fa-lightbulb text-2xl text-green-600"></i>
            </div>
            <div>
                <h2 class="text-lg font-bold text-gray-800 mb-2">
                    <i class="fas fa-graduation-cap mr-2"></i>
                    Understanding FIRE & The 4% Rule
                </h2>
                <div class="text-gray-700 space-y-2 text-sm leading-relaxed">
                    <p>
                        <strong>FIRE (Financial Independence, Retire Early)</strong> is a movement focused on achieving financial freedom through aggressive saving and smart investing.
                    </p>
                    <p>
                        <strong>The 4% Rule:</strong> Based on the Trinity Study, this rule suggests you can safely withdraw 4% of your investment portfolio annually in retirement, adjusted for inflation, with a high probability your money will last 30+ years.
                    </p>
                    <p>
                        <strong>Your FIRE Target = Annual Expenses × 25</strong> (because 1 ÷ 0.04 = 25)
                    </p>
                    <p class="pt-2 border-t border-green-300 mt-2">
                        <i class="fas fa-info-circle mr-1"></i>
                        <strong>Example:</strong> If you need A$80,000/year to live comfortably, your FIRE target is A$2,000,000.
                        At 4% withdrawal, A$2M × 4% = A$80,000 per year.
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Chart.js (CDN — page-specific, benefits from edge proximity) -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.5.1/dist/chart.umd.min.js"></script>

<script>
    let netWorthChart = null;
    let monteCarloChart = null;

    // Custom plugin to draw vertical line at retirement age
    const verticalLinePlugin = {
        id: 'verticalLine',
        afterDatasetsDraw(chart, args, pluginOptions) {
            const options = chart.options.plugins.verticalLine;

            if (!options || !options.xValue) {
                return;
            }

            const {ctx, chartArea: {top, bottom, left, right}, scales: {x, y}} = chart;

            // Find the index of the target age in the labels array
            const labels = chart.data.labels;
            const targetIndex = labels.findIndex(label => label === options.xValue);

            if (targetIndex === -1) {
                return;
            }

            // Get pixel position using the index
            const xPos = x.getPixelForValue(targetIndex);

            // Draw vertical line
            ctx.save();
            ctx.strokeStyle = options.lineColor || 'rgb(54, 162, 235)';
            ctx.lineWidth = options.lineWidth || 3;
            ctx.setLineDash(options.lineDash || [10, 5]);
            ctx.beginPath();
            ctx.moveTo(xPos, top);
            ctx.lineTo(xPos, bottom);
            ctx.stroke();
            ctx.setLineDash([]);

            // Draw label
            if (options.label) {
                ctx.fillStyle = options.lineColor || 'rgb(54, 162, 235)';
                ctx.font = 'bold 11px Arial';
                const textWidth = ctx.measureText(options.label).width;
                const padding = 6;

                // Background
                ctx.fillRect(xPos - textWidth/2 - padding, top + 5, textWidth + padding * 2, 20);

                // Text
                ctx.fillStyle = 'white';
                ctx.textAlign = 'center';
                ctx.fillText(options.label, xPos, top + 19);
            }

            ctx.restore();
        }
    };

    // Register the plugin
    Chart.register(verticalLinePlugin);

    // Format currency
    function formatCurrency(value) {
        return '$' + new Intl.NumberFormat('en-US', {
            minimumFractionDigits: 0,
            maximumFractionDigits: 0
        }).format(value);
    }

    // Format percentage
    function formatPercentage(value) {
        return value.toFixed(1) + '%';
    }

    // Generate year-by-year projections
    function generateProjections(inputs) {
        const projections = [];
        const yearsToProject = inputs.targetAge - inputs.currentAge;
        let currentIncome = inputs.annualIncome;
        let netWorth = inputs.currentNetWorth;

        for (let year = 0; year <= yearsToProject; year++) {
            const age = inputs.currentAge + year;
            const currentYear = new Date().getFullYear() + year;
            const fireTarget = inputs.fireTarget * Math.pow(1 + inputs.inflationRate, year);
            const annualSavings = currentIncome * inputs.savingsRate;

            // Store starting net worth for the year
            const startingNetWorth = netWorth;

            // Calculate investment return for the year (return on starting net worth + savings)
            const investmentReturn = (netWorth + annualSavings) * inputs.returnRate;

            // Calculate ending net worth for the year
            const endingNetWorth = (netWorth + annualSavings) * (1 + inputs.returnRate);

            // Calculate progress based on ending net worth
            const progress = (endingNetWorth / fireTarget) * 100;

            projections.push({
                age: age,
                year: currentYear,
                netWorth: endingNetWorth,  // Store ENDING net worth
                startingNetWorth: startingNetWorth,  // Keep starting for modal calculation
                fireTarget: fireTarget,
                progress: progress,
                annualSavings: annualSavings,
                investmentReturn: investmentReturn,
                annualIncome: currentIncome,
                returnRate: inputs.returnRate
            });

            // Project next year's net worth and income
            netWorth = endingNetWorth;  // Next year starts with this year's ending
            currentIncome = currentIncome * (1 + inputs.incomeGrowthRate);
        }

        return projections;
    }    // Find the year FIRE is achieved
    function findFIREYear(projections) {
        return projections.find(p => p.progress >= 100);
    }

    // Update summary cards
    function updateSummary(projections, inputs) {
        const fireYear = findFIREYear(projections);
        const finalProjection = projections[projections.length - 1];
        const initialFireTarget = inputs.fireTarget;
        const annualSavings = inputs.annualIncome * inputs.savingsRate;

        // Update calculation explanations
        document.getElementById('calcAnnualSavings').textContent =
            `${formatCurrency(inputs.annualIncome)} × ${formatPercentage(inputs.savingsRate * 100)} = ${formatCurrency(annualSavings)}`;
        document.getElementById('calcFireTarget').textContent =
            `${formatCurrency(inputs.annualExpenses)} × 25 = ${formatCurrency(initialFireTarget)}`;

        let summaryHTML = `
            <div class="summary-card">
                <div class="summary-label">FIRE Target (Today)</div>
                <div class="summary-value">${formatCurrency(initialFireTarget)}</div>
                <div class="text-xs text-gray-600 mt-1">Based on 4% rule (25× expenses)</div>
            </div>

            <div class="summary-card">
                <div class="summary-label">FIRE Target (At Age ${inputs.targetAge})</div>
                <div class="summary-value">${formatCurrency(finalProjection.fireTarget)}</div>
                <div class="text-xs text-gray-600 mt-1">Adjusted for ${formatPercentage(inputs.inflationRate * 100)} annual inflation</div>
            </div>
        `;

        if (fireYear) {
            summaryHTML += `
                <div class="summary-card success">
                    <div class="summary-label">🎉 FIRE Achieved at Age</div>
                    <div class="summary-value">${fireYear.age}</div>
                    <div class="text-xs text-gray-600 mt-1">In ${fireYear.age - inputs.currentAge} years (${fireYear.year})</div>
                </div>

                <div class="summary-card success">
                    <div class="summary-label">Net Worth at FIRE</div>
                    <div class="summary-value">${formatCurrency(fireYear.netWorth)}</div>
                    <div class="text-xs text-gray-600 mt-1">${formatPercentage(fireYear.progress)} of target reached</div>
                </div>
            `;
        } else {
            summaryHTML += `
                <div class="summary-card warning">
                    <div class="summary-label">⚠️ FIRE Not Achieved by Age ${inputs.targetAge}</div>
                    <div class="summary-value">${formatPercentage(finalProjection.progress)}</div>
                    <div class="text-xs text-gray-600 mt-1">Consider: higher savings rate or later retirement age</div>
                </div>

                <div class="summary-card">
                    <div class="summary-label">Projected Net Worth at ${inputs.targetAge}</div>
                    <div class="summary-value">${formatCurrency(finalProjection.netWorth)}</div>
                    <div class="text-xs text-gray-600 mt-1">Shortfall: ${formatCurrency(finalProjection.fireTarget - finalProjection.netWorth)}</div>
                </div>
            `;
        }

        document.getElementById('summaryCards').innerHTML = summaryHTML;
    }

    // Update projection table
    function updateTable(projections) {
        let tableHTML = '';

        projections.forEach((proj, index) => {
            const rowClass = proj.progress >= 100 ? 'fire-achieved' : '';

            tableHTML += `
                <tr class="${rowClass}">
                    <td>${proj.age}</td>
                    <td>${proj.year}</td>
                    <td>${formatCurrency(proj.annualIncome)}</td>
                    <td>${formatCurrency(proj.annualSavings)}</td>
                    <td>${formatCurrency(proj.investmentReturn)}</td>
                    <td class="net-worth-cell" onclick="showNetWorthCalculation(${index})">${formatCurrency(proj.netWorth)}</td>
                    <td>${formatCurrency(proj.fireTarget)}</td>
                    <td>${formatPercentage(proj.progress)}</td>
                </tr>
            `;
        });

        document.getElementById('projectionTableBody').innerHTML = tableHTML;

        // Store projections globally for modal access
        window.currentProjections = projections;
    }

    // Adjust value with quick buttons
    function adjustValue(fieldId, delta) {
        const input = document.getElementById(fieldId);
        let currentValue = parseFloat(input.value) || 0;
        let newValue = currentValue + delta;

        // Apply min/max constraints
        const min = parseFloat(input.min) || -Infinity;
        const max = parseFloat(input.max) || Infinity;
        newValue = Math.max(min, Math.min(max, newValue));

        // Round to appropriate precision
        if (fieldId === 'returnRate' || fieldId === 'inflationRate' || fieldId === 'incomeGrowthRate') {
            newValue = Math.round(newValue * 10) / 10; // 1 decimal place
        } else {
            newValue = Math.round(newValue);
        }

        input.value = newValue;

        // Update quick adjustment display
        updateQuickAdjustmentDisplays();

        // Trigger calculation
        calculateFIRE();
    }

    // Update the quick adjustment display values
    function updateQuickAdjustmentDisplays() {
        const annualExpenses = parseFloat(document.getElementById('annualExpenses').value) || 0;
        const returnRate = parseFloat(document.getElementById('returnRate').value) || 0;
        const annualIncome = parseFloat(document.getElementById('annualIncome').value) || 0;
        const targetAge = parseInt(document.getElementById('targetAge').value) || 0;
        const incomeGrowthRate = parseFloat(document.getElementById('incomeGrowthRate').value) || 0;

        document.getElementById('quickExpensesValue').textContent = formatCurrency(annualExpenses);
        document.getElementById('quickReturnValue').textContent = returnRate.toFixed(1) + '%';
        document.getElementById('quickIncomeValue').textContent = formatCurrency(annualIncome);
        document.getElementById('quickTargetAgeValue').textContent = targetAge;
        document.getElementById('quickIncomeGrowthValue').textContent = incomeGrowthRate.toFixed(1) + '%';
    }

    // Get input values
    function getInputs() {
        const income = parseFloat(document.getElementById('annualIncome').value) || 0;
        const expenses = parseFloat(document.getElementById('annualExpenses').value) || 0;
        const savingsRate = parseFloat(document.getElementById('savingsRate').value) / 100 || 0;

        return {
            currentAge: parseInt(document.getElementById('currentAge').value) || 35,
            targetAge: parseInt(document.getElementById('targetAge').value) || 50,
            currentNetWorth: parseFloat(document.getElementById('currentNetWorth').value) || 0,
            totalNetWorth: parseFloat(document.getElementById('totalNetWorth').value) || 0,
            annualExpenses: expenses,
            annualIncome: income,
            savingsRate: savingsRate,
            returnRate: parseFloat(document.getElementById('returnRate').value) / 100 || 0.08,
            inflationRate: parseFloat(document.getElementById('inflationRate').value) / 100 || 0.025,
            incomeGrowthRate: parseFloat(document.getElementById('incomeGrowthRate').value) / 100 || 0,
            // Calculate FIRE target using 4% rule
            fireTarget: expenses * 25
        };
    }

    // Run Monte Carlo simulation
    function runMonteCarloSimulation(inputs, numSimulations = 100) {
        const maxYears = inputs.targetAge - inputs.currentAge + 10; // Add buffer years
        const results = [];

        for (let sim = 0; sim < numSimulations; sim++) {
            let netWorth = inputs.currentNetWorth;
            let currentIncome = inputs.annualIncome;
            let yearToFire = null;

            for (let year = 0; year < maxYears; year++) {
                const age = inputs.currentAge + year;
                const annualSavings = currentIncome * inputs.savingsRate;

                // Add randomness to returns (normal distribution)
                const volatility = 0.15; // 15% standard deviation
                const randomReturn = inputs.returnRate + (Math.random() - 0.5) * 2 * volatility;

                netWorth = (netWorth + annualSavings) * (1 + randomReturn);
                currentIncome = currentIncome * (1 + inputs.incomeGrowthRate);

                // Adjust FIRE target for inflation
                const inflationAdjustedTarget = inputs.fireTarget * Math.pow(1 + inputs.inflationRate, year);

                // Check if FIRE achieved
                if (netWorth >= inflationAdjustedTarget && yearToFire === null) {
                    yearToFire = year;
                    break;
                }
            }

            if (yearToFire !== null) {
                results.push(yearToFire);
            } else {
                results.push(maxYears); // Didn't achieve FIRE
            }
        }

        results.sort((a, b) => a - b);
        return results;
    }

    // Calculate FIRE
    function calculateFIRE() {
        const inputs = getInputs();

        // Validation
        if (inputs.targetAge <= inputs.currentAge) {
            alert('Target FIRE age must be greater than current age');
            return;
        }

        // Generate projections
        const projections = generateProjections(inputs);

        // Update summary cards
        updateSummary(projections, inputs);

        // Update projection table
        updateTable(projections);

        // Run Monte Carlo simulation
        const simulationResults = runMonteCarloSimulation(inputs, 100);

        if (simulationResults.length > 0) {
            const p10 = simulationResults[Math.floor(simulationResults.length * 0.10)];
            const p25 = simulationResults[Math.floor(simulationResults.length * 0.25)];
            const p50 = simulationResults[Math.floor(simulationResults.length * 0.50)];
            const p75 = simulationResults[Math.floor(simulationResults.length * 0.75)];
            const p90 = simulationResults[Math.floor(simulationResults.length * 0.90)];

            document.getElementById('cycleCount').textContent = simulationResults.length;
            document.getElementById('medianAge').textContent = p50.toFixed(1) + ' years';
            document.getElementById('range1090').textContent = p10.toFixed(1) + ' to ' + p90.toFixed(1) + ' years';
            document.getElementById('range2575').textContent = p25.toFixed(0) + ' to ' + p75.toFixed(0) + ' years';

            // Update all charts
            updateNetWorthChart(projections, inputs);
            updateMonteCarloChart(inputs, p10, p25, p50, p75, p90);
        }

        // Show results
        document.getElementById('resultsSection').classList.add('show');
    }

    // Update original net worth chart (simple version)
    function updateNetWorthChart(projections, inputs) {
        if (netWorthChart) {
            netWorthChart.destroy();
        }

        const ages = projections.map(p => p.age);
        const netWorths = projections.map(p => p.netWorth);
        const fireTargets = projections.map(p => p.fireTarget);

        const ctx = document.getElementById('netWorthChart').getContext('2d');
        netWorthChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ages,
                datasets: [{
                    label: 'Projected Net Worth',
                    data: netWorths,
                    borderColor: '#27ae60',
                    backgroundColor: 'rgba(39, 174, 96, 0.1)',
                    borderWidth: 3,
                    fill: true,
                    tension: 0.4,
                    pointRadius: 0
                }, {
                    label: 'FIRE Target (Inflation-Adjusted)',
                    data: fireTargets,
                    borderColor: '#e74c3c',
                    backgroundColor: 'transparent',
                    borderWidth: 2,
                    borderDash: [5, 5],
                    fill: false,
                    tension: 0.4,
                    pointRadius: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: {
                        display: true,
                        position: 'top'
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                        callbacks: {
                            label: function(context) {
                                return context.dataset.label + ': ' + formatCurrency(context.parsed.y);
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return '$' + (value / 1000000).toFixed(1) + 'M';
                            }
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: 'Age'
                        }
                    }
                }
            }
        });
    }

    // Update Monte Carlo chart with percentile bands
    function updateMonteCarloChart(inputs, p10, p25, p50, p75, p90) {
        if (monteCarloChart) {
            monteCarloChart.destroy();
        }

        // Only show up to retirement year + 5 years
        const maxYears = inputs.targetAge - inputs.currentAge + 5;
        const ages = [];

        // Generate projections for different percentiles
        const projections = {
            p10: [],
            p25: [],
            median: [],
            p75: [],
            p90: [],
            fireTarget: []
        };

        for (let year = 0; year <= maxYears; year++) {
            ages.push(inputs.currentAge + year);

            // Calculate net worth for median scenario
            let netWorth = inputs.currentNetWorth;
            const annualSavings = inputs.annualIncome * inputs.savingsRate;

            for (let y = 0; y < year; y++) {
                netWorth = (netWorth + annualSavings) * (1 + inputs.returnRate);
            }

            // Inflation-adjusted FIRE target
            const adjustedTarget = inputs.fireTarget * Math.pow(1 + inputs.inflationRate, year);
            projections.fireTarget.push(adjustedTarget);

            projections.median.push(netWorth);
            projections.p10.push(netWorth * 0.7);   // Conservative
            projections.p25.push(netWorth * 0.85);  // Below average
            projections.p75.push(netWorth * 1.15);  // Above average
            projections.p90.push(netWorth * 1.3);   // Optimistic
        }

        const ctx = document.getElementById('monteCarloChart').getContext('2d');

        monteCarloChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ages,
                datasets: [
                    {
                        label: '90th %ile',
                        data: projections.p90,
                        borderColor: 'rgba(255, 159, 64, 0.3)',
                        backgroundColor: 'rgba(255, 159, 64, 0.1)',
                        fill: '+1',
                        borderWidth: 1,
                        pointRadius: 0
                    },
                    {
                        label: '75th %ile',
                        data: projections.p75,
                        borderColor: 'rgba(154, 205, 50, 0.4)',
                        backgroundColor: 'rgba(154, 205, 50, 0.15)',
                        fill: '+1',
                        borderWidth: 1,
                        pointRadius: 0
                    },
                    {
                        label: 'Median',
                        data: projections.median,
                        borderColor: '#000',
                        backgroundColor: 'transparent',
                        borderWidth: 2,
                        pointRadius: 0
                    },
                    {
                        label: '25th %ile',
                        data: projections.p25,
                        borderColor: 'rgba(154, 205, 50, 0.4)',
                        backgroundColor: 'rgba(154, 205, 50, 0.15)',
                        fill: '+1',
                        borderWidth: 1,
                        pointRadius: 0
                    },
                    {
                        label: '10th %ile',
                        data: projections.p10,
                        borderColor: 'rgba(255, 159, 64, 0.3)',
                        backgroundColor: 'rgba(255, 159, 64, 0.1)',
                        fill: false,
                        borderWidth: 1,
                        pointRadius: 0
                    },
                    {
                        label: 'FIRE Target',
                        data: projections.fireTarget,
                        borderColor: '#e74c3c',
                        backgroundColor: 'transparent',
                        borderWidth: 2,
                        borderDash: [5, 5],
                        pointRadius: 0
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false
                    },
                    verticalLine: {
                        xValue: inputs.targetAge,
                        lineColor: 'rgb(54, 162, 235)',
                        lineWidth: 3,
                        lineDash: [10, 5],
                        label: 'Retire Age ' + inputs.targetAge
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return '$' + (value / 1000000).toFixed(1) + 'M';
                            }
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: 'Age'
                        }
                    }
                }
            }
        });
    }

    // Show Net Worth Calculation Modal
    function showNetWorthCalculation(index) {
        const proj = window.currentProjections[index];
        const modal = document.getElementById('netWorthModal');
        const content = document.getElementById('modalCalculationContent');

        let calculationHTML = '';

        // All years use the same calculation logic
        const startNetWorth = proj.startingNetWorth;
        const withSavings = startNetWorth + proj.annualSavings;
        const endNetWorth = withSavings * (1 + proj.returnRate);
        const returnPercent = (proj.returnRate * 100).toFixed(1);
        const returnMultiplier = (1 + proj.returnRate).toFixed(2);

        calculationHTML = `
            <div style="text-align: center; margin-bottom: 1.5rem;">
                <div class="text-sm text-gray-600 font-semibold">Age ${proj.age} - Year ${proj.year}</div>
                <div class="text-xs text-gray-500 mt-1">Showing net worth growth during this year</div>
            </div>

            <div class="calculation-step">
                <div class="calculation-label">Step 1: Starting Net Worth</div>
                <div class="calculation-value">${formatCurrency(startNetWorth)}</div>
                ${index === 0 ? '<div class="text-xs text-gray-600 mt-1">(Your initial net worth)</div>' :
                  `<div class="text-xs text-gray-600 mt-1">(This is what you ended age ${proj.age - 1} with)</div>`}
            </div>

            <div class="calculation-step">
                <div class="calculation-label">Step 2: Add Annual Savings</div>
                <div class="calculation-value">+ ${formatCurrency(proj.annualSavings)}</div>
                <div class="text-xs text-gray-600 mt-1">
                    From income of ${formatCurrency(proj.annualIncome)}
                </div>
            </div>

            <div class="calculation-step">
                <div class="calculation-label">Step 3: Subtotal Before Returns</div>
                <div class="calculation-value">= ${formatCurrency(withSavings)}</div>
            </div>

            <div class="calculation-formula">
                <div class="font-semibold mb-1">Apply Investment Return:</div>
                ${formatCurrency(withSavings)} × ${returnMultiplier} (${returnPercent}% return)
            </div>

            <div class="calculation-step highlight">
                <div class="calculation-label">Final: Ending Net Worth</div>
                <div class="calculation-value" style="font-size: 1.5rem; color: #2563eb;">
                    ${formatCurrency(endNetWorth)}
                </div>
                <div class="text-xs text-gray-600 mt-1">
                    (This becomes your starting net worth for age ${proj.age + 1})
                </div>
            </div>

            <div class="mt-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                <div class="text-xs font-semibold text-blue-900 mb-1">💡 Understanding the Formula</div>
                <div class="text-xs text-blue-800">
                    Net Worth (End) = (Net Worth (Start) + Annual Savings) × (1 + Return Rate)
                </div>
            </div>
        `;

        content.innerHTML = calculationHTML;
        modal.style.display = 'flex';

        // Close modal when clicking outside
        modal.onclick = function(event) {
            if (event.target === modal) {
                closeNetWorthModal();
            }
        };
    }

    // Close Net Worth Calculation Modal
    function closeNetWorthModal() {
        document.getElementById('netWorthModal').style.display = 'none';
    }

    // Close modal with Escape key
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeNetWorthModal();
        }
    });

    // Reset form
    function resetForm() {
        document.getElementById('currentAge').value = 35;
        document.getElementById('targetAge').value = 50;
        document.getElementById('currentNetWorth').value = 200000;
        document.getElementById('totalNetWorth').value = 900000;
        document.getElementById('annualExpenses').value = 130000;
        document.getElementById('annualIncome').value = 300000;
        document.getElementById('savingsRate').value = 40;
        document.getElementById('returnRate').value = 8;
        document.getElementById('inflationRate').value = 2.5;
        document.getElementById('incomeGrowthRate').value = 0;

        updateQuickAdjustmentDisplays();
        document.getElementById('resultsSection').classList.remove('show');
    }

    // Debounce function to avoid excessive calculations while typing
    let debounceTimer;
    function debounce(func, delay) {
        return function() {
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(() => func.apply(this, arguments), delay);
        };
    }

    // Auto-calculate when inputs change (debounced)
    const autoCalculate = debounce(function() {
        // Check if all required fields have values
        const inputs = getInputs();
        const hasAllValues =
            inputs.targetAge > inputs.currentAge &&
            !isNaN(inputs.currentNetWorth) &&
            !isNaN(inputs.annualIncome) &&
            !isNaN(inputs.annualExpenses) &&
            inputs.annualIncome > 0 &&
            inputs.fireTarget > 0;

        if (hasAllValues) {
            calculateFIRE();
        }
    }, 500); // 500ms delay after user stops typing

    // Initialize: Add event listeners to all input fields
    document.addEventListener('DOMContentLoaded', function() {
        const inputFields = [
            'currentAge',
            'targetAge',
            'currentNetWorth',
            'totalNetWorth',
            'annualExpenses',
            'annualIncome',
            'savingsRate',
            'returnRate',
            'inflationRate',
            'incomeGrowthRate'
        ];

        // Add input event listeners for auto-calculation
        inputFields.forEach(fieldId => {
            const field = document.getElementById(fieldId);
            if (field) {
                field.addEventListener('input', autoCalculate);
                field.addEventListener('change', autoCalculate);
            }
        });

        // Auto-calculate on page load if all fields have values
        setTimeout(() => {
            updateQuickAdjustmentDisplays();
            autoCalculate();
        }, 100);
    });
</script>
{% endblock %}
