<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ page_title }} — Fluxibly Monitoring</title>
    <link rel="stylesheet" href="/static/css/dashboard.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js"></script>
</head>
<body>
    <nav class="sidebar">
        <div class="sidebar-header">
            <h2>Fluxibly</h2>
            <span class="subtitle">Monitoring</span>
        </div>
        <ul class="nav-links">
            <li><a href="/" class="{% if page_title == 'Overview' %}active{% endif %}">Overview</a></li>
            <li><a href="/traces" class="{% if page_title == 'Traces' %}active{% endif %}">Traces</a></li>
            <li><a href="/analytics" class="{% if page_title == 'Analytics' %}active{% endif %}">Analytics</a></li>
            <li><a href="/analytics/models" class="{% if page_title == 'Model Usage' %}active{% endif %}">Models</a></li>
            <li><a href="/analytics/agents" class="{% if page_title == 'Agent Usage' %}active{% endif %}">Agents</a></li>
        </ul>
    </nav>

    <main class="content">
        <header class="page-header">
            <h1>{{ page_title }}</h1>
        </header>

        {% block content %}
        <!-- Overview Dashboard -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-label">Total Requests</div>
                <div class="stat-value">{{ stats.total_requests | default(0) }}</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Total Cost</div>
                <div class="stat-value">${{ "%.4f" | format(stats.total_cost | default(0) | float) }}</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Input Tokens</div>
                <div class="stat-value">{{ "{:,}".format(stats.total_input_tokens | default(0) | int) }}</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Output Tokens</div>
                <div class="stat-value">{{ "{:,}".format(stats.total_output_tokens | default(0) | int) }}</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Total Tokens</div>
                <div class="stat-value">{{ "{:,}".format(stats.total_tokens | default(0) | int) }}</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Avg Latency</div>
                <div class="stat-value">{{ "%.0f" | format(stats.avg_duration_ms | default(0) | float) }}ms</div>
            </div>
        </div>

        {# ── Usage Over Time Chart ── #}
        {% if daily_usage is defined and daily_usage %}
        <section class="card">
            <div class="card-header">
                <h3>Usage</h3>
                <div class="chart-controls">
                    <select id="usageMetric" onchange="updateUsageChart()">
                        <option value="cost" selected>Cost ($)</option>
                        <option value="tokens">Total Tokens</option>
                        <option value="requests">Requests</option>
                    </select>
                </div>
            </div>
            <div class="usage-chart-container">
                <canvas id="usageChart"></canvas>
            </div>
        </section>
        <script>
        (function() {
            var dailyData = {{ daily_usage | tojson }};
            var labels = dailyData.map(function(d) { return d.day; });
            var datasets = {
                cost: dailyData.map(function(d) { return parseFloat(d.total_cost) || 0; }),
                tokens: dailyData.map(function(d) { return parseInt(d.total_tokens) || 0; }),
                requests: dailyData.map(function(d) { return parseInt(d.request_count) || 0; })
            };
            var colors = {
                cost: { bg: 'rgba(74, 108, 247, 0.7)', border: 'rgba(74, 108, 247, 1)' },
                tokens: { bg: 'rgba(245, 158, 11, 0.7)', border: 'rgba(245, 158, 11, 1)' },
                requests: { bg: 'rgba(16, 185, 129, 0.7)', border: 'rgba(16, 185, 129, 1)' }
            };
            var chartLabels = {
                cost: 'Cost ($)',
                tokens: 'Total Tokens',
                requests: 'Requests'
            };
            var ctx = document.getElementById('usageChart').getContext('2d');
            var chart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: chartLabels.cost,
                        data: datasets.cost,
                        backgroundColor: colors.cost.bg,
                        borderColor: colors.cost.border,
                        borderWidth: 1,
                        borderRadius: 3
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            callbacks: {
                                label: function(ctx) {
                                    var metric = document.getElementById('usageMetric').value;
                                    if (metric === 'cost') return '$' + ctx.parsed.y.toFixed(6);
                                    return ctx.parsed.y.toLocaleString();
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            grid: { display: false },
                            ticks: { font: { size: 11 } }
                        },
                        y: {
                            beginAtZero: true,
                            grid: { color: '#e2e8f0' },
                            ticks: {
                                font: { size: 11 },
                                callback: function(v) {
                                    var metric = document.getElementById('usageMetric').value;
                                    if (metric === 'cost') return '$' + v.toFixed(4);
                                    if (v >= 1000) return (v / 1000).toFixed(1) + 'k';
                                    return v;
                                }
                            }
                        }
                    }
                }
            });
            window.updateUsageChart = function() {
                var metric = document.getElementById('usageMetric').value;
                chart.data.datasets[0].data = datasets[metric];
                chart.data.datasets[0].label = chartLabels[metric];
                chart.data.datasets[0].backgroundColor = colors[metric].bg;
                chart.data.datasets[0].borderColor = colors[metric].border;
                chart.update();
            };
        })();
        </script>
        {% endif %}

        {% if top_models %}
        <section class="card">
            <h3>Top Models</h3>
            <table class="data-table">
                <thead>
                    <tr><th>Model</th><th>Requests</th><th>Cost</th></tr>
                </thead>
                <tbody>
                    {% for m in top_models %}
                    <tr>
                        <td>{{ m.model }}</td>
                        <td>{{ m.request_count }}</td>
                        <td>${{ "%.4f" | format(m.total_cost | float) }}</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </section>
        {% endif %}

        {% if recent_traces %}
        <section class="card">
            <h3>Recent Traces <a href="/traces" class="link-small">View all</a></h3>
            <table class="data-table">
                <thead>
                    <tr><th>ID</th><th>Input</th><th>Status</th><th>Cost</th><th>Duration</th><th>Time</th></tr>
                </thead>
                <tbody>
                    {% for t in recent_traces %}
                    <tr>
                        <td><a href="/traces/{{ t.trace_id }}">{{ t.trace_id[:8] }}...</a></td>
                        <td class="truncate">{{ (t.entry_input or '')[:60] }}{% if (t.entry_input or '') | length > 60 %}...{% endif %}</td>
                        <td><span class="badge badge-{{ t.status }}">{{ t.status }}</span></td>
                        <td>${{ "%.4f" | format(t.total_cost | default(0) | float) }}</td>
                        <td>{{ t.total_duration_ms | default('-') }}ms</td>
                        <td>{{ t.created_at }}</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </section>
        {% endif %}
        {% endblock %}
    </main>

    <script src="/static/js/charts.js?v=1.0.2"></script>
</body>
</html>
