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

{% block title %}Complexity — 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">Draft Complexity Matrix</h1>
    <p class="text-slate-400 text-sm mt-1">Correlating structural complexity (pages, authors, citations, ideas) with quality ratings. Does more complexity mean better drafts?</p>
</div>

<!-- Stats Cards -->
<div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 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">Avg Pages</div>
        <div class="text-2xl font-bold text-white mt-1">{{ data.stats.avg_pages }}</div>
        <div class="text-xs text-slate-500 mt-1">{{ data.stats.pages_coverage_pct }}% have page data</div>
    </div>
    <div class="stat-card rounded-xl border border-slate-800 p-4">
        <div class="text-xs text-slate-500 uppercase tracking-wider">Avg Authors</div>
        <div class="text-2xl font-bold text-white mt-1">{{ data.stats.avg_authors }}</div>
    </div>
    <div class="stat-card rounded-xl border border-slate-800 p-4">
        <div class="text-xs text-slate-500 uppercase tracking-wider">Avg Citations</div>
        <div class="text-2xl font-bold text-white mt-1">{{ data.stats.avg_citations }}</div>
    </div>
    <div class="stat-card rounded-xl border border-slate-800 p-4">
        <div class="text-xs text-slate-500 uppercase tracking-wider">Drafts Analyzed</div>
        <div class="text-2xl font-bold text-white mt-1">{{ data.stats.total_drafts }}</div>
    </div>
    <div class="stat-card rounded-xl border border-slate-800 p-4">
        <div class="text-xs text-slate-500 uppercase tracking-wider">Metrics</div>
        <div class="text-2xl font-bold text-white mt-1">{{ data.metrics | length }} x {{ data.dimensions | length }}</div>
        <div class="text-xs text-slate-500 mt-1">complexity x rating</div>
    </div>
</div>

<!-- Scatter Plot Matrix -->
<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">Complexity vs Rating Scatter Plots</h2>
    <p class="text-xs text-slate-500 mb-3">How structural complexity metrics relate to rating dimensions. Each dot is a rated draft. Click to navigate.</p>
    <div id="scatterMatrix" style="height: 500px;"></div>
</div>

<!-- Correlation 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">Correlation Matrix</h2>
        <p class="text-xs text-slate-500 mt-1">Pearson correlation between complexity metrics (rows) and rating dimensions (columns). Green = positive, red = negative. Values range from -1 to +1.</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">Metric</th>
                    {% for dim in data.dimensions %}
                    <th class="px-4 py-3 font-medium text-center">{{ dim | capitalize }}</th>
                    {% endfor %}
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-800/50" id="corrTable">
            </tbody>
        </table>
    </div>
</div>

<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
    <!-- Top 10 Most Complex -->
    <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">Top 10 Most Complex Drafts</h2>
            <p class="text-xs text-slate-500 mt-1">Ranked by composite complexity (pages + authors + citations + ideas, normalized).</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-2 font-medium">#</th>
                        <th class="px-4 py-2 font-medium">Draft</th>
                        <th class="px-4 py-2 font-medium text-right">Pages</th>
                        <th class="px-4 py-2 font-medium text-right">Authors</th>
                        <th class="px-4 py-2 font-medium text-right">Cites</th>
                        <th class="px-4 py-2 font-medium text-right">Score</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-800/50" id="complexTable">
                </tbody>
            </table>
        </div>
    </div>

    <!-- Top 10 Most Efficient -->
    <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">Top 10 Most Efficient Drafts</h2>
            <p class="text-xs text-slate-500 mt-1">High ratings relative to low structural complexity. Efficiency = score / complexity.</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-2 font-medium">#</th>
                        <th class="px-4 py-2 font-medium">Draft</th>
                        <th class="px-4 py-2 font-medium text-right">Pages</th>
                        <th class="px-4 py-2 font-medium text-right">Authors</th>
                        <th class="px-4 py-2 font-medium text-right">Score</th>
                        <th class="px-4 py-2 font-medium text-right">Efficiency</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-800/50" id="efficientTable">
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Category Complexity -->
<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">Complexity by Category</h2>
    <p class="text-xs text-slate-500 mb-3">Average complexity metrics per category. Wider bars = more complex category.</p>
    <div id="catComplexity" style="height: 400px;"></div>
</div>

<!-- Source Complexity -->
<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">Complexity by Source</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">Source</th>
                    <th class="px-4 py-3 font-medium text-right">Count</th>
                    <th class="px-4 py-3 font-medium text-right">Avg Pages</th>
                    <th class="px-4 py-3 font-medium text-right">Avg Authors</th>
                    <th class="px-4 py-3 font-medium text-right">Avg Citations</th>
                    <th class="px-4 py-3 font-medium text-right">Avg Score</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-800/50">
                {% for s in data.source_complexity %}
                <tr class="hover:bg-slate-800/50 transition">
                    <td class="px-4 py-2 text-slate-300 font-medium">{{ s.source | upper }}</td>
                    <td class="px-4 py-2 text-right text-slate-400">{{ s.count }}</td>
                    <td class="px-4 py-2 text-right text-slate-300">{{ s.avg_pages }}</td>
                    <td class="px-4 py-2 text-right text-slate-300">{{ s.avg_authors }}</td>
                    <td class="px-4 py-2 text-right text-slate-300">{{ s.avg_citations }}</td>
                    <td class="px-4 py-2 text-right">
                        {% if s.avg_score >= 3.0 %}
                        <span class="score-badge score-high">{{ s.avg_score }}</span>
                        {% elif s.avg_score >= 2.0 %}
                        <span class="score-badge score-mid">{{ s.avg_score }}</span>
                        {% else %}
                        <span class="score-badge score-low">{{ s.avg_score }}</span>
                        {% 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: 30, r: 20, b: 40, l: 50 },
    xaxis: { gridcolor: '#1e293b', zerolinecolor: '#334155' },
    yaxis: { gridcolor: '#1e293b', zerolinecolor: '#334155' },
};
const CFG = { responsive: true, displayModeBar: false };

const cdata = {{ data | tojson }};

// Scatter plot matrix (2x3 subplots)
(function() {
    const pairs = [
        { x: 'pages', y: 'novelty', xLabel: 'Pages', yLabel: 'Novelty' },
        { x: 'author_count', y: 'maturity', xLabel: 'Authors', yLabel: 'Maturity' },
        { x: 'citation_count', y: 'relevance', xLabel: 'Citations', yLabel: 'Relevance' },
        { x: 'idea_count', y: 'momentum', xLabel: 'Ideas', yLabel: 'Momentum' },
        { x: 'pages', y: 'maturity', xLabel: 'Pages', yLabel: 'Maturity' },
        { x: 'citation_count', y: 'novelty', xLabel: 'Citations', yLabel: 'Novelty' },
    ];
    const colors = ['#3b82f6', '#22c55e', '#a855f7', '#f59e0b', '#06b6d4', '#ef4444'];
    const traces = [];
    const annotations = [];

    pairs.forEach((p, i) => {
        const row = i < 3 ? 1 : 2;
        const col = (i % 3) + 1;
        const xaxis = i === 0 ? 'x' : `x${i + 1}`;
        const yaxis = i === 0 ? 'y' : `y${i + 1}`;
        const filteredDrafts = p.x === 'pages'
            ? cdata.drafts.filter(d => d.pages !== null)
            : cdata.drafts;
        traces.push({
            x: filteredDrafts.map(d => d[p.x]),
            y: filteredDrafts.map(d => d[p.y]),
            text: filteredDrafts.map(d => d.name),
            type: 'scatter',
            mode: 'markers',
            marker: { color: colors[i], size: 5, opacity: 0.6 },
            xaxis: xaxis,
            yaxis: yaxis,
            hovertemplate: `<b>%{text}</b><br>${p.xLabel}: %{x}<br>${p.yLabel}: %{y}<extra></extra>`,
            showlegend: false,
        });
    });

    const layout = {
        ...PLOTLY_LAYOUT,
        grid: { rows: 2, columns: 3, pattern: 'independent' },
        margin: { t: 30, r: 20, b: 40, l: 50 },
    };
    // Set axis labels
    pairs.forEach((p, i) => {
        const xKey = i === 0 ? 'xaxis' : `xaxis${i + 1}`;
        const yKey = i === 0 ? 'yaxis' : `yaxis${i + 1}`;
        layout[xKey] = { ...PLOTLY_LAYOUT.xaxis, title: { text: p.xLabel, font: { size: 10 } } };
        layout[yKey] = { ...PLOTLY_LAYOUT.yaxis, title: { text: p.yLabel, font: { size: 10 } } };
    });

    Plotly.newPlot('scatterMatrix', traces, layout, CFG);

    // Click to navigate
    document.getElementById('scatterMatrix').on('plotly_click', function(ev) {
        const pt = ev.points[0];
        if (pt.text) window.location.href = '/drafts/' + pt.text;
    });
})();

// Correlation table
(function() {
    const tbody = document.getElementById('corrTable');
    const metricLabels = { pages: 'Pages', author_count: 'Authors', citation_count: 'Citations', idea_count: 'Ideas', category_count: 'Categories' };
    cdata.metrics.forEach(metric => {
        const row = document.createElement('tr');
        row.className = 'hover:bg-slate-800/50 transition';
        let cells = `<td class="px-4 py-2 text-slate-300 font-medium">${metricLabels[metric] || metric}</td>`;
        cdata.dimensions.forEach(dim => {
            const val = cdata.correlations[metric][dim];
            let bgClass, textColor;
            const absVal = Math.abs(val);
            if (val > 0.2) { bgClass = 'bg-green-900/30'; textColor = 'text-green-400'; }
            else if (val < -0.2) { bgClass = 'bg-red-900/30'; textColor = 'text-red-400'; }
            else if (absVal > 0.1) { bgClass = 'bg-yellow-900/20'; textColor = 'text-yellow-400'; }
            else { bgClass = ''; textColor = 'text-slate-500'; }
            cells += `<td class="px-4 py-2 text-center ${bgClass}"><span class="${textColor} font-mono text-xs">${val.toFixed(3)}</span></td>`;
        });
        row.innerHTML = cells;
        tbody.appendChild(row);
    });
})();

// Top 10 Complex table
(function() {
    const tbody = document.getElementById('complexTable');
    cdata.top_complex.forEach((d, i) => {
        const row = document.createElement('tr');
        row.className = 'hover:bg-slate-800/50 transition';
        const shortName = d.name.replace('draft-', '').substring(0, 35);
        const scoreClass = d.score >= 3.0 ? 'score-high' : d.score >= 2.0 ? 'score-mid' : 'score-low';
        row.innerHTML = `
            <td class="px-4 py-2 text-slate-500 font-mono text-xs">${i + 1}</td>
            <td class="px-4 py-2"><a href="/drafts/${d.name}" class="text-blue-400 hover:text-blue-300 text-xs font-mono">${shortName}</a></td>
            <td class="px-4 py-2 text-right text-slate-300">${d.pages !== null ? d.pages : '-'}</td>
            <td class="px-4 py-2 text-right text-slate-300">${d.author_count}</td>
            <td class="px-4 py-2 text-right text-slate-300">${d.citation_count}</td>
            <td class="px-4 py-2 text-right"><span class="score-badge ${scoreClass}">${d.score.toFixed(2)}</span></td>
        `;
        tbody.appendChild(row);
    });
})();

// Top 10 Efficient table
(function() {
    const tbody = document.getElementById('efficientTable');
    cdata.top_efficient.forEach((d, i) => {
        const row = document.createElement('tr');
        row.className = 'hover:bg-slate-800/50 transition';
        const shortName = d.name.replace('draft-', '').substring(0, 35);
        const scoreClass = d.score >= 3.0 ? 'score-high' : d.score >= 2.0 ? 'score-mid' : 'score-low';
        row.innerHTML = `
            <td class="px-4 py-2 text-slate-500 font-mono text-xs">${i + 1}</td>
            <td class="px-4 py-2"><a href="/drafts/${d.name}" class="text-blue-400 hover:text-blue-300 text-xs font-mono">${shortName}</a></td>
            <td class="px-4 py-2 text-right text-slate-300">${d.pages !== null ? d.pages : '-'}</td>
            <td class="px-4 py-2 text-right text-slate-300">${d.author_count}</td>
            <td class="px-4 py-2 text-right"><span class="score-badge ${scoreClass}">${d.score.toFixed(2)}</span></td>
            <td class="px-4 py-2 text-right text-green-400 font-mono text-xs">${d.efficiency.toFixed(1)}</td>
        `;
        tbody.appendChild(row);
    });
})();

// Category complexity bar chart
(function() {
    const cats = cdata.category_complexity.slice(0, 12);
    const catNames = cats.map(c => c.category);
    Plotly.newPlot('catComplexity', [
        {
            y: catNames, x: cats.map(c => c.avg_pages),
            name: 'Avg Pages', type: 'bar', orientation: 'h',
            marker: { color: '#3b82f6', opacity: 0.8 },
        },
        {
            y: catNames, x: cats.map(c => c.avg_citations),
            name: 'Avg Citations', type: 'bar', orientation: 'h',
            marker: { color: '#22c55e', opacity: 0.8 },
        },
        {
            y: catNames, x: cats.map(c => c.avg_authors * 5),
            name: 'Avg Authors (x5)', type: 'bar', orientation: 'h',
            marker: { color: '#a855f7', opacity: 0.8 },
        },
    ], {
        ...PLOTLY_LAYOUT,
        barmode: 'group',
        xaxis: { ...PLOTLY_LAYOUT.xaxis, title: 'Value' },
        yaxis: { ...PLOTLY_LAYOUT.yaxis, autorange: 'reversed' },
        legend: { font: { size: 10, color: '#94a3b8' }, orientation: 'h', y: -0.15 },
        margin: { t: 10, r: 20, b: 60, l: 150 },
    }, CFG);
})();
</script>
{% endblock %}
