<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student Progress Dashboard</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
        }

        .header {
            background: white;
            padding: 30px;
            border-radius: 20px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
        }

        .header-left h1 {
            color: #667eea;
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header-left p {
            color: #666;
            font-size: 1.1em;
        }

        .logout-btn {
            padding: 12px 30px;
            background: #ef4444;
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .logout-btn:hover {
            background: #dc2626;
            transform: scale(1.05);
        }

        .loading {
            text-align: center;
            padding: 50px;
            color: white;
            font-size: 1.5em;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
        }

        .stat-card h3 {
            color: #666;
            font-size: 0.9em;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 10px;
        }

        .stat-card .value {
            font-size: 2.5em;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 5px;
        }

        .stat-card .label {
            color: #999;
            font-size: 0.9em;
        }

        .accuracy {
            color: #10b981 !important;
        }

        .score {
            color: #f59e0b !important;
        }

        .charts-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 30px;
            margin-bottom: 30px;
        }

        .chart-card {
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
        }

        .chart-card h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 1.3em;
        }

        .period-selector {
            background: white;
            padding: 20px;
            border-radius: 15px;
            margin-bottom: 30px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
        }

        .period-buttons {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .period-btn {
            padding: 12px 24px;
            border: 2px solid #667eea;
            background: white;
            color: #667eea;
            border-radius: 25px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .period-btn:hover {
            background: #667eea;
            color: white;
        }

        .period-btn.active {
            background: #667eea;
            color: white;
        }

        .error {
            background: #fee;
            color: #c33;
            padding: 20px;
            border-radius: 10px;
            margin: 20px 0;
            border-left: 4px solid #c33;
        }

        canvas {
            max-height: 300px;
        }

        @media (max-width: 768px) {
            .charts-grid {
                grid-template-columns: 1fr;
            }
            
            .header-left h1 {
                font-size: 1.8em;
            }

            .header {
                flex-direction: column;
                gap: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="header-left">
                <h1>📊 Learning Progress Dashboard</h1>
                <p id="userInfo">Welcome back!</p>
            </div>
            <button class="logout-btn" onclick="logout()">Go Back</button>
        </div>

        <div id="loading" class="loading">
            Loading your progress...
        </div>

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

        <div id="dashboard" style="display: none;">
            <!-- Overall Stats -->
            <div class="stats-grid">
                <div class="stat-card">
                    <h3>Total Questions</h3>
                    <div class="value" id="totalQuestions">0</div>
                    <div class="label">All time</div>
                </div>
                <div class="stat-card">
                    <h3>Answered</h3>
                    <div class="value" id="answeredQuestions">0</div>
                    <div class="label">Completed</div>
                </div>
                <div class="stat-card">
                    <h3>Accuracy</h3>
                    <div class="value accuracy" id="accuracy">0%</div>
                    <div class="label">Success rate</div>
                </div>
                <div class="stat-card">
                    <h3>Total Score</h3>
                    <div class="value score" id="totalScore">0</div>
                    <div class="label">Points earned</div>
                </div>
            </div>

            <!-- Period Selector -->
            <div class="period-selector">
                <div class="period-buttons">
                    <button class="period-btn active" onclick="changePeriod('today')">Today</button>
                    <button class="period-btn" onclick="changePeriod('this_week')">This Week</button>
                    <button class="period-btn" onclick="changePeriod('this_month')">This Month</button>
                    <button class="period-btn" onclick="changePeriod('this_year')">This Year</button>
                    <button class="period-btn" onclick="changePeriod('overall')">All Time</button>
                </div>
            </div>

            <!-- Charts -->
            <div class="charts-grid">
                <div class="chart-card">
                    <h2>Questions Overview</h2>
                    <canvas id="questionsChart"></canvas>
                </div>
                <div class="chart-card">
                    <h2>Accuracy Breakdown</h2>
                    <canvas id="accuracyChart"></canvas>
                </div>
            </div>

            <div class="charts-grid">
                <div class="chart-card">
                    <h2>Progress Comparison</h2>
                    <canvas id="periodComparisonChart"></canvas>
                </div>
                <div class="chart-card">
                    <h2>Performance Metrics</h2>
                    <canvas id="performanceChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <script>
        let progressData = null;
        let currentPeriod = 'today';
        let charts = {};

        // Get access token from Jinja2 template or fallback methods
        function getAccessToken() {
            // Try to get token from Jinja2 template variable
            const templateToken = "{{ token }}";
            if (templateToken && templateToken !== "{{ token }}") {
                return templateToken;
            }

            // Fallback: Try URL parameter
            const urlParams = new URLSearchParams(window.location.search);
            const urlToken = urlParams.get('token');
            if (urlToken) {
                return urlToken;
            }

            // Fallback: Try localStorage
            const storageToken = localStorage.getItem('accessToken');
            if (storageToken) {
                return storageToken;
            }

            showError('No access token found. Please login again.');
            setTimeout(() => {
                window.location.href = '/';
            }, 2000);
            return null;
        }

        // Fetch progress data
        async function fetchProgress() {
            const token = getAccessToken();
            if (!token) return;

            // Save token to localStorage
            localStorage.setItem('accessToken', token);

            try {
                const response = await fetch('https://lm.warals.codetorise.com/progress/user/', {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (!response.ok) {
                    if (response.status === 401) {
                        throw new Error('Authentication failed. Please login again.');
                    }
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                progressData = await response.json();
                displayProgress();
            } catch (error) {
                showError(`Failed to load progress: ${error.message}`);
                setTimeout(() => {
                    window.location.href = '/';
                }, 3000);
            }
        }

        function showError(message) {
            document.getElementById('loading').style.display = 'none';
            document.getElementById('error').style.display = 'block';
            document.getElementById('error').className = 'error';
            document.getElementById('error').textContent = message;
        }

        function displayProgress() {
            document.getElementById('loading').style.display = 'none';
            document.getElementById('dashboard').style.display = 'block';

            // Update user info
            document.getElementById('userInfo').textContent = 
                `Welcome back, ${progressData.username}! 🎓`;

            // Update overall stats
            updateStats(progressData.overall);

            // Create charts
            createCharts();
            
            // Update charts with today's data
            updateCharts('today');
        }

        function updateStats(data) {
            document.getElementById('totalQuestions').textContent = data.total_questions;
            document.getElementById('answeredQuestions').textContent = data.answered_questions;
            document.getElementById('accuracy').textContent = data.accuracy_percentage + '%';
            document.getElementById('totalScore').textContent = data.total_score;
        }

        function changePeriod(period) {
            currentPeriod = period;
            
            // Update button states
            document.querySelectorAll('.period-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            event.target.classList.add('active');

            // Update charts
            updateCharts(period);
        }

        function logout() {
            // Clear stored token
            localStorage.removeItem('accessToken');
            
            // Redirect to home/login page
            window.location.href = '/';
        }

        function createCharts() {
            // Questions Overview Chart
            const questionsCtx = document.getElementById('questionsChart').getContext('2d');
            charts.questions = new Chart(questionsCtx, {
                type: 'doughnut',
                data: {
                    labels: ['Answered', 'Unanswered'],
                    datasets: [{
                        data: [0, 0],
                        backgroundColor: ['#10b981', '#e5e7eb'],
                        borderWidth: 0
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });

            // Accuracy Chart
            const accuracyCtx = document.getElementById('accuracyChart').getContext('2d');
            charts.accuracy = new Chart(accuracyCtx, {
                type: 'pie',
                data: {
                    labels: ['Correct', 'Incorrect'],
                    datasets: [{
                        data: [0, 0],
                        backgroundColor: ['#10b981', '#ef4444'],
                        borderWidth: 0
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });

            // Period Comparison Chart
            const comparisonCtx = document.getElementById('periodComparisonChart').getContext('2d');
            charts.comparison = new Chart(comparisonCtx, {
                type: 'bar',
                data: {
                    labels: ['Today', 'This Week', 'This Month', 'This Year', 'All Time'],
                    datasets: [{
                        label: 'Questions Answered',
                        data: [0, 0, 0, 0, 0],
                        backgroundColor: '#667eea',
                        borderRadius: 8
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });

            // Performance Chart
            const performanceCtx = document.getElementById('performanceChart').getContext('2d');
            charts.performance = new Chart(performanceCtx, {
                type: 'radar',
                data: {
                    labels: ['Today', 'Week', 'Month', 'Year', 'Overall'],
                    datasets: [{
                        label: 'Accuracy %',
                        data: [0, 0, 0, 0, 0],
                        backgroundColor: 'rgba(102, 126, 234, 0.2)',
                        borderColor: '#667eea',
                        borderWidth: 2,
                        pointBackgroundColor: '#667eea'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    scales: {
                        r: {
                            beginAtZero: true,
                            max: 100
                        }
                    }
                }
            });
        }

        function updateCharts(period) {
            const data = progressData[period];

            // Update questions chart
            charts.questions.data.datasets[0].data = [
                data.answered_questions,
                data.unanswered_questions
            ];
            charts.questions.update();

            // Update accuracy chart
            charts.accuracy.data.datasets[0].data = [
                data.correct_answers,
                data.incorrect_answers
            ];
            charts.accuracy.update();

            // Update comparison chart
            charts.comparison.data.datasets[0].data = [
                progressData.today.answered_questions,
                progressData.this_week.answered_questions,
                progressData.this_month.answered_questions,
                progressData.this_year.answered_questions,
                progressData.overall.answered_questions
            ];
            charts.comparison.update();

            // Update performance chart
            charts.performance.data.datasets[0].data = [
                progressData.today.accuracy_percentage,
                progressData.this_week.accuracy_percentage,
                progressData.this_month.accuracy_percentage,
                progressData.this_year.accuracy_percentage,
                progressData.overall.accuracy_percentage
            ];
            charts.performance.update();
        }

        // Load data on page load
        window.addEventListener('load', fetchProgress);
    </script>
</body>
</html>