{% extends "base.html" %}
{% set active_page = "trends" %}

{% block title %}Trends — IETF Draft Analyzer{% endblock %}

{% block extra_head %}<script src="/static/js/plotly.min.js"></script>{% endblock %}

{% block content %}
<div class="mb-6">
    <h1 class="text-2xl font-bold text-white">Temporal Evolution</h1>
    <p class="text-slate-400 text-sm mt-1">How the AI standards landscape is changing over time. Submission volume, rating trends, category shifts, and the safety-vs-capability balance.</p>
</div>

<!-- Stats Cards -->
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
    <div class="stat-card rounded-xl border border-slate-800 p-4">
        <div class="text-xs text-slate-500 uppercase tracking-wider">Months Tracked</div>
        <div class="text-2xl font-bold text-white mt-1">{{ data.months | length }}</div>
    </div>
    <div class="stat-card rounded-xl border border-slate-800 p-4">
        <div class="text-xs text-slate-500 uppercase tracking-wider">Total Submissions</div>
        <div class="text-2xl font-bold text-white mt-1">{{ data.monthly_table | sum(attribute='total') }}</div>
    </div>
    <div class="stat-card rounded-xl border border-slate-800 p-4">
        <div class="text-xs text-slate-500 uppercase tracking-wider">Fastest Growing</div>
        <div class="text-lg font-bold text-green-400 mt-1">{{ data.stats.fastest_growing or 'N/A' }}</div>
    </div>
    <div class="stat-card rounded-xl border border-slate-800 p-4">
        <div class="text-xs text-slate-500 uppercase tracking-wider">Newest Category</div>
        <div class="text-lg font-bold text-blue-400 mt-1">{{ data.stats.newest_active or 'N/A' }}</div>
    </div>
</div>

<!-- Monthly Submissions by Source -->
<div class="bg-slate-900 rounded-xl border border-slate-800 p-5 mb-6">
    <h2 class="text-sm font-semibold text-slate-300 mb-1">Monthly Draft Submissions by Source</h2>
    <p class="text-xs text-slate-500 mb-3">Stacked area chart showing submission volume over time, broken down by source (IETF, W3C, etc.).</p>
    <div id="submissionChart" style="height: 350px;"></div>
</div>

<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
    <!-- Monthly Average Ratings -->
    <div class="bg-slate-900 rounded-xl border border-slate-800 p-5">
        <h2 class="text-sm font-semibold text-slate-300 mb-1">Monthly Average Ratings</h2>
        <p class="text-xs text-slate-500 mb-3">Are drafts getting more mature? More novel? Track the five rating dimensions over time.</p>
        <div id="ratingsChart" style="height: 350px;"></div>
    </div>
    <!-- Safety Ratio -->
    <div class="bg-slate-900 rounded-xl border border-slate-800 p-5">
        <h2 class="text-sm font-semibold text-slate-300 mb-1">Safety vs Capability Ratio</h2>
        <p class="text-xs text-slate-500 mb-3">Ratio of safety-related drafts (Security, Privacy, Trust, Safety, Governance) to capability drafts (Agents, Infrastructure, MCP, etc.). Higher = more safety focus.</p>
        <div id="safetyChart" style="height: 350px;"></div>
    </div>
</div>

<!-- Category Distribution Over Time -->
<div class="bg-slate-900 rounded-xl border border-slate-800 p-5 mb-6">
    <h2 class="text-sm font-semibold text-slate-300 mb-1">Category Distribution Over Time</h2>
    <p class="text-xs text-slate-500 mb-3">Stacked area showing which topics are growing or shrinking. Top 8 categories shown.</p>
    <div id="categoryChart" style="height: 400px;"></div>
</div>

<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
    <!-- Cumulative Ideas -->
    <div class="bg-slate-900 rounded-xl border border-slate-800 p-5">
        <h2 class="text-sm font-semibold text-slate-300 mb-1">Cumulative Idea Count</h2>
        <p class="text-xs text-slate-500 mb-3">Total number of unique technical ideas extracted from drafts over time.</p>
        <div id="ideasChart" style="height: 300px;"></div>
    </div>
    <!-- New Authors -->
    <div class="bg-slate-900 rounded-xl border border-slate-800 p-5">
        <h2 class="text-sm font-semibold text-slate-300 mb-1">Monthly New Authors</h2>
        <p class="text-xs text-slate-500 mb-3">First-time contributors entering the AI standards space each month.</p>
        <div id="authorsChart" style="height: 300px;"></div>
    </div>
</div>

<!-- Monthly Breakdown Table -->
<div class="bg-slate-900 rounded-xl border border-slate-800 overflow-hidden">
    <div class="p-4 border-b border-slate-800">
        <h2 class="text-sm font-semibold text-slate-300">Monthly Breakdown</h2>
    </div>
    <div class="overflow-x-auto">
        <table class="w-full text-sm">
            <thead>
                <tr class="border-b border-slate-800 text-left text-xs text-slate-500">
                    <th class="px-4 py-3 font-medium">Month</th>
                    <th class="px-4 py-3 font-medium text-right">Total</th>
                    <th class="px-4 py-3 font-medium text-right">Avg Score</th>
                    <th class="px-4 py-3 font-medium">Trend</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-800/50">
                {% for row in data.monthly_table %}
                <tr class="hover:bg-slate-800/50 transition">
                    <td class="px-4 py-2 font-mono text-xs text-slate-300">{{ row.month }}</td>
                    <td class="px-4 py-2 text-right text-slate-300">{{ row.total }}</td>
                    <td class="px-4 py-2 text-right">
                        {% if row.avg_score >= 3.0 %}
                        <span class="text-green-400">{{ row.avg_score }}</span>
                        {% elif row.avg_score >= 2.0 %}
                        <span class="text-yellow-400">{{ row.avg_score }}</span>
                        {% else %}
                        <span class="text-slate-500">{{ row.avg_score }}</span>
                        {% endif %}
                    </td>
                    <td class="px-4 py-2">
                        {% if loop.index > 1 %}
                            {% set prev = data.monthly_table[loop.index0 - 1].total %}
                            {% if row.total > prev %}
                            <span class="text-green-400 text-xs font-mono">&#x2191; +{{ row.total - prev }}</span>
                            {% elif row.total < prev %}
                            <span class="text-red-400 text-xs font-mono">&#x2193; {{ row.total - prev }}</span>
                            {% else %}
                            <span class="text-slate-500 text-xs font-mono">&#x2192; 0</span>
                            {% endif %}
                        {% endif %}
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
</div>
{% endblock %}

{% block extra_scripts %}
<script>
const PLOTLY_LAYOUT = {
    paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)',
    font: { color: '#94a3b8', family: 'Inter, system-ui, sans-serif', size: 12 },
    margin: { t: 20, r: 20, b: 40, l: 50 },
    xaxis: { gridcolor: '#1e293b', zerolinecolor: '#334155' },
    yaxis: { gridcolor: '#1e293b', zerolinecolor: '#334155' },
};
const CFG = { responsive: true, displayModeBar: false };

const data = {{ data | tojson }};

// 1. Monthly submissions by source (stacked area)
(function() {
    const bySource = {};
    data.monthly_submissions.forEach(r => {
        if (!bySource[r.source]) bySource[r.source] = {};
        bySource[r.source][r.month] = r.count;
    });
    const months = data.months;
    const colors = ['#3b82f6', '#22c55e', '#f59e0b', '#ef4444', '#a855f7', '#06b6d4'];
    const traces = Object.entries(bySource).map(([src, monthly], i) => ({
        x: months,
        y: months.map(m => monthly[m] || 0),
        name: src.toUpperCase(),
        type: 'scatter',
        mode: 'lines',
        stackgroup: 'one',
        line: { color: colors[i % colors.length], width: 0 },
        fillcolor: colors[i % colors.length] + '80',
    }));
    Plotly.newPlot('submissionChart', traces, {
        ...PLOTLY_LAYOUT,
        xaxis: { ...PLOTLY_LAYOUT.xaxis, title: 'Month' },
        yaxis: { ...PLOTLY_LAYOUT.yaxis, title: 'Draft Count' },
        legend: { font: { size: 10, color: '#94a3b8' } },
    }, CFG);
})();

// 2. Monthly average ratings (5 lines)
(function() {
    const dims = ['novelty', 'maturity', 'overlap', 'momentum', 'relevance'];
    const labels = ['Novelty', 'Maturity', 'Overlap', 'Momentum', 'Relevance'];
    const colors = ['#3b82f6', '#22c55e', '#ef4444', '#f59e0b', '#a855f7'];
    const months = data.monthly_ratings.map(r => r.month);
    const traces = dims.map((d, i) => ({
        x: months,
        y: data.monthly_ratings.map(r => r[d]),
        name: labels[i],
        type: 'scatter',
        mode: 'lines+markers',
        line: { color: colors[i], width: 2 },
        marker: { size: 4 },
    }));
    Plotly.newPlot('ratingsChart', traces, {
        ...PLOTLY_LAYOUT,
        xaxis: { ...PLOTLY_LAYOUT.xaxis },
        yaxis: { ...PLOTLY_LAYOUT.yaxis, title: 'Avg Rating (1-5)', range: [0.5, 5.5] },
        legend: { font: { size: 10, color: '#94a3b8' } },
    }, CFG);
})();

// 3. Safety ratio
(function() {
    const months = data.safety_ratio.map(r => r.month);
    Plotly.newPlot('safetyChart', [
        {
            x: months,
            y: data.safety_ratio.map(r => r.ratio),
            type: 'scatter',
            mode: 'lines+markers',
            line: { color: '#22c55e', width: 2 },
            marker: { size: 5 },
            name: 'Safety/Capability Ratio',
            hovertemplate: '%{x}<br>Ratio: %{y:.2f}<br>Safety: %{customdata[0]}<br>Capability: %{customdata[1]}<extra></extra>',
            customdata: data.safety_ratio.map(r => [r.safety, r.capability]),
        },
        {
            x: months,
            y: months.map(() => 1.0),
            type: 'scatter',
            mode: 'lines',
            line: { color: '#64748b', width: 1, dash: 'dash' },
            name: 'Parity line',
            showlegend: false,
        }
    ], {
        ...PLOTLY_LAYOUT,
        xaxis: { ...PLOTLY_LAYOUT.xaxis },
        yaxis: { ...PLOTLY_LAYOUT.yaxis, title: 'Ratio (safety / capability)' },
        showlegend: false,
    }, CFG);
})();

// 4. Category distribution (stacked area)
(function() {
    const months = data.months;
    const cats = data.top_categories;
    const colors = ['#3b82f6', '#22c55e', '#f59e0b', '#ef4444', '#a855f7', '#06b6d4', '#f97316', '#ec4899'];
    // Build per-cat monthly data
    const catMonthly = {};
    data.monthly_categories.forEach(r => {
        if (!catMonthly[r.category]) catMonthly[r.category] = {};
        catMonthly[r.category][r.month] = r.count;
    });
    const traces = cats.map((cat, i) => ({
        x: months,
        y: months.map(m => (catMonthly[cat] || {})[m] || 0),
        name: cat,
        type: 'scatter',
        mode: 'lines',
        stackgroup: 'one',
        line: { color: colors[i % colors.length], width: 0 },
        fillcolor: colors[i % colors.length] + '80',
    }));
    Plotly.newPlot('categoryChart', traces, {
        ...PLOTLY_LAYOUT,
        xaxis: { ...PLOTLY_LAYOUT.xaxis, title: 'Month' },
        yaxis: { ...PLOTLY_LAYOUT.yaxis, title: 'Draft Count' },
        legend: { font: { size: 10, color: '#94a3b8' } },
    }, CFG);
})();

// 5. Cumulative ideas
(function() {
    Plotly.newPlot('ideasChart', [{
        x: data.cumulative_ideas.map(r => r.month),
        y: data.cumulative_ideas.map(r => r.total),
        type: 'scatter',
        mode: 'lines',
        fill: 'tozeroy',
        line: { color: '#3b82f6', width: 2 },
        fillcolor: 'rgba(59,130,246,0.15)',
    }], {
        ...PLOTLY_LAYOUT,
        xaxis: { ...PLOTLY_LAYOUT.xaxis },
        yaxis: { ...PLOTLY_LAYOUT.yaxis, title: 'Total Ideas' },
        showlegend: false,
    }, CFG);
})();

// 6. New authors per month
(function() {
    Plotly.newPlot('authorsChart', [{
        x: data.monthly_new_authors.map(r => r.month),
        y: data.monthly_new_authors.map(r => r.count),
        type: 'bar',
        marker: { color: '#a855f7', opacity: 0.8 },
    }], {
        ...PLOTLY_LAYOUT,
        xaxis: { ...PLOTLY_LAYOUT.xaxis },
        yaxis: { ...PLOTLY_LAYOUT.yaxis, title: 'New Authors' },
        showlegend: false,
    }, CFG);
})();
</script>
{% endblock %}
