{% extends "base.html" %}
{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip, privacy_note %}

{% block title %}Star Reviews Analytics{% endblock %}

{% block extra_head %}
<link rel="stylesheet" href="/static/css/star_reviews.css">
{% endblock %}

{% block content %}
<div class="ldr-star-reviews-container">
    <div class="ldr-metrics-header">
        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px;">
            <h1>⭐ Star Reviews Analytics</h1>
            <a href="/metrics/" style="background: var(--bg-tertiary); color: var(--text-primary); padding: 0.5rem 1rem; border-radius: 0.375rem; text-decoration: none; font-size: 0.875rem; border: 1px solid var(--border-color); transition: background-color 0.2s ease;">
                ← Back to Metrics
            </a>
        </div>
        <p>Comprehensive analysis of user satisfaction ratings</p>
    </div>

    <div class="ldr-period-selector">
        <label for="period-select">Time Period: </label>
        <select id="period-select">
            <option value="7d">Last 7 days</option>
            <option value="30d" selected>Last 30 days</option>
            <option value="3m">Last 3 months</option>
            <option value="1y">Last year</option>
            <option value="all">All time</option>
        </select>
    </div>

    <!-- Understanding Star Reviews Help Panel -->
    {% call help_panel('reviews-how', 'Understanding Star Reviews', icon='star', collapsed=true, dismissible=true) %}
    <div class="ldr-help-steps">
        {{ help_step(1, "Rate Your Research", "After viewing results, rate them 1-5 stars. This helps you track which settings produce best results.") }}
        {{ help_step(2, "Model Comparison", "See which AI models and search engines give you the highest satisfaction.") }}
        {{ help_step(3, "Improve Over Time", "Use insights to adjust settings - switch to models or engines that consistently rate higher.") }}
    </div>
    {{ privacy_note("All rating data is stored locally on your device only - never shared or sent anywhere.") }}
    {% endcall %}

    <div id="loading" class="ldr-loading">
        <div>Loading star reviews data...</div>
    </div>

    <div id="error" class="ldr-error" style="display: none;"></div>

    <!-- Screen-reader live region. Kept OUTSIDE #content (which is display:none
         until data loads) so it stays in the accessibility tree and reliably
         announces on each refresh / period change — a region toggled with its
         content does not announce. -->
    <div id="chart-status" role="status" aria-live="polite" class="sr-only"></div>

    <div id="content" style="display: none;">
        <!-- Overall Statistics with Doughnut -->
        <div class="ldr-metric-card">
            <h3>📊 Overall Satisfaction</h3>
            <div class="ldr-overall-stats">
                <div class="ldr-stat-item">
                    <span class="ldr-stat-value" id="avg-rating">0.0</span>
                    <div class="ldr-stat-label">Average Rating</div>
                </div>
                <div class="ldr-stat-item">
                    <span class="ldr-stat-value" id="total-ratings">0</span>
                    <div class="ldr-stat-label">Total Ratings</div>
                </div>
                <div class="ldr-stat-item">
                    <span class="ldr-stat-value" id="satisfaction-rate">0%</span>
                    <div class="ldr-stat-label">Satisfaction Rate</div>
                </div>
            </div>

            <div class="ldr-satisfaction-layout">
                <div class="ldr-rating-distribution">
                    <h4>Rating Distribution</h4>
                    <div class="ldr-rating-bar">
                        <div class="ldr-rating-label">5 ⭐</div>
                        <div class="ldr-rating-progress">
                            <div class="ldr-rating-fill" id="rating-5" style="width: 0%;"></div>
                        </div>
                        <div class="ldr-rating-count" id="count-5">0</div>
                    </div>
                    <div class="ldr-rating-bar">
                        <div class="ldr-rating-label">4 ⭐</div>
                        <div class="ldr-rating-progress">
                            <div class="ldr-rating-fill" id="rating-4" style="width: 0%;"></div>
                        </div>
                        <div class="ldr-rating-count" id="count-4">0</div>
                    </div>
                    <div class="ldr-rating-bar">
                        <div class="ldr-rating-label">3 ⭐</div>
                        <div class="ldr-rating-progress">
                            <div class="ldr-rating-fill" id="rating-3" style="width: 0%;"></div>
                        </div>
                        <div class="ldr-rating-count" id="count-3">0</div>
                    </div>
                    <div class="ldr-rating-bar">
                        <div class="ldr-rating-label">2 ⭐</div>
                        <div class="ldr-rating-progress">
                            <div class="ldr-rating-fill" id="rating-2" style="width: 0%;"></div>
                        </div>
                        <div class="ldr-rating-count" id="count-2">0</div>
                    </div>
                    <div class="ldr-rating-bar">
                        <div class="ldr-rating-label">1 ⭐</div>
                        <div class="ldr-rating-progress">
                            <div class="ldr-rating-fill" id="rating-1" style="width: 0%;"></div>
                        </div>
                        <div class="ldr-rating-count" id="count-1">0</div>
                    </div>
                </div>

                <div class="ldr-distribution-doughnut">
                    <canvas id="distribution-doughnut-chart"></canvas>
                </div>
            </div>
        </div>

        <div class="ldr-metrics-grid">
            <!-- Rating Trends Over Time (with volume overlay) -->
            <div class="ldr-metric-card">
                <h3>📈 Rating Trends</h3>
                <div class="ldr-chart-container">
                    <canvas id="rating-trends-chart"></canvas>
                </div>
            </div>

            <!-- Research Mode Comparison -->
            <div class="ldr-metric-card">
                <h3>🔬 Research Mode Comparison</h3>
                <div class="ldr-chart-container">
                    <canvas id="mode-ratings-chart"></canvas>
                </div>
                <div id="mode-empty-state" class="ldr-empty-state" style="display: none;">
                    No mode data available yet.
                </div>
            </div>

            <!-- LLM Model Ratings Chart -->
            <div class="ldr-metric-card">
                <h3>🤖 LLM Model Performance</h3>
                <div class="ldr-chart-container">
                    <canvas id="llm-ratings-chart"></canvas>
                </div>
            </div>

            <!-- LLM Satisfaction Breakdown -->
            <div class="ldr-metric-card">
                <h3>📊 LLM Rating Breakdown</h3>
                <div class="ldr-chart-container">
                    <canvas id="llm-breakdown-chart"></canvas>
                </div>
                <div id="llm-breakdown-empty-state" class="ldr-empty-state" style="display: none;">
                    No LLM data available yet.
                </div>
            </div>

            <!-- Search Engine Ratings Chart -->
            <div class="ldr-metric-card">
                <h3>🔍 Search Engine Performance</h3>
                <div class="ldr-chart-container">
                    <canvas id="search-engine-ratings-chart"></canvas>
                </div>
            </div>

            <!-- Quality Dimensions Radar -->
            <div class="ldr-metric-card">
                <h3>🎯 Quality Dimensions</h3>
                <div class="ldr-chart-container">
                    <canvas id="quality-radar-chart"></canvas>
                </div>
                <div id="quality-empty-state" class="ldr-empty-state" style="display: none;">
                    No detailed ratings yet. Detailed ratings will appear here once you rate research on individual quality dimensions.
                </div>
            </div>

            <!-- Recent Ratings -->
            <div class="ldr-metric-card">
                <h3>🕐 Recent Ratings</h3>
                <div class="ldr-recent-ratings" id="recent-ratings">
                </div>
            </div>

            <!-- Recent Feedback -->
            <div class="ldr-metric-card">
                <h3>💬 Recent Feedback</h3>
                <div class="ldr-recent-feedback" id="recent-feedback">
                </div>
            </div>
        </div>
    </div>

    <div class="ldr-info-section">
        <div class="ldr-info-card">
            <div class="ldr-info-icon">📊</div>
            <div class="ldr-info-content">
                <h3>Data-Driven Research Optimization</h3>
                <p>Use your personal rating history to optimize your research workflow. Instead of relying on intuition alone, leverage actual performance statistics to identify which LLM models, search engines, and research approaches deliver the best results for your specific needs.</p>
            </div>
        </div>

        <div class="ldr-info-grid">
            <div class="ldr-info-item">
                <div class="ldr-info-item-icon">🤖</div>
                <h4>Model Performance</h4>
                <p>Compare LLM models based on your actual satisfaction ratings to choose the best performing one for your research style.</p>
            </div>

            <div class="ldr-info-item">
                <div class="ldr-info-item-icon">🔍</div>
                <h4>Search Engine Insights</h4>
                <p>Discover which search engines consistently deliver higher-quality results for your research topics and preferences.</p>
            </div>

            <div class="ldr-info-item">
                <div class="ldr-info-item-icon">📈</div>
                <h4>Trend Analysis</h4>
                <p>Track your satisfaction trends over time to understand how your research effectiveness evolves and identify optimization opportunities.</p>
            </div>

            <div class="ldr-info-item">
                <div class="ldr-info-item-icon">🎯</div>
                <h4>Personalized Recommendations</h4>
                <p>Make informed decisions about your research configuration based on your personal usage patterns and satisfaction data.</p>
            </div>
        </div>
    </div>
</div>

<script>
let llmChart, searchEngineChart, trendsChart, doughnutChart, modeChart, llmBreakdownChart, qualityRadarChart;

const escapeHtml = window.escapeHtml || function(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
};

document.addEventListener('DOMContentLoaded', function() {
    loadStarReviews();
    document.getElementById('period-select').addEventListener('change', loadStarReviews);
});

async function loadStarReviews() {
    const period = document.getElementById('period-select').value;
    showLoading();

    try {
        const response = await fetch(`/metrics/api/star-reviews?period=${period}`);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        const data = await response.json();
        if (data.error) {
            showError(data.error);
            return;
        }

        updateOverallStats(data.overall_stats);
        updateDoughnutChart(data.overall_stats);
        updateLLMChart(data.llm_ratings);
        updateSearchEngineChart(data.search_engine_ratings);
        updateTrendsChart(data.rating_trends);
        updateRecentRatings(data.recent_ratings);

        if (data.mode_ratings) updateModeChart(data.mode_ratings);
        if (data.llm_ratings) updateLLMBreakdownChart(data.llm_ratings);
        if (data.quality_dimensions) updateQualityRadar(data.quality_dimensions);
        if (data.recent_feedback) updateRecentFeedback(data.recent_feedback);

        showContent();
        announceChartStates();
    } catch (error) {
        console.error('Error loading star reviews:', error);
        showError('Failed to load star reviews data: ' + error.message);
    }
}

// Announce the refresh (and any empty charts) to screen readers via the
// persistent #chart-status live region. Reads the empty-state visibility the
// chart updaters just set, so it reflects their own emptiness decisions.
function announceChartStates() {
    const region = document.getElementById('chart-status');
    if (!region) return;
    const charts = [
        ['mode-empty-state', 'research mode comparison'],
        ['llm-breakdown-empty-state', 'LLM rating breakdown'],
        ['quality-empty-state', 'quality dimensions'],
    ];
    const empty = charts
        .filter(([id]) => {
            const el = document.getElementById(id);
            return el && el.style.display !== 'none';
        })
        .map(([, label]) => label);
    region.textContent = empty.length
        ? `Star reviews updated. No data yet for: ${empty.join(', ')}.`
        : 'Star reviews updated.';
}

function showLoading() {
    document.getElementById('loading').style.display = 'block';
    document.getElementById('content').style.display = 'none';
    document.getElementById('error').style.display = 'none';
}

function showContent() {
    document.getElementById('loading').style.display = 'none';
    document.getElementById('content').style.display = 'block';
    document.getElementById('error').style.display = 'none';
}

function showError(message) {
    document.getElementById('loading').style.display = 'none';
    document.getElementById('content').style.display = 'none';
    document.getElementById('error').style.display = 'block';
    document.getElementById('error').textContent = message;
    // Announce the actual failure via the persistent live region. (#error is
    // display:none until shown, so a live role on it wouldn't reliably fire;
    // #chart-status is always in the accessibility tree.)
    const region = document.getElementById('chart-status');
    if (region) region.textContent = message;
}

function updateOverallStats(stats) {
    document.getElementById('avg-rating').textContent = stats.avg_rating;
    document.getElementById('total-ratings').textContent = stats.total_ratings;

    const satisfactionRate = stats.total_ratings > 0 ?
        Math.round(((stats.rating_distribution['4'] + stats.rating_distribution['5']) / stats.total_ratings) * 100) : 0;
    document.getElementById('satisfaction-rate').textContent = satisfactionRate + '%';

    const total = stats.total_ratings || 1;
    for (let i = 1; i <= 5; i++) {
        const count = stats.rating_distribution[i.toString()] || 0;
        const percentage = Math.round((count / total) * 100);
        document.getElementById(`rating-${i}`).style.width = percentage + '%';
        document.getElementById(`count-${i}`).textContent = count;
    }
}

function updateDoughnutChart(stats) {
    const ctx = document.getElementById('distribution-doughnut-chart').getContext('2d');
    if (doughnutChart) doughnutChart.destroy();

    const colors = [
        'rgba(75, 192, 192, 0.8)',
        'rgba(54, 162, 235, 0.8)',
        'rgba(255, 206, 86, 0.8)',
        'rgba(255, 159, 64, 0.8)',
        'rgba(255, 99, 132, 0.8)',
    ];

    doughnutChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: ['5 Stars', '4 Stars', '3 Stars', '2 Stars', '1 Star'],
            datasets: [{
                data: [
                    stats.rating_distribution['5'] || 0,
                    stats.rating_distribution['4'] || 0,
                    stats.rating_distribution['3'] || 0,
                    stats.rating_distribution['2'] || 0,
                    stats.rating_distribution['1'] || 0,
                ],
                backgroundColor: colors,
                borderWidth: 1,
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            cutout: '60%',
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: { padding: 12, usePointStyle: true }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const pct = total > 0 ? Math.round((context.parsed / total) * 100) : 0;
                            return `${context.label}: ${context.parsed} (${pct}%)`;
                        }
                    }
                }
            }
        },
        plugins: [{
            id: 'centerText',
            afterDraw(chart) {
                const { ctx: c, width, height } = chart;
                c.save();
                c.font = 'bold 1.5rem sans-serif';
                c.fillStyle = getComputedStyle(document.documentElement).getPropertyValue('--text-primary').trim() || '#333';
                c.textAlign = 'center';
                c.textBaseline = 'middle';
                c.fillText(stats.avg_rating || '0', width / 2, height / 2 - 8);
                c.font = '0.75rem sans-serif';
                c.fillText('avg', width / 2, height / 2 + 14);
                c.restore();
            }
        }]
    });
}

function updateTrendsChart(ratingTrends) {
    const ctx = document.getElementById('rating-trends-chart').getContext('2d');
    if (trendsChart) trendsChart.destroy();

    trendsChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ratingTrends.map(item => new Date(item.date).toLocaleDateString()),
            datasets: [
                {
                    label: 'Daily Ratings',
                    data: ratingTrends.map(item => item.count),
                    backgroundColor: 'rgba(200, 200, 200, 0.3)',
                    borderColor: 'rgba(200, 200, 200, 0.5)',
                    borderWidth: 1,
                    yAxisID: 'y1',
                    order: 2,
                },
                {
                    label: 'Average Rating',
                    type: 'line',
                    data: ratingTrends.map(item => item.avg_rating),
                    borderColor: 'rgba(75, 192, 192, 1)',
                    backgroundColor: 'rgba(75, 192, 192, 0.2)',
                    borderWidth: 2,
                    fill: true,
                    tension: 0.4,
                    yAxisID: 'y',
                    order: 1,
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    max: 5,
                    position: 'left',
                    title: { display: true, text: 'Average Rating' }
                },
                y1: {
                    beginAtZero: true,
                    position: 'right',
                    grid: { drawOnChartArea: false },
                    title: { display: true, text: 'Number of Ratings' }
                },
                x: {
                    title: { display: true, text: 'Date' }
                }
            },
            plugins: {
                legend: { display: true }
            }
        }
    });
}

function updateModeChart(modeRatings) {
    const canvas = document.getElementById('mode-ratings-chart');
    const emptyState = document.getElementById('mode-empty-state');
    if (modeChart) modeChart.destroy();

    const sortedData = modeRatings.sort((a, b) => b.avg_rating - a.avg_rating).slice(0, 10);

    if (sortedData.length === 0) {
        canvas.style.display = 'none';
        emptyState.style.display = 'block';
        return;
    }

    canvas.style.display = 'block';
    emptyState.style.display = 'none';

    const ctx = canvas.getContext('2d');

    modeChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: sortedData.map(item => item.mode || 'Unknown'),
            datasets: [{
                label: 'Average Rating',
                data: sortedData.map(item => item.avg_rating),
                backgroundColor: 'rgba(153, 102, 255, 0.8)',
                borderColor: 'rgba(153, 102, 255, 1)',
                borderWidth: 1,
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            indexAxis: 'y',
            scales: {
                x: {
                    beginAtZero: true,
                    max: 5,
                    title: { display: true, text: 'Average Rating' }
                }
            },
            plugins: {
                legend: { display: false },
                tooltip: {
                    callbacks: {
                        afterLabel: function(context) {
                            const item = sortedData[context.dataIndex];
                            return [`Ratings: ${item.rating_count}`, `Satisfaction: ${item.satisfaction_rate}%`];
                        }
                    }
                }
            }
        }
    });
}

function updateLLMBreakdownChart(llmRatings) {
    const canvas = document.getElementById('llm-breakdown-chart');
    const emptyState = document.getElementById('llm-breakdown-empty-state');
    if (llmBreakdownChart) llmBreakdownChart.destroy();

    const sortedData = llmRatings.sort((a, b) => b.avg_rating - a.avg_rating).slice(0, 10);

    if (sortedData.length === 0) {
        canvas.style.display = 'none';
        emptyState.style.display = 'block';
        return;
    }

    canvas.style.display = 'block';
    emptyState.style.display = 'none';

    const ctx = canvas.getContext('2d');

    llmBreakdownChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: sortedData.map(item => item.model || 'Unknown'),
            datasets: [
                {
                    label: 'Positive (4-5)',
                    data: sortedData.map(item => item.positive_ratings || 0),
                    backgroundColor: 'rgba(75, 192, 192, 0.8)',
                    borderWidth: 1,
                },
                {
                    label: 'Neutral (3)',
                    data: sortedData.map(item => item.neutral_ratings || 0),
                    backgroundColor: 'rgba(255, 206, 86, 0.8)',
                    borderWidth: 1,
                },
                {
                    label: 'Negative (1-2)',
                    data: sortedData.map(item => item.negative_ratings || 0),
                    backgroundColor: 'rgba(255, 99, 132, 0.8)',
                    borderWidth: 1,
                },
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            indexAxis: 'y',
            scales: {
                x: {
                    stacked: true,
                    title: { display: true, text: 'Number of Ratings' }
                },
                y: {
                    stacked: true,
                }
            },
            plugins: {
                legend: { position: 'bottom' }
            }
        }
    });
}

function updateLLMChart(llmRatings) {
    const ctx = document.getElementById('llm-ratings-chart').getContext('2d');
    if (llmChart) llmChart.destroy();

    const sortedData = llmRatings.sort((a, b) => b.avg_rating - a.avg_rating).slice(0, 10);

    llmChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: sortedData.map(item => item.model || 'Unknown'),
            datasets: [{
                label: 'Average Rating',
                data: sortedData.map(item => item.avg_rating),
                backgroundColor: 'rgba(54, 162, 235, 0.8)',
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    max: 5,
                    title: { display: true, text: 'Average Rating (Stars)' }
                },
                x: {
                    title: { display: true, text: 'LLM Models' }
                }
            },
            plugins: {
                legend: { display: false },
                tooltip: {
                    callbacks: {
                        afterLabel: function(context) {
                            const item = sortedData[context.dataIndex];
                            return [`Ratings: ${item.rating_count}`, `Satisfaction: ${item.satisfaction_rate}%`];
                        }
                    }
                }
            }
        }
    });
}

function updateSearchEngineChart(searchEngineRatings) {
    const ctx = document.getElementById('search-engine-ratings-chart').getContext('2d');
    if (searchEngineChart) searchEngineChart.destroy();

    const sortedData = searchEngineRatings.sort((a, b) => b.avg_rating - a.avg_rating).slice(0, 10);

    searchEngineChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: sortedData.map(item => item.search_engine || 'Unknown'),
            datasets: [{
                label: 'Average Rating',
                data: sortedData.map(item => item.avg_rating),
                backgroundColor: 'rgba(255, 99, 132, 0.8)',
                borderColor: 'rgba(255, 99, 132, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    max: 5,
                    title: { display: true, text: 'Average Rating (Stars)' }
                },
                x: {
                    title: { display: true, text: 'Search Engines' }
                }
            },
            plugins: {
                legend: { display: false },
                tooltip: {
                    callbacks: {
                        afterLabel: function(context) {
                            const item = sortedData[context.dataIndex];
                            return [`Ratings: ${item.rating_count}`, `Satisfaction: ${item.satisfaction_rate}%`];
                        }
                    }
                }
            }
        }
    });
}

function updateQualityRadar(dims) {
    const canvas = document.getElementById('quality-radar-chart');
    const emptyState = document.getElementById('quality-empty-state');

    if (!dims.dimension_count || dims.dimension_count === 0) {
        canvas.style.display = 'none';
        emptyState.style.display = 'block';
        return;
    }

    canvas.style.display = 'block';
    emptyState.style.display = 'none';

    const ctx = canvas.getContext('2d');
    if (qualityRadarChart) qualityRadarChart.destroy();

    qualityRadarChart = new Chart(ctx, {
        type: 'radar',
        data: {
            labels: ['Accuracy', 'Completeness', 'Relevance', 'Readability'],
            datasets: [{
                label: 'Quality Score',
                data: [dims.avg_accuracy, dims.avg_completeness, dims.avg_relevance, dims.avg_readability],
                backgroundColor: 'rgba(153, 102, 255, 0.2)',
                borderColor: 'rgba(153, 102, 255, 1)',
                borderWidth: 2,
                pointBackgroundColor: 'rgba(153, 102, 255, 1)',
                pointRadius: 5,
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                r: {
                    beginAtZero: true,
                    max: 5,
                    ticks: { stepSize: 1 },
                    pointLabels: { font: { size: 12 } }
                }
            },
            plugins: {
                legend: { display: false },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const counts = dims.dimension_counts || {};
                            const perAxis = [
                                counts.accuracy,
                                counts.completeness,
                                counts.relevance,
                                counts.readability,
                            ][context.dataIndex];
                            const n = perAxis !== undefined ? perAxis : dims.dimension_count;
                            const score = context.parsed.r;
                            if (score === null || score === undefined) {
                                return `${context.label}: no ratings`;
                            }
                            return `${context.label}: ${score.toFixed(1)}/5 (${n} ratings)`;
                        }
                    }
                }
            }
        }
    });
}

function updateRecentRatings(recentRatings) {
    const container = document.getElementById('recent-ratings');
    container.innerHTML = '';

    if (recentRatings.length === 0) {
        container.innerHTML = '<div style="text-align: center; padding: 20px; color: var(--text-muted);">No recent ratings found</div>';
        return;
    }

    recentRatings.forEach(rating => {
        const item = document.createElement('div');
        item.className = 'ldr-rating-item';

        const stars = '⭐'.repeat(rating.rating);
        const date = new Date(rating.created_at).toLocaleDateString();

        item.innerHTML = `
            <div class="ldr-rating-details">
                <div class="ldr-rating-query">
                    <a href="/results/${encodeURIComponent(rating.research_id)}" class="ldr-rating-link">
                        ${escapeHtml(rating.query)}
                    </a>
                </div>
                <div class="ldr-rating-meta">
                    ${escapeHtml(rating.llm_model)} • ${escapeHtml(rating.mode)} • ${date}
                </div>
            </div>
            <div class="ldr-rating-score">
                <span class="ldr-star-rating">${stars}</span>
                <span>${rating.rating}/5</span>
            </div>
        `;

        container.appendChild(item);
    });
}

function updateRecentFeedback(feedbackItems) {
    const container = document.getElementById('recent-feedback');
    container.innerHTML = '';

    if (!feedbackItems || feedbackItems.length === 0) {
        container.innerHTML = '<div class="ldr-empty-state">No written feedback yet. Feedback will appear here once you add comments to your ratings.</div>';
        return;
    }

    feedbackItems.forEach(item => {
        const el = document.createElement('div');
        el.className = 'ldr-feedback-item';

        const stars = '⭐'.repeat(item.rating);
        const date = new Date(item.created_at).toLocaleDateString();
        const researchLink = item.research_id
            ? `<a href="/results/${encodeURIComponent(item.research_id)}" class="ldr-rating-link">View research <span aria-hidden="true">→</span></a>`
            : '';

        el.innerHTML = `
            <div class="ldr-feedback-text">${escapeHtml(item.feedback)}</div>
            <div class="ldr-feedback-meta">
                <span class="ldr-star-rating">${stars}</span>
                <span>${item.rating}/5</span>
                <span>• ${date}</span>
                ${researchLink}
            </div>
        `;

        container.appendChild(el);
    });
}
</script>
{% endblock %}
