<div class="results-container mt-3">
    <div class="card mb-4">
        <div class="card-header">
            <h5 class="card-title mb-0">Backtest Results for {{ results.strategy_name }}</h5>
        </div>
        <div class="card-body">
            <!-- Chart Container -->
            <div id="chart-container-{{ results.task_id }}" style="width: 100%; height: 400px; margin-bottom: 2em;"></div>

            <!-- Summary Metrics Table -->
            <h5 class="mt-4">Key Metrics</h5>
            <div class="table-responsive">
                <table class="summary-table table">
                    <tbody>
                        {% for key, value in results.summary.items() %}
                        <tr>
                            <td class="w-50"><strong>{{ key }}</strong></td>
                            <td>{{ value }}</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Include TradingView Lightweight Charts Library -->
    <script src="https://unpkg.com/lightweight-charts/dist/lightweight-charts.standalone.production.js"></script>

    <script>
        // Use a self-executing function to avoid polluting the global scope
        (function() {
            // Use a unique ID for the chart container to support multiple charts on one page
            const chartContainer = document.getElementById('chart-container-{{ results.task_id }}');
            if (!chartContainer) {
                console.error("Chart container not found!");
                return;
            }

            // The | tojson filter is crucial for safely embedding JSON data in JS
            const equityCurveData = {{ results.equity_curve | tojson }};

            if (!equityCurveData || equityCurveData.length === 0) {
                chartContainer.innerHTML = "<p class='text-muted text-center'>No equity curve data available to display.</p>";
                return;
            }
            
            // Initialize the chart with a dark theme
            const chart = LightweightCharts.createChart(chartContainer, {
                width: chartContainer.clientWidth,
                height: 400,
                layout: {
                    background: { color: '#1e222d' }, // var(--bg-secondary-color)
                    textColor: '#d1d4dc',        // var(--text-color)
                },
                grid: {
                    vertLines: { color: '#2a2e39' }, // var(--border-color)
                    horzLines: { color: '#2a2e39' },
                },
                timeScale: {
                    timeVisible: true,
                    secondsVisible: false,
                },
                crosshair: {
                    mode: LightweightCharts.CrosshairMode.Normal,
                },
            });

            // Add an area series for the equity curve
            const areaSeries = chart.addAreaSeries({
                topColor: 'rgba(41, 98, 255, 0.56)', // Primary color with opacity
                bottomColor: 'rgba(41, 98, 255, 0.04)',
                lineColor: 'rgba(41, 98, 255, 1)',
                lineWidth: 2,
                title: 'Equity'
            });

            // Format data for the chart library: { time: 'YYYY-MM-DD', value: 12345.67 }
            const formattedData = equityCurveData.map(item => ({
                time: item.timestamp.split('T')[0], // Use YYYY-MM-DD for the time scale
                value: item.equity
            }));

            areaSeries.setData(formattedData);
            chart.timeScale().fitContent();

            // Handle chart resizing when the window is resized
            new ResizeObserver(entries => {
                if (entries.length > 0 && entries[0].contentRect.width > 0) {
                    chart.applyOptions({ width: entries[0].contentRect.width });
                }
            }).observe(chartContainer);

        })();
    </script>
</div>