window.onload = async function () { const token = localStorage.getItem('auth_token'); if (token) { try { const decoded = JSON.parse(atob(token.split('.')[1])); // Manually decoding JWT const userName = decoded.name; document.getElementById('user-name').textContent = userName; // Verify JWT expiration const currentTime = Math.floor(Date.now() / 1000); if (decoded.exp && decoded.exp < currentTime) { console.warn("Token is expired"); localStorage.removeItem('auth_token'); window.location.href = '/'; } } catch (error) { console.error("Error decoding token:", error); localStorage.removeItem('auth_token'); window.location.href = '/'; } } else { window.location.href = '/'; } try { const statsRes = await fetch('/api/users/stats', { method: 'GET', headers: { 'Authorization': `Bearer ${token}` } }); if (!statsRes.ok) { throw new Error('Failed to fetch user stats'); } const stats = await statsRes.json(); const userTableBody = document.getElementById('user-table-body'); const table = document.querySelector('.user-table'); const spinner = document.getElementById('loading-spinner'); // Ensure watchedRatio is treated as a number and sort in descending order stats.sort((a, b) => parseFloat(b.watchedRatio) - parseFloat(a.watchedRatio)); // Clear previous rows to prevent duplication userTableBody.innerHTML = ''; stats.forEach(userStat => { const userRow = document.createElement('tr'); userRow.innerHTML = `