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

{% block title %}Cross-Source Comparison — 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">Cross-Source Comparison</h1>
    <p class="text-slate-400 text-sm mt-1">Comparing drafts across {{ data.summary | length }} standards bodies on rating dimensions, category focus, and output volume.</p>
</div>

<!-- Summary Table -->
<div class="bg-slate-900 rounded-xl border border-slate-800 overflow-hidden mb-6">
    <div class="p-4 border-b border-slate-800">
        <h2 class="text-sm font-semibold text-slate-300">Standards Body Summary</h2>
        <p class="text-xs text-slate-500 mt-1">Overview of each source's contribution to the AI/agent standards landscape.</p>
    </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">Source</th>
                    <th class="px-4 py-3 font-medium text-center">Drafts</th>
                    <th class="px-4 py-3 font-medium text-center">Rated</th>
                    <th class="px-4 py-3 font-medium text-center">Authors</th>
                    <th class="px-4 py-3 font-medium text-center">Ideas</th>
                    <th class="px-4 py-3 font-medium text-center">Avg Score</th>
                    <th class="px-4 py-3 font-medium">Top Category</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-800/50">
                {% for row in data.summary | sort(attribute='drafts', reverse=True) %}
                <tr class="hover:bg-slate-800/50 transition">
                    <td class="px-4 py-3">
                        <span class="inline-block px-2 py-0.5 rounded text-xs font-semibold uppercase
                            {% if row.source == 'ietf' %}bg-blue-500/20 text-blue-400
                            {% elif row.source == 'iso' %}bg-green-500/20 text-green-400
                            {% elif row.source == 'itu' %}bg-yellow-500/20 text-yellow-400
                            {% elif row.source == 'w3c' %}bg-purple-500/20 text-purple-400
                            {% elif row.source == 'etsi' %}bg-red-500/20 text-red-400
                            {% elif row.source == 'nist' %}bg-cyan-500/20 text-cyan-400
                            {% else %}bg-slate-500/20 text-slate-400{% endif %}">{{ row.source }}</span>
                    </td>
                    <td class="px-4 py-3 text-center text-white font-mono">{{ row.drafts }}</td>
                    <td class="px-4 py-3 text-center text-slate-400 font-mono">{{ row.rated }}</td>
                    <td class="px-4 py-3 text-center text-slate-400 font-mono">{{ row.authors }}</td>
                    <td class="px-4 py-3 text-center text-slate-400 font-mono">{{ row.ideas }}</td>
                    <td class="px-4 py-3 text-center">
                        {% if row.avg_score >= 3.5 %}
                        <span class="score-badge score-high">{{ row.avg_score }}</span>
                        {% elif row.avg_score >= 2.5 %}
                        <span class="score-badge score-mid">{{ row.avg_score }}</span>
                        {% else %}
                        <span class="score-badge score-low">{{ row.avg_score }}</span>
                        {% endif %}
                    </td>
                    <td class="px-4 py-3">
                        <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400">{{ row.top_category }}</span>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
</div>

<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
    <!-- Radar Chart -->
    <div class="bg-slate-900 rounded-xl border border-slate-800 p-5">
        <h2 class="text-sm font-semibold text-slate-300 mb-1">Rating Dimensions by Source</h2>
        <p class="text-xs text-slate-500 mb-3">Average rating across five dimensions for each standards body. Larger shapes indicate higher average ratings.</p>
        <div id="radarChart" style="height: 400px;"></div>
    </div>

    <!-- Stacked Bar Chart -->
    <div class="bg-slate-900 rounded-xl border border-slate-800 p-5">
        <h2 class="text-sm font-semibold text-slate-300 mb-1">Category Distribution by Source</h2>
        <p class="text-xs text-slate-500 mb-3">What topics each standards body focuses on. Stacked bars show the relative emphasis per source.</p>
        <div id="stackedBar" style="height: 400px;"></div>
    </div>
</div>

<!-- Heatmap -->
<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">Sources x Categories Heatmap</h2>
    <p class="text-xs text-slate-500 mb-3">Draft counts per source-category pair. Darker cells = more drafts. Shows where each body concentrates its work.</p>
    <div id="heatmap" style="height: 400px;"></div>
</div>

<!-- Unique/Shared Categories -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
    <div class="bg-slate-900 rounded-xl border border-slate-800 p-5">
        <h2 class="text-sm font-semibold text-slate-300 mb-3">Shared Categories</h2>
        <p class="text-xs text-slate-500 mb-3">Categories covered by multiple standards bodies.</p>
        <div class="flex flex-wrap gap-2">
            {% for cat in data.shared_categories %}
            <a href="/drafts?cat={{ cat }}" class="px-2 py-1 rounded text-xs bg-blue-500/15 text-blue-400 border border-blue-500/20 hover:bg-blue-500/25 transition">{{ cat }}</a>
            {% endfor %}
        </div>
    </div>
    <div class="bg-slate-900 rounded-xl border border-slate-800 p-5">
        <h2 class="text-sm font-semibold text-slate-300 mb-3">Unique Categories by Source</h2>
        <p class="text-xs text-slate-500 mb-3">Categories only covered by a single standards body.</p>
        {% for src, cats in data.unique_categories.items() %}
        {% if cats %}
        <div class="mb-3">
            <span class="text-xs font-semibold uppercase text-slate-500">{{ src }}</span>
            <div class="flex flex-wrap gap-1 mt-1">
                {% for cat in cats %}
                <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400">{{ cat }}</span>
                {% endfor %}
            </div>
        </div>
        {% endif %}
        {% endfor %}
    </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 }};

// Source colors
const sourceColors = {
    'ietf': '#3b82f6', 'iso': '#22c55e', 'itu': '#eab308',
    'w3c': '#a855f7', 'etsi': '#ef4444', 'nist': '#06b6d4',
};
function srcColor(src) { return sourceColors[src] || '#64748b'; }

// Radar Chart
const radarDims = ['novelty', 'maturity', 'overlap', 'momentum', 'relevance'];
const radarLabels = ['Novelty', 'Maturity', 'Overlap', 'Momentum', 'Relevance'];
const radarTraces = Object.entries(data.radar).map(([src, vals]) => ({
    type: 'scatterpolar',
    r: radarDims.map(d => vals[d]).concat([vals[radarDims[0]]]),
    theta: radarLabels.concat([radarLabels[0]]),
    fill: 'toself',
    name: `${src.toUpperCase()} (${vals.count})`,
    opacity: 0.45,
    line: { color: srcColor(src) },
    fillcolor: srcColor(src) + '33',
}));
Plotly.newPlot('radarChart', radarTraces, {
    ...PLOTLY_LAYOUT,
    polar: {
        bgcolor: 'rgba(0,0,0,0)',
        radialaxis: { visible: true, range: [0, 5], gridcolor: '#1e293b', color: '#64748b' },
        angularaxis: { gridcolor: '#1e293b', color: '#94a3b8' },
    },
    legend: { font: { size: 10, color: '#94a3b8' } },
    margin: { t: 30, r: 60, b: 30, l: 60 },
}, CFG);

// Stacked Bar Chart
const heatmap = data.heatmap;
const barTraces = heatmap.categories.map((cat, ci) => ({
    name: cat,
    type: 'bar',
    x: heatmap.sources.map(s => s.toUpperCase()),
    y: heatmap.values.map(row => row[ci]),
}));
Plotly.newPlot('stackedBar', barTraces, {
    ...PLOTLY_LAYOUT,
    barmode: 'stack',
    xaxis: { ...PLOTLY_LAYOUT.xaxis, title: '' },
    yaxis: { ...PLOTLY_LAYOUT.yaxis, title: 'Draft Count' },
    legend: { font: { size: 9, color: '#94a3b8' }, orientation: 'h', y: -0.25 },
    margin: { t: 10, r: 10, b: 80, l: 50 },
}, CFG);

// Heatmap
Plotly.newPlot('heatmap', [{
    z: heatmap.values,
    x: heatmap.categories,
    y: heatmap.sources.map(s => s.toUpperCase()),
    type: 'heatmap',
    colorscale: [[0, '#0f172a'], [0.5, '#1e40af'], [1, '#3b82f6']],
    hovertemplate: '%{y} / %{x}<br>Drafts: %{z}<extra></extra>',
}], {
    ...PLOTLY_LAYOUT,
    xaxis: { ...PLOTLY_LAYOUT.xaxis, tickangle: -45 },
    yaxis: { ...PLOTLY_LAYOUT.yaxis, autorange: 'reversed' },
    margin: { t: 10, r: 10, b: 120, l: 60 },
}, CFG);
</script>
{% endblock %}
