import React, { useState, useEffect } from 'react'; import { Link } from 'react-router-dom'; import { useApp } from '../store/AppContext'; import Card from '../components/ui/Card'; import Button from '../components/ui/Button'; import Tag from '../components/ui/Tag'; import * as db from '../lib/db'; import { getAssignedTopic } from '../lib/learningService'; const Dashboard = () => { const { state } = useApp(); const { currentUser, weekNumber } = state; const [dashData, setDashData] = useState({ topic: null, learnDone: false, testResult: null, top3: [], myRank: 0, myPoints: 0, activity: [], }); useEffect(() => { if (!currentUser) return; const load = async () => { const [topic, learnDone, testResult, allUsers, leaderboard] = await Promise.all([ getAssignedTopic(currentUser.id, weekNumber), db.getLearnDone(currentUser.id, weekNumber), db.getQuizResult(currentUser.id, weekNumber), db.getTeamMembers(), db.getLeaderboard(), ]); const nonAdminIds = allUsers.filter(u => u.role !== 'admin').map(u => u.id); const filtered = leaderboard.filter(u => nonAdminIds.includes(u.user_id)); const top3 = filtered.slice(0, 3); const myRank = filtered.findIndex(u => u.user_id === currentUser.id) + 1; const myPoints = filtered.find(u => u.user_id === currentUser.id)?.points || 0; const activity = []; for (let w = weekNumber; w >= Math.max(1, weekNumber - 3); w--) { const [pastLearn, pastTest, pastTopic] = await Promise.all([ db.getLearnDone(currentUser.id, w), db.getQuizResult(currentUser.id, w), getAssignedTopic(currentUser.id, w), ]); if (pastTest) activity.push({ type: 'test', week: w, topic: pastTopic?.label, score: pastTest.percentage, points: pastTest.points_earned }); if (pastLearn) activity.push({ type: 'learn', week: w, topic: pastTopic?.label }); } setDashData({ topic, learnDone, testResult, top3, myRank, myPoints, activity }); }; load(); }, [currentUser, weekNumber]); const { topic, learnDone, testResult, top3, myRank, myPoints, activity } = dashData; return (
Here is your overview for week {weekNumber}.
Your topic this week:
Weekly test — 10 questions
{act.type === 'test' ? 'Test completed' : 'Learning session'}: {act.topic}
Week {act.week} {act.type === 'test' && `· Score: ${act.score}%`}