<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Value Averaging Pro | Analysis Tool</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Epilogue:wght@300;400;600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    
    <style>
        body { font-family: 'Epilogue', sans-serif; background-color: #f4f7fe; color: #1a1f36; }
        .card { border: none; border-radius: 16px; box-shadow: 0 10px 30px rgba(0,0,0,0.04); background: #fff; }
        .kpi-card { border-radius: 12px; padding: 20px; text-align: center; height: 100%; border: 1px solid #edf2f7; }
        .next-inv-header { background: #4d55ff; color: white; border-radius: 12px 12px 0 0; padding: 15px; }
        
        /* Table Styling */
        .table thead th { background-color: #1a1f36; color: white; vertical-align: middle; border: none; }
        .table-striped tbody tr:nth-of-type(odd) { background-color: rgba(244, 247, 254, 0.7); }
        .badge-ret { border-radius: 50px; padding: 6px 12px; font-weight: 700; font-size: 0.85rem; }
        .col-dva { background-color: #2dce89 !important; color: white !important; }
        .col-dca { background-color: #11cdef !important; color: white !important; }
        
        /* Tab Styling */
        .nav-pills .nav-link { color: #4d55ff; font-weight: 600; padding: 12px 30px; }
        .nav-pills .nav-link.active { background-color: #4d55ff !important; }
        .chart-container { position: relative; height: 500px; width: 100%; }
    </style>
</head>
<body>
    <div class="container-fluid py-3" style="max-width: 1200px; margin-left: 0;">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h2 class="mb-0 fw-bold" style="font-size: 1.5rem;">🛠️ Value Averaging Strategy Analysis</h2>
            <button onclick="resetAll()" class="btn btn-warning btn-sm px-3">Reset</button>
        </div>

        <div class="row g-2 mb-3">
            <div class="col-md-3">
                <label class="form-label small fw-bold text-uppercase mb-1">Ticker</label>
                <input type="text" id="symbol" class="form-control form-control-sm" value="SPY">
            </div>
            <div class="col-md-3">
                <label class="form-label small fw-bold text-uppercase mb-1">Initial ($)</label>
                <input type="number" id="initial_inv" class="form-control form-control-sm" value="20000">
            </div>
            <div class="col-md-3">
                <label class="form-label small fw-bold text-uppercase mb-1">Monthly Target ($)</label>
                <input type="number" id="monthly_target" class="form-control form-control-sm" value="500">
            </div>
            <div class="col-md-3">
                <label class="form-label small fw-bold text-uppercase mb-1">Start Date</label>
                <input type="date" id="startDate" class="form-control form-control-sm" value="2024-01-01">
            </div>
        </div>

        <div class="row align-items-center g-3">
            <div class="col-auto">
                <div class="d-flex align-items-center">
                    <label class="small fw-bold text-uppercase me-2 mb-0">Frequency</label>
                    <select id="frequency" class="form-select form-select-sm" style="width: auto;">
                        <option value="Weekly">Weekly</option>
                        <option value="Bi-Weekly">Bi-Weekly</option>
                        <option value="Monthly" selected>Monthly</option>
                    </select>
                </div>
            </div>
        <div class="col-auto">
            <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="allow_sell" checked>
                <label class="form-check-label small fw-bold text-uppercase" for="allow_sell">Allow Share Sales</label>
            </div>
        </div>
        <div class="col-auto">
            <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="allow_fractional" checked>
                <label class="form-check-label small fw-bold text-uppercase" for="allow_fractional">Fractional Shares</label>
            </div>
        </div>
        <div class="col-auto">
            <button onclick="runSimulation()" class="btn btn-primary fw-bold px-4">Run Analysis</button>
        </div>
    </div>
    <div id="kpiArea" class="d-none mb-4">
        <div class="d-flex justify-content-end mb-2">
            <span id="syncBadge" class="badge rounded-pill bg-success px-3">
                Data Synced: <span id="lastSyncDate">YYYY-MM-DD</span>
            </span>
        </div>
        <div class="row g-3 d-flex align-items-stretch">
            <div class="col-md-4">
                <div class="card p-3 text-center h-100">
                    <h6 class="text-muted text-uppercase small">Target Value Goal</h6>
                    <h2 id="targetValueCard" class="fw-bold mb-1">$0.00</h2>
                    <small class="text-muted">Expected value</small>
                </div>
            </div>

            <div class="col-md-4">
                <div class="card p-3 text-center border-primary h-100">
                    <h6 class="text-muted text-uppercase small">Next Recommended Move</h6>
                    <h2 id="nextInvAmt" class="fw-bold mb-1">$0.00</h2>
                    <div class="small text-muted mb-2">
                        Price: <span id="latestPriceDisplay" class="fw-bold text-dark">$0.00</span> 
                        as of <span id="priceDateLabel" class="fw-bold text-dark">YYYY-MM-DD</span>
                    </div>
                    <p id="nextInvMsg" class="mb-0 small text-muted">Calculating...</p>
                </div>
            </div>

            <div class="col-md-4 d-flex flex-column">
                <div class="card p-2 text-center flex-fill mb-2 d-flex justify-content-center">
                    <p class="text-muted small mb-0">Total Invested (DVA)</p>
                    <div id="totalSaved" class="h5 fw-bold mb-0">$0.00</div>
                </div>
                <div class="card p-2 text-center flex-fill d-flex justify-content-center">
                    <p class="text-muted small mb-0">Current Portfolio Value</p>
                    <div id="totalVal" class="h5 fw-bold mb-0">$0.00</div>
                </div>
            </div>
        </div>

    <div id="resultsArea" class="d-none">
        <ul class="nav nav-pills nav-justified mb-3 card p-2 flex-row" id="mainTabs">
            <li class="nav-item"><button class="nav-link active" data-bs-toggle="pill" data-bs-target="#tab-chart">Performance Chart</button></li>
            <li class="nav-item"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#tab-table">Data Ledger</button></li>
        </ul>

        <div class="tab-content card p-4">
            <div class="tab-pane fade show active" id="tab-chart">
                <div class="chart-container">
                    <canvas id="mainChart"></canvas>
                </div>
            </div>
            <div class="tab-pane fade" id="tab-table">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="fw-bold m-0">Historical Ledger</h5>
                    <button class="btn btn-success btn-sm fw-bold" onclick="exportToExcel()">📥 Export to Excel</button>
                </div>
                <div class="table-responsive">
                    <table class="table table-striped align-middle border" id="ledgerTable">
                        <thead class="text-center">
                            <tr>
                                <th rowspan="2">Date</th>
                                <th rowspan="2">Price</th>
                                <th colspan="2" class="col-dva">Investment & Shares</th> <th colspan="2" class="col-dca">Total Value & Balance</th> <th colspan="2" class="bg-secondary">Annualized Return</th>
                            </tr>
                            <tr class="small">
                                <th class="col-dva">DVA ($ / Δ Shares)</th> <th class="col-dca">DCA</th>
                                <th class="col-dva">DVA ($ / Total Shrs)</th> <th class="col-dca">DCA</th>
                                <th class="col-dva">DVA (%)</th>
                                <th class="col-dca">DCA (%)</th>
                            </tr>
                        </thead>
                        <tbody id="tableBody" class="text-center"></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    let myChart = null;

   async function runSimulation() {
    // 1. Get references (Added frequency)
        const el = {
            symbol: document.getElementById('symbol'),
            initial: document.getElementById('initial_inv'),
            monthly: document.getElementById('monthly_target'),
            date: document.getElementById('startDate'),
            freq: document.getElementById('frequency'), // <--- ADDED
            sell: document.getElementById('allow_sell'),
            frac: document.getElementById('allow_fractional'),
            btn: document.querySelector("button[onclick='runSimulation()']")
        };

        // 2. Safety Check
        for (const [key, element] of Object.entries(el)) {
            if (!element) {
                console.error(`Error: Component '${key}' not found.`);
                return;
            }
        }

        const originalText = el.btn.innerHTML;

        try {
            const payload = {
                symbol: el.symbol.value.trim().toUpperCase(),
                initial_inv: parseFloat(el.initial.value) || 0,
                monthly_target: parseFloat(el.monthly.value) || 0,
                startDate: el.date.value,        // Match backend's preferred key
                frequency: el.freq.value,        // <--- CRITICAL: MUST BE SENT
                allow_sell: el.sell.checked,
                allow_fractional: el.frac.checked
            };

            if (!payload.symbol) {
                alert("Please enter a ticker symbol.");
                return;
            }

            // Loading State
            el.btn.disabled = true;
            el.btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Loading...';

            const res = await fetch('/api/backtest', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });

            // Parse response to check for specific Python errors
            const data = await res.json();
            
            if (!res.ok) {
                throw new Error(data.error || `Server returned ${res.status}`);
            }

            // Update UI
            document.getElementById('kpiArea')?.classList.remove('d-none');
            document.getElementById('resultsArea')?.classList.remove('d-none');

            updateKPIs(data, payload.monthly_target);
            renderDetailedChart(data);
            renderTable(data);

        } catch (err) {
            console.error("Simulation Error:", err);
            alert(`Analysis Failed: ${err.message}`);
        } finally {
            el.btn.disabled = false;
            el.btn.innerHTML = originalText;
        }
}
/**
 * Updates the summary cards with the DVA "Next Move" recommendation.
 * Uses the Fixed Value Path logic: (Last Target + Monthly Increment) - Current Value.
 */
    /**
 * Updates the Dashboard KPIs and Recommended Move
 * @param {Array} data - The history array from the Python backend
 * @param {number} monthlyTarget - The user-defined monthly investment increment
 */
function updateKPIs(data, monthlyTarget) {
    if (!data || data.length === 0) return;

    const last = data[data.length - 1];

    // Helper function to update text ONLY if the element exists
    const safeUpdate = (id, value) => {
        const el = document.getElementById(id);
        if (el) {
            el.innerText = value;
        } else {
            console.warn(`KPI Error: Element with ID '${id}' not found in HTML.`);
        }
    };

    // 1. Format the values from the Python response
    const targetVal = (last.va_target_value || 0).toLocaleString(undefined, {minimumFractionDigits: 2});
    const investedVal = (last.va_invested || 0).toLocaleString(undefined, {minimumFractionDigits: 2});
    const marketVal = (last.va_value || 0).toLocaleString(undefined, {minimumFractionDigits: 2});

    // 2. Push to the UI using the IDs defined in the HTML above
    safeUpdate('targetValueCard', `$${targetVal}`);
    safeUpdate('totalSaved', `$${investedVal}`);
    safeUpdate('totalVal', `$${marketVal}`);

    // 3. Update the Recommendation Card (Next Move)
    const nextMove = last.va_diff || 0;
    const nextAmtEl = document.getElementById('nextInvAmt');
    if (nextAmtEl) {
        nextAmtEl.innerText = (nextMove >= 0 ? "+" : "") + "$" + Math.abs(nextMove).toLocaleString();
        nextAmtEl.className = nextMove >= 0 ? "fw-bold text-success" : "fw-bold text-danger";
    }
}
/**
 * Updates a visual badge showing if data is fresh or stale
 */
function updateSyncBadge(dateString) {
    const syncDateEl = document.getElementById('lastSyncDate');
    const syncBadge = document.getElementById('syncBadge');
    
    if (syncDateEl && syncBadge) {
        syncDateEl.innerText = dateString;
        
        // Calculate age of data
        const dataDate = new Date(dateString);
        const today = new Date();
        const diffDays = Math.ceil(Math.abs(today - dataDate) / (1000 * 60 * 60 * 24));

        // Turn badge red if data is older than 5 days
        if (diffDays > 5) {
            syncBadge.classList.replace('bg-success', 'bg-danger');
        } else {
            syncBadge.classList.replace('bg-danger', 'bg-success');
        }
    }
}
    function renderDetailedChart(data) {
        if(myChart) myChart.destroy();
        const ctx = document.getElementById('mainChart').getContext('2d');
        
        myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: data.map(d => d.date),
                datasets: [
                    { label: 'Portfolio Value', data: data.map(d => d.va_value), borderColor: '#2dce89', yAxisID: 'y', tension: 0.3, fill: true, backgroundColor: 'rgba(45, 206, 137, 0.05)' },
                    { label: 'Total Invested', data: data.map(d => d.va_invested), borderColor: '#5e72e4', yAxisID: 'y', tension: 0, borderDash: [5,5] },
                    { label: 'Return (%)', data: data.map(d => ((d.va_value-d.va_invested)/d.va_invested*100).toFixed(2)), borderColor: '#f5365c', yAxisID: 'y1', tension: 0.3 }
                ]
            },
            options: {
                responsive: true, maintainAspectRatio: false,
                interaction: { mode: 'index', intersect: false }, // Critical for hover detail
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                let label = context.dataset.label || '';
                                let val = context.parsed.y;
                                return label.includes('%') ? `${label}: ${val}%` : `${label}: $${val.toLocaleString()}`;
                            }
                        }
                    }
                },
                scales: {
                    y: { type: 'linear', position: 'left', ticks: { callback: v => '$' + v.toLocaleString() } },
                    y1: { type: 'linear', position: 'right', grid: { drawOnChartArea: false }, ticks: { callback: v => v + '%' } }
                }
            }
        });
    }

    // 2. Updated renderTable to remove text labels and fix ID reference
    function renderTable(data) {
        const tableBody = document.getElementById('tableBody');
        const initialInput = parseFloat(document.getElementById('initial_inv').value) || 0;
        const monthlyInput = parseFloat(document.getElementById('monthly_target').value) || 0;
        
        if (!tableBody || !data) return;

        tableBody.innerHTML = data.map((d, index) => {
            const dcaInvestedThisMonth = index === 0 ? initialInput : monthlyInput;
            
            // Safety Fallbacks: Ensure numbers exist before calculation
            const vaVal = d.va_value || 0;
            const vaInv = d.va_invested || 0;
            const dcaVal = d.dca_value || 0;
            const dcaInv = d.dca_invested || 0;

            const vaAnnRet = vaInv > 0 ? (((vaVal - vaInv) / vaInv) * 100).toFixed(2) : "0.00";
            const dcaAnnRet = dcaInv > 0 ? (((dcaVal - dcaInv) / dcaInv) * 100).toFixed(2) : "0.00";

            return `
                <tr>
                    <td class="small fw-bold">${d.date}</td>
                    <td>$${(d.price || 0).toLocaleString(undefined, {minimumFractionDigits: 2})}</td>
                    
                    <td class="${(d.va_diff || 0) >= 0 ? 'text-success' : 'text-danger'} fw-bold">
                        $${(d.va_diff || 0).toLocaleString()}<br>
                        <small class="text-muted">${(d.va_shares_trans || 0) >= 0 ? '+' : ''}${(d.va_shares_trans || 0).toFixed(2)}</small>
                    </td>
                    
                    <td>
                        $${dcaInvestedThisMonth.toLocaleString()}<br>
                        <small class="text-muted">+${(d.dca_shares_trans || 0).toFixed(2)}</small>
                    </td>
                    
                    <td class="fw-bold">
                        $${vaVal.toLocaleString()}<br>
                        <small class="text-primary">${(d.va_shares_total || 0).toFixed(2)}</small>
                    </td>
                    
                    <td>
                        $${dcaVal.toLocaleString()}<br>
                        <small class="text-primary">${(d.dca_shares_total || 0).toFixed(2)}</small>
                    </td>
                    
                    <td>
                        <span class="badge ${parseFloat(vaAnnRet) >= 0 ? 'bg-success' : 'bg-danger'}">
                            ${vaAnnRet}%
                        </span>
                    </td>
                    <td>
                        <span class="badge ${parseFloat(dcaAnnRet) >= 0 ? 'bg-info' : 'bg-danger'}">
                            ${dcaAnnRet}%
                        </span>
                    </td>
                </tr>`;
        }).join('');
    }
    
    function exportToExcel() {
        const table = document.getElementById("ledgerTable");
        const wb = XLSX.utils.table_to_book(table);
        XLSX.writeFile(wb, "Investment_Backtest_Results.xlsx");
    }

    function resetAll() {
    // 1. Reset Inputs to Defaults (Including Frequency)
    const defaults = {
        'symbol': 'SPY',
        'initial_inv': 20000,
        'monthly_target': 500,
        'startDate': '2024-01-01',
        'frequency': 'Monthly'  // <--- Added this
    };

    Object.keys(defaults).forEach(id => {
        const input = document.getElementById(id);
        if (input) input.value = defaults[id];
    });

    // 2. Reset Toggles
    const sellToggle = document.getElementById('allow_sell');
    const fracToggle = document.getElementById('allow_fractional');
    if (sellToggle) sellToggle.checked = true;
    if (fracToggle) fracToggle.checked = true;

    // 3. Hide Result Sections
    document.getElementById('kpiArea')?.classList.add('d-none');
    document.getElementById('resultsArea')?.classList.add('d-none');

    // 4. Clear Data
    const tableBody = document.getElementById('tableBody');
    if (tableBody) tableBody.innerHTML = '';
    
    // 5. Clear Chart if it exists
    if (window.detailedChart) {
        window.detailedChart.destroy();
        window.detailedChart = null;
    }

    console.log("Dashboard reset to defaults.");
}
</script>
</body>
</html>