Files
pdga-rating/index.html
T
Samuel Enocsson 10d1f88a58 Add standard deviation display for predicted ratings
- Calculate and store standard deviation during rating prediction
- Add std_dev column to players database table
- Display standard deviation tooltip on hover over predicted rating
- Show rating range (±std_dev) tooltip on hover over current rating
- Update tooltips dynamically when ratings are refreshed

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-14 17:48:21 +02:00

1478 lines
62 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PDGA Ratings</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f5f5f5;
}
@media (max-width: 768px) {
body {
padding: 10px;
}
}
.container {
max-width: 800px;
margin: 0 auto;
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
overflow-x: auto;
}
@media (max-width: 768px) {
.container {
padding: 15px;
border-radius: 0;
box-shadow: none;
}
}
h1 {
color: #333;
text-align: center;
margin-bottom: 30px;
}
@media (max-width: 768px) {
h1 {
font-size: 24px;
margin-bottom: 20px;
}
}
.loading {
text-align: center;
padding: 20px;
font-size: 18px;
color: #666;
}
.progress-container {
width: 100%;
background-color: #f0f0f0;
border-radius: 10px;
padding: 3px;
margin: 20px 0;
}
.progress-bar {
width: 0%;
height: 30px;
background-color: #007bff;
border-radius: 8px;
text-align: center;
line-height: 30px;
color: white;
font-weight: bold;
transition: width 0.3s ease;
}
.progress-text {
text-align: center;
margin: 10px 0;
font-size: 16px;
color: #666;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
font-size: 14px;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #ddd;
}
@media (max-width: 768px) {
table {
font-size: 12px;
}
th, td {
padding: 8px 4px;
}
/* Hide less important columns on mobile */
.mobile-hide {
display: none;
}
/* Show mobile-only elements only on mobile */
.mobile-only {
display: block;
}
/* Make player names more prominent on mobile */
.player-name {
font-weight: bold;
}
}
/* Hide mobile-only elements on desktop */
.mobile-only {
display: none;
}
@media (max-width: 768px) {
/* Adjust colspan for mobile - fewer visible columns */
.expanded-cell {
/* Mobile shows: Player Name, Rating, Action = 3 columns */
/* But we need to account for the fact that mobile-hide columns still exist in DOM */
}
/* Better mobile chart sizing */
.chart-container {
height: 250px;
margin: 5px 0;
}
.chart-title {
font-size: 14px;
}
}
th {
background-color: #f8f9fa;
font-weight: bold;
color: #495057;
}
tr:hover {
background-color: #f5f5f5;
}
.expandable-row {
cursor: pointer;
}
.expandable-row:hover {
background-color: #e3f2fd;
}
.expanded-content {
display: none;
background-color: #f8f9fa;
border-top: 2px solid #007bff;
}
.expanded-content td {
padding: 20px;
}
.chart-container {
width: 100%;
height: 300px;
margin: 10px 0;
border: 1px solid #ddd;
border-radius: 4px;
background: white;
}
.chart-title {
text-align: center;
font-weight: bold;
margin-bottom: 10px;
color: #333;
}
.loading-chart {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
color: #666;
}
.chart-tooltip {
position: fixed;
background-color: rgba(0, 0, 0, 0.9);
color: white;
padding: 8px 12px;
border-radius: 4px;
font-size: 12px;
pointer-events: none;
z-index: 10000;
display: none;
white-space: nowrap;
box-shadow: 0 2px 8px rgba(0,0,0,0.3);
border: 1px solid rgba(255,255,255,0.2);
}
.rating {
font-weight: bold;
color: #007bff;
}
.std-dev-tooltip {
position: absolute;
background-color: rgba(0, 0, 0, 0.9);
color: white;
padding: 8px 12px;
border-radius: 4px;
font-size: 12px;
pointer-events: none;
z-index: 10000;
display: none;
white-space: nowrap;
box-shadow: 0 2px 8px rgba(0,0,0,0.3);
border: 1px solid rgba(255,255,255,0.2);
font-weight: normal;
}
.predicted-value {
position: relative;
display: inline-block;
}
.pdga-number {
color: #6c757d;
font-size: 14px;
}
.difference {
font-weight: bold;
}
.positive {
color: #28a745;
}
.negative {
color: #dc3545;
}
.neutral {
color: #6c757d;
}
.rating-change {
font-weight: bold;
font-size: 14px;
}
a {
color: #007bff;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.refresh-icon {
cursor: pointer;
opacity: 0.6;
margin-left: 8px;
font-size: 13px;
color: #6c757d;
transition: all 0.2s ease;
padding: 2px;
border-radius: 3px;
}
.refresh-icon:hover {
opacity: 1;
color: #007bff;
background-color: rgba(0, 123, 255, 0.1);
transform: scale(1.1);
}
.refresh-icon.spinning {
animation: spin 1s linear infinite;
color: #007bff;
opacity: 1;
background-color: rgba(0, 123, 255, 0.1);
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.refresh-section {
display: inline-flex;
align-items: center;
}
.debug-icon:hover {
opacity: 1 !important;
color: #007bff !important;
transform: scale(1.1);
}
.debug-modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 10001;
display: none;
justify-content: center;
align-items: center;
}
.debug-content {
background: white;
border-radius: 8px;
padding: 20px;
max-width: 600px;
max-height: 80vh;
overflow-y: auto;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}
.debug-header {
font-weight: bold;
font-size: 18px;
margin-bottom: 15px;
color: #333;
border-bottom: 2px solid #007bff;
padding-bottom: 10px;
}
.debug-log {
font-family: 'Courier New', monospace;
background-color: #f8f9fa;
border: 1px solid #e9ecef;
border-radius: 4px;
padding: 15px;
font-size: 12px;
line-height: 1.4;
white-space: pre-line;
color: #495057;
}
.debug-close {
position: absolute;
top: 10px;
right: 15px;
font-size: 24px;
color: #999;
cursor: pointer;
background: none;
border: none;
}
.debug-close:hover {
color: #333;
}
.add-player-section {
background-color: #f8f9fa;
border: 2px solid #007bff;
border-radius: 8px;
padding: 20px;
margin-bottom: 30px;
text-align: center;
}
.add-player-section h3 {
margin-top: 0;
margin-bottom: 15px;
color: #333;
font-size: 18px;
}
.add-player-form {
display: flex;
justify-content: center;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.pdga-input {
padding: 10px 15px;
font-size: 16px;
border: 2px solid #ddd;
border-radius: 4px;
outline: none;
width: 250px;
transition: border-color 0.2s;
}
.pdga-input:focus {
border-color: #007bff;
}
.btn-add {
background-color: #28a745;
}
.btn-add:hover {
background-color: #218838;
}
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 10001;
display: none;
justify-content: center;
align-items: center;
}
.modal-content {
background: white;
border-radius: 8px;
padding: 0;
max-width: 500px;
width: 90%;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
position: relative;
}
.modal-header {
font-weight: bold;
font-size: 20px;
padding: 20px;
color: #333;
border-bottom: 2px solid #007bff;
}
.modal-body {
padding: 20px;
font-size: 16px;
color: #495057;
line-height: 1.6;
}
.modal-footer {
padding: 15px 20px;
border-top: 1px solid #e9ecef;
display: flex;
justify-content: flex-end;
gap: 10px;
}
.modal-close {
position: absolute;
top: 10px;
right: 15px;
font-size: 28px;
color: #999;
cursor: pointer;
background: none;
border: none;
line-height: 1;
}
.modal-close:hover {
color: #333;
}
.btn-cancel {
background-color: #6c757d;
}
.btn-cancel:hover {
background-color: #5a6268;
}
.btn-confirm {
background-color: #28a745;
}
.btn-confirm:hover {
background-color: #218838;
}
@media (max-width: 768px) {
.add-player-section {
padding: 15px;
}
.add-player-form {
flex-direction: column;
}
.pdga-input {
width: 100%;
}
}
</style>
</head>
<body>
<div class="container">
<h1>PDGA Player Ratings</h1>
<div style="text-align: center; margin-bottom: 20px;">
<a href="/" style="margin: 0 15px; color: #333; text-decoration: none; font-weight: bold;">Player Ratings</a>
<a href="/courses.html" style="margin: 0 15px; color: #007bff; text-decoration: none; font-weight: bold;">Courses</a>
</div>
<!-- Add Player Section -->
<div class="add-player-section">
<h3>Add Yourself to Tracked Players</h3>
<div class="add-player-form">
<input
type="number"
id="pdga-number-input"
class="pdga-input"
placeholder="Enter your PDGA number"
min="1"
/>
<button class="btn btn-add" onclick="searchAndAddPlayer()">
<i class="fas fa-user-plus"></i> Add Player
</button>
</div>
</div>
<div style="position: absolute; top: 10px; right: 15px;">
<a href="#" onclick="loadAllPlayers(); return false;" style="color: #007bff; font-size: 11px; text-decoration: none; margin-right: 10px;" title="Load all player data" id="load-all-btn">Load All</a>
<a href="#" onclick="clearCache(); return false;" style="color: #ccc; font-size: 12px; text-decoration: none; opacity: 0.3;" title="Clear cache"><i class="fas fa-cog"></i></a>
</div>
<div id="loading" class="loading" style="display: none;">Loading ratings...</div>
<div id="progress-section" style="display: none;">
<div class="progress-container">
<div id="progress-bar" class="progress-bar">0%</div>
</div>
<div id="progress-text" class="progress-text">Preparing to load ratings...</div>
</div>
<div id="ratings-table"></div>
</div>
<!-- Debug Modal -->
<div id="debug-modal" class="debug-modal" onclick="closeDebugModal(event)">
<div class="debug-content" onclick="event.stopPropagation()">
<button class="debug-close" onclick="closeDebugModal()">&times;</button>
<div class="debug-header" id="debug-header">Prediction Calculation Details</div>
<div class="debug-log" id="debug-log">Loading...</div>
</div>
</div>
<!-- Add Player Confirmation Modal -->
<div id="add-player-modal" class="modal" onclick="closeAddPlayerModal(event)">
<div class="modal-content" onclick="event.stopPropagation()">
<button class="modal-close" onclick="closeAddPlayerModal()">&times;</button>
<div class="modal-header" id="add-player-modal-header">Confirm Player</div>
<div class="modal-body" id="add-player-modal-body">Loading...</div>
<div class="modal-footer" id="add-player-modal-footer">
<button class="btn btn-cancel" onclick="closeAddPlayerModal()">Cancel</button>
<button class="btn btn-confirm" id="confirm-add-btn" onclick="confirmAddPlayer()">Add Player</button>
</div>
</div>
</div>
<script>
function fetchRatingsWithProgress() {
const progressSection = document.getElementById('progress-section');
const progressBar = document.getElementById('progress-bar');
const progressText = document.getElementById('progress-text');
const tableDiv = document.getElementById('ratings-table');
progressSection.style.display = 'block';
tableDiv.innerHTML = '';
const eventSource = new EventSource('/api/ratings/progress');
eventSource.onmessage = function(event) {
const data = JSON.parse(event.data);
if (data.status === 'loading') {
const percentage = Math.round((data.current / data.total) * 100);
progressBar.style.width = `${percentage}%`;
progressBar.textContent = `${percentage}%`;
progressText.textContent = `Loading player ${data.current}/${data.total}: PDGA #${data.pdgaNumber}`;
} else if (data.status === 'completed') {
const percentage = Math.round((data.current / data.total) * 100);
progressBar.style.width = `${percentage}%`;
progressBar.textContent = `${percentage}%`;
progressText.textContent = `Loaded ${data.name} (${data.current}/${data.total})`;
} else if (data.status === 'error') {
const percentage = Math.round((data.current / data.total) * 100);
progressBar.style.width = `${percentage}%`;
progressBar.textContent = `${percentage}%`;
progressText.textContent = `Error loading PDGA #${data.pdgaNumber} (${data.current}/${data.total})`;
} else if (data.status === 'complete') {
progressSection.style.display = 'none';
displayRatings(data.ratings);
eventSource.close();
} else if (data.status === 'error') {
progressSection.style.display = 'none';
tableDiv.innerHTML = '<p>Error loading ratings. Please try again.</p>';
eventSource.close();
}
};
eventSource.onerror = function() {
progressSection.style.display = 'none';
tableDiv.innerHTML = '<p>Connection error. Please refresh the page.</p>';
eventSource.close();
};
}
function displayRatings(ratings) {
const tableDiv = document.getElementById('ratings-table');
if (ratings.length === 0) {
tableDiv.innerHTML = '<p>No ratings found.</p>';
return;
}
let tableHTML = `
<table>
<thead>
<tr>
<th class="mobile-hide">Rank</th>
<th>Player Name</th>
<th class="mobile-hide">PDGA #</th>
<th>Rating</th>
<th class="mobile-hide">Change</th>
<th class="mobile-hide">Predicted</th>
</tr>
</thead>
<tbody>
`;
ratings.forEach((player, index) => {
const difference = player.predictedRating && player.rating ?
player.predictedRating - player.rating : 0;
const diffText = difference > 0 ? `+${difference}` : difference.toString();
const diffClass = difference > 0 ? 'positive' : difference < 0 ? 'negative' : 'neutral';
const ratingChangeText = player.ratingChange ?
(player.ratingChange > 0 ? `+${player.ratingChange}` : player.ratingChange.toString()) : 'N/A';
const ratingChangeClass = player.ratingChange > 0 ? 'positive' :
player.ratingChange < 0 ? 'negative' : 'neutral';
tableHTML += `
<tr id="row-${player.pdgaNumber}" class="expandable-row" onclick="togglePlayerHistory(${player.pdgaNumber})">
<td class="mobile-hide">${index + 1}</td>
<td class="player-name">
<a href="https://www.pdga.com/player/${player.pdgaNumber}" target="_blank" onclick="event.stopPropagation()">${player.name}</a>
<div class="mobile-only pdga-number" style="font-size: 11px; color: #999; margin-top: 2px;">PDGA #${player.pdgaNumber}</div>
</td>
<td class="pdga-number mobile-hide">#${player.pdgaNumber}</td>
<td class="rating">
<div class="refresh-section">
<span class="rating-value" data-rating="${player.rating || ''}" data-stddev="${player.stdDev || ''}" data-pdga="${player.pdgaNumber}" style="cursor: help;">${player.rating || '<span style="color: #999; font-style: italic;">Click refresh</span>'}</span>
<i class="fas fa-sync-alt refresh-icon" onclick="refreshPlayer(${player.pdgaNumber})" title="Refresh player data"></i>
</div>
<div class="mobile-only rating-change ${ratingChangeClass}" style="font-size: 11px; margin-top: 2px;">${ratingChangeText}</div>
<div class="std-dev-tooltip" id="tooltip-rating-${player.pdgaNumber}"></div>
</td>
<td class="rating-change ${ratingChangeClass} mobile-hide">${ratingChangeText}</td>
<td class="predicted-rating mobile-hide" id="predicted-${player.pdgaNumber}">
<div class="refresh-section">
<span class="predicted-value" data-stddev="${player.stdDev || ''}" data-pdga="${player.pdgaNumber}" style="cursor: help;">${player.predictedRating || 'N/A'}</span>
<i class="fas fa-question-circle debug-icon" onclick="showDebugInfo(${player.pdgaNumber})" title="Show calculation details" style="margin-left: 5px; color: #6c757d; cursor: pointer; opacity: 0.6;"></i>
<i class="fas fa-sync-alt refresh-icon" onclick="refreshRoundHistory(${player.pdgaNumber})" title="Refresh prediction data"></i>
</div>
<div class="std-dev-tooltip" id="tooltip-stddev-${player.pdgaNumber}"></div>
</td>
</tr>
<tr id="history-${player.pdgaNumber}" class="expanded-content">
<td colspan="6" class="expanded-cell">
<div class="chart-title">
<div class="refresh-section">
Rating History for ${player.name}
<i class="fas fa-sync-alt refresh-icon" onclick="refreshRatingHistory(${player.pdgaNumber})" title="Refresh rating history"></i>
</div>
</div>
<div class="chart-container" id="chart-${player.pdgaNumber}" style="position: relative;">
<div class="loading-chart">Click to load rating history...</div>
</div>
<div class="chart-tooltip" id="tooltip-${player.pdgaNumber}"></div>
</td>
</tr>
`;
});
tableHTML += `
</tbody>
</table>
`;
tableDiv.innerHTML = tableHTML;
// Add hover listeners for predicted rating standard deviation tooltips
document.querySelectorAll('.predicted-value').forEach(span => {
const pdgaNumber = span.dataset.pdga;
const stdDev = span.dataset.stddev;
const tooltip = document.getElementById(`tooltip-stddev-${pdgaNumber}`);
if (stdDev && tooltip) {
span.addEventListener('mouseenter', (e) => {
tooltip.textContent = `Standard Deviation: ±${stdDev}`;
tooltip.style.display = 'block';
tooltip.style.left = `${e.clientX + 15}px`;
tooltip.style.top = `${e.clientY - 35}px`;
});
span.addEventListener('mousemove', (e) => {
tooltip.style.left = `${e.clientX + 15}px`;
tooltip.style.top = `${e.clientY - 35}px`;
});
span.addEventListener('mouseleave', () => {
tooltip.style.display = 'none';
});
}
});
// Add hover listeners for current rating range tooltips
document.querySelectorAll('.rating-value').forEach(span => {
const pdgaNumber = span.dataset.pdga;
const rating = parseInt(span.dataset.rating);
const stdDev = parseInt(span.dataset.stddev);
const tooltip = document.getElementById(`tooltip-rating-${pdgaNumber}`);
if (rating && stdDev && tooltip) {
const minRating = rating - stdDev;
const maxRating = rating + stdDev;
span.addEventListener('mouseenter', (e) => {
tooltip.textContent = `Rating Range: ${minRating} - ${maxRating}${stdDev})`;
tooltip.style.display = 'block';
tooltip.style.left = `${e.clientX + 15}px`;
tooltip.style.top = `${e.clientY - 35}px`;
});
span.addEventListener('mousemove', (e) => {
tooltip.style.left = `${e.clientX + 15}px`;
tooltip.style.top = `${e.clientY - 35}px`;
});
span.addEventListener('mouseleave', () => {
tooltip.style.display = 'none';
});
}
});
}
async function togglePlayerHistory(pdgaNumber) {
const historyRow = document.getElementById(`history-${pdgaNumber}`);
const chartContainer = document.getElementById(`chart-${pdgaNumber}`);
if (historyRow.style.display === 'table-row') {
historyRow.style.display = 'none';
return;
}
historyRow.style.display = 'table-row';
// Check if chart is already loaded
if (chartContainer.dataset.loaded === 'true') {
return;
}
// Show loading state
chartContainer.innerHTML = '<div class="loading-chart">Loading rating history...</div>';
try {
const response = await fetch(`/api/rating-history/${pdgaNumber}`);
const data = await response.json();
if (data.history && data.history.length > 0) {
createRatingChart(chartContainer, data.history);
chartContainer.dataset.loaded = 'true';
} else {
chartContainer.innerHTML = '<div class="loading-chart">No rating history available</div>';
}
} catch (error) {
console.error('Error loading rating history:', error);
chartContainer.innerHTML = '<div class="loading-chart">Error loading rating history</div>';
}
}
function createRatingChart(container, history) {
const width = container.clientWidth - 40;
const height = 250;
const margin = { top: 20, right: 30, bottom: 40, left: 60 };
const chartWidth = width - margin.left - margin.right;
const chartHeight = height - margin.top - margin.bottom;
// Get the tooltip element
const pdgaNumber = container.id.replace('chart-', '');
const tooltip = document.getElementById(`tooltip-${pdgaNumber}`);
// Calculate scales
const ratings = history.map(h => h.rating);
const minRating = Math.min(...ratings) - 10;
const maxRating = Math.max(...ratings) + 10;
const xStep = chartWidth / (history.length - 1 || 1);
const yScale = chartHeight / (maxRating - minRating);
// Create SVG
let svg = `<svg width="${width}" height="${height}" style="font-family: Arial, sans-serif;" id="svg-${pdgaNumber}">`;
// Background
svg += `<rect x="0" y="0" width="${width}" height="${height}" fill="white" stroke="#ddd"/>`;
// Chart area background
svg += `<rect x="${margin.left}" y="${margin.top}" width="${chartWidth}" height="${chartHeight}" fill="#f9f9f9" stroke="#ccc"/>`;
// Grid lines
for (let i = 0; i <= 5; i++) {
const y = margin.top + (i * chartHeight / 5);
const rating = Math.round(maxRating - (i * (maxRating - minRating) / 5));
svg += `<line x1="${margin.left}" y1="${y}" x2="${margin.left + chartWidth}" y2="${y}" stroke="#e0e0e0"/>`;
svg += `<text x="${margin.left - 5}" y="${y + 4}" text-anchor="end" font-size="12" fill="#666">${rating}</text>`;
}
// Data line
let pathData = '';
const points = [];
history.forEach((point, i) => {
const x = margin.left + (i * xStep);
const y = margin.top + ((maxRating - point.rating) * yScale);
points.push({ x, y, rating: point.rating, date: point.displayDate });
if (i === 0) {
pathData += `M ${x} ${y}`;
} else {
pathData += ` L ${x} ${y}`;
}
});
// Draw line
svg += `<path d="${pathData}" stroke="#007bff" stroke-width="2" fill="none"/>`;
// Draw points with enhanced hover areas
points.forEach((point, i) => {
svg += `<circle cx="${point.x}" cy="${point.y}" r="12" fill="transparent" class="hover-area" data-index="${i}" style="cursor: pointer;"/>`;
svg += `<circle cx="${point.x}" cy="${point.y}" r="4" fill="#007bff" stroke="white" stroke-width="2" class="data-point" data-index="${i}" style="pointer-events: none;"/>`;
});
// X-axis labels (show every few dates to avoid crowding)
const labelStep = Math.max(1, Math.floor(history.length / 6));
history.forEach((point, i) => {
if (i % labelStep === 0 || i === history.length - 1) {
const x = margin.left + (i * xStep);
const date = new Date(point.date).toLocaleDateString('en-US', { month: 'short', year: '2-digit' });
svg += `<text x="${x}" y="${height - 10}" text-anchor="middle" font-size="11" fill="#666">${date}</text>`;
}
});
// Y-axis label
svg += `<text x="20" y="${height/2}" text-anchor="middle" font-size="12" fill="#333" transform="rotate(-90, 20, ${height/2})">Rating</text>`;
svg += '</svg>';
container.innerHTML = svg;
// Add event listeners for tooltips after a small delay to ensure DOM is ready
setTimeout(() => {
const svgElement = document.getElementById(`svg-${pdgaNumber}`);
if (svgElement) {
const hoverAreas = svgElement.querySelectorAll('.hover-area');
const dataPoints = svgElement.querySelectorAll('.data-point');
let currentTooltip = null;
let tooltipTimeout = null;
hoverAreas.forEach((area, i) => {
area.addEventListener('mouseenter', (e) => {
// Clear any pending hide
if (tooltipTimeout) {
clearTimeout(tooltipTimeout);
tooltipTimeout = null;
}
// Hide current tooltip if different
if (currentTooltip !== null && currentTooltip !== i) {
dataPoints[currentTooltip].setAttribute('r', '4');
dataPoints[currentTooltip].setAttribute('fill', '#007bff');
}
currentTooltip = i;
const point = points[i];
tooltip.innerHTML = `<strong>${point.date}</strong><br>Rating: ${point.rating}`;
tooltip.style.display = 'block';
tooltip.style.left = `${e.clientX + 15}px`;
tooltip.style.top = `${e.clientY - 35}px`;
// Highlight the data point
dataPoints[i].setAttribute('r', '6');
dataPoints[i].setAttribute('fill', '#0056b3');
});
area.addEventListener('mousemove', (e) => {
if (currentTooltip === i) {
tooltip.style.left = `${e.clientX + 15}px`;
tooltip.style.top = `${e.clientY - 35}px`;
}
});
area.addEventListener('mouseleave', () => {
if (currentTooltip === i) {
// Delay hiding to prevent flicker
tooltipTimeout = setTimeout(() => {
tooltip.style.display = 'none';
dataPoints[i].setAttribute('r', '4');
dataPoints[i].setAttribute('fill', '#007bff');
currentTooltip = null;
}, 100);
}
});
});
}
}, 100);
}
async function clearCache() {
try {
const response = await fetch('/api/clear-cache', {
method: 'POST'
});
const data = await response.json();
if (data.success) {
alert(data.message);
// Optionally reload the page to reflect fresh data
if (confirm('Reload page to fetch fresh data?')) {
location.reload();
}
} else {
alert('Failed to clear cache');
}
} catch (error) {
console.error('Error clearing cache:', error);
alert('Error clearing cache');
}
}
// Refresh functions
async function refreshPlayer(pdgaNumber) {
const icon = document.querySelector(`#row-${pdgaNumber} .rating .refresh-icon`);
icon.classList.add('spinning');
try {
const response = await fetch(`/api/refresh-player/${pdgaNumber}`, {
method: 'POST'
});
const data = await response.json();
if (data.success) {
// Update the table with new data
const row = document.getElementById(`row-${pdgaNumber}`);
const ratingCell = row.querySelector('.rating');
const ratingChangeCell = row.querySelector('.rating-change');
// Update player name
const nameLink = row.querySelector('.player-name a');
nameLink.textContent = data.player.name;
const ratingChangeText = data.player.ratingChange ?
(data.player.ratingChange > 0 ? `+${data.player.ratingChange}` : data.player.ratingChange.toString()) : 'N/A';
const ratingChangeClass = data.player.ratingChange > 0 ? 'positive' :
data.player.ratingChange < 0 ? 'negative' : 'neutral';
// Update rating value
const ratingValue = ratingCell.querySelector('.rating-value');
if (ratingValue) {
ratingValue.textContent = data.player.rating || 'N/A';
ratingValue.dataset.rating = data.player.rating || '';
// stdDev stays the same - only updates with predicted rating refresh
// Re-attach tooltip listeners if we have both rating and stdDev
const stdDev = parseInt(ratingValue.dataset.stddev);
const rating = parseInt(data.player.rating);
const tooltip = document.getElementById(`tooltip-rating-${pdgaNumber}`);
if (rating && stdDev && tooltip) {
// Remove old listeners by cloning and replacing
const newRatingValue = ratingValue.cloneNode(true);
ratingValue.parentNode.replaceChild(newRatingValue, ratingValue);
const minRating = rating - stdDev;
const maxRating = rating + stdDev;
// Add new listeners
newRatingValue.addEventListener('mouseenter', (e) => {
tooltip.textContent = `Rating Range: ${minRating} - ${maxRating}${stdDev})`;
tooltip.style.display = 'block';
tooltip.style.left = `${e.clientX + 15}px`;
tooltip.style.top = `${e.clientY - 35}px`;
});
newRatingValue.addEventListener('mousemove', (e) => {
tooltip.style.left = `${e.clientX + 15}px`;
tooltip.style.top = `${e.clientY - 35}px`;
});
newRatingValue.addEventListener('mouseleave', () => {
tooltip.style.display = 'none';
});
}
}
if (ratingChangeCell) ratingChangeCell.textContent = ratingChangeText;
if (ratingChangeCell) ratingChangeCell.className = `rating-change ${ratingChangeClass} mobile-hide`;
// Update mobile rating change
const mobileChange = ratingCell.querySelector('.mobile-only.rating-change');
if (mobileChange) {
mobileChange.textContent = ratingChangeText;
mobileChange.className = `mobile-only rating-change ${ratingChangeClass}`;
}
}
} catch (error) {
console.error('Error refreshing player:', error);
alert('Failed to refresh player data');
} finally {
icon.classList.remove('spinning');
}
}
async function refreshRoundHistory(pdgaNumber) {
const icon = document.querySelector(`#predicted-${pdgaNumber} .refresh-icon`);
icon.classList.add('spinning');
try {
const response = await fetch(`/api/refresh-round-history/${pdgaNumber}`, {
method: 'POST'
});
const data = await response.json();
if (!response.ok) {
// Handle server error responses
throw new Error(JSON.stringify(data));
}
if (data.success) {
// Cache debug info for later use
if (data.debugLog) {
cachedDebugInfo[pdgaNumber] = data.debugLog;
}
// Update predicted rating if the element exists
const predictedCell = document.getElementById(`predicted-${pdgaNumber}`);
if (predictedCell) {
const predictedValue = predictedCell.querySelector('.predicted-value');
if (predictedValue) {
predictedValue.textContent = data.predictedRating || 'N/A';
// Update data attribute for tooltip
predictedValue.dataset.stddev = data.stdDev || '';
// Re-attach tooltip listeners
const tooltip = document.getElementById(`tooltip-stddev-${pdgaNumber}`);
if (data.stdDev && tooltip) {
// Remove old listeners by cloning and replacing
const newPredictedValue = predictedValue.cloneNode(true);
predictedValue.parentNode.replaceChild(newPredictedValue, predictedValue);
// Add new listeners
newPredictedValue.addEventListener('mouseenter', (e) => {
tooltip.textContent = `Standard Deviation: ±${data.stdDev}`;
tooltip.style.display = 'block';
tooltip.style.left = `${e.clientX + 15}px`;
tooltip.style.top = `${e.clientY - 35}px`;
});
newPredictedValue.addEventListener('mousemove', (e) => {
tooltip.style.left = `${e.clientX + 15}px`;
tooltip.style.top = `${e.clientY - 35}px`;
});
newPredictedValue.addEventListener('mouseleave', () => {
tooltip.style.display = 'none';
});
}
}
}
// Also update the rating value's stddev attribute and tooltip
const row = document.getElementById(`row-${pdgaNumber}`);
const ratingCell = row.querySelector('.rating');
const ratingValue = ratingCell.querySelector('.rating-value');
if (ratingValue && data.stdDev) {
ratingValue.dataset.stddev = data.stdDev;
// Re-attach rating tooltip listeners if we have both rating and stdDev
const rating = parseInt(ratingValue.dataset.rating);
const stdDev = parseInt(data.stdDev);
const ratingTooltip = document.getElementById(`tooltip-rating-${pdgaNumber}`);
if (rating && stdDev && ratingTooltip) {
// Remove old listeners by cloning and replacing
const newRatingValue = ratingValue.cloneNode(true);
ratingValue.parentNode.replaceChild(newRatingValue, ratingValue);
const minRating = rating - stdDev;
const maxRating = rating + stdDev;
// Add new listeners
newRatingValue.addEventListener('mouseenter', (e) => {
ratingTooltip.textContent = `Rating Range: ${minRating} - ${maxRating}${stdDev})`;
ratingTooltip.style.display = 'block';
ratingTooltip.style.left = `${e.clientX + 15}px`;
ratingTooltip.style.top = `${e.clientY - 35}px`;
});
newRatingValue.addEventListener('mousemove', (e) => {
ratingTooltip.style.left = `${e.clientX + 15}px`;
ratingTooltip.style.top = `${e.clientY - 35}px`;
});
newRatingValue.addEventListener('mouseleave', () => {
ratingTooltip.style.display = 'none';
});
}
}
// Update difference calculation if the element exists
const diffCell = document.getElementById(`diff-${pdgaNumber}`);
if (diffCell) {
const currentRatingElement = document.querySelector(`#row-${pdgaNumber} .rating .refresh-section`);
if (currentRatingElement && currentRatingElement.firstChild) {
const currentRatingText = currentRatingElement.firstChild.textContent;
const currentRating = parseInt(currentRatingText);
if (data.predictedRating && currentRating && !isNaN(currentRating)) {
const difference = data.predictedRating - currentRating;
const diffText = difference > 0 ? `+${difference}` : difference.toString();
const diffClass = difference > 0 ? 'positive' : difference < 0 ? 'negative' : 'neutral';
diffCell.className = `difference ${diffClass}`;
diffCell.textContent = diffText;
} else {
diffCell.innerHTML = '<span style="color: #999; font-style: italic;">Use refresh</span>';
}
}
}
}
} catch (error) {
console.error('Error refreshing round history:', error);
// Try to get detailed error information
let errorMessage = 'Failed to refresh prediction data';
let errorDetails = '';
try {
// If error message is JSON, parse it
const errorData = JSON.parse(error.message);
errorMessage = errorData.error || errorMessage;
// Special handling for rate limit errors
if (errorData.message) {
errorDetails = errorData.message;
} else {
errorDetails = errorData.details || '';
if (errorData.suggestion) {
errorDetails += '\n\nSuggestion: ' + errorData.suggestion;
}
if (errorData.errorType) {
errorDetails += '\n\nError Type: ' + errorData.errorType;
}
if (errorData.timestamp) {
errorDetails += '\n\nTime: ' + new Date(errorData.timestamp).toLocaleString();
}
}
} catch (parseError) {
// If not JSON, just use the error message
errorDetails = error.message;
}
const fullMessage = errorDetails ? errorMessage + '\n\n' + errorDetails : errorMessage;
alert(fullMessage);
} finally {
icon.classList.remove('spinning');
}
}
async function refreshRatingHistory(pdgaNumber) {
const icon = document.querySelector(`#history-${pdgaNumber} .chart-title .refresh-icon`);
icon.classList.add('spinning');
try {
const response = await fetch(`/api/refresh-rating-history/${pdgaNumber}`, {
method: 'POST'
});
const data = await response.json();
if (data.success) {
// Refresh the chart
const chartContainer = document.getElementById(`chart-${pdgaNumber}`);
chartContainer.dataset.loaded = 'false'; // Mark as not loaded to force refresh
if (data.history && data.history.length > 0) {
createRatingChart(chartContainer, data.history);
chartContainer.dataset.loaded = 'true';
} else {
chartContainer.innerHTML = '<div class="loading-chart">No rating history available</div>';
}
}
} catch (error) {
console.error('Error refreshing rating history:', error);
alert('Failed to refresh rating history');
} finally {
icon.classList.remove('spinning');
}
}
async function refreshAllPlayers() {
const icons = document.querySelectorAll('th .refresh-icon');
const ratingIcon = icons[0]; // First refresh icon in Rating header
ratingIcon.classList.add('spinning');
try {
const ratings = await getAllPlayersFromDB();
displayRatings(ratings);
} catch (error) {
console.error('Error refreshing all players:', error);
alert('Failed to refresh player data');
} finally {
ratingIcon.classList.remove('spinning');
}
}
async function refreshAllPredictions() {
const icons = document.querySelectorAll('th .refresh-icon');
const predictedIcon = icons[1]; // Second refresh icon in Predicted header
predictedIcon.classList.add('spinning');
try {
// This would be a bulk operation - for now just show message
alert('Bulk prediction refresh not implemented yet. Use individual refresh icons.');
} catch (error) {
console.error('Error refreshing all predictions:', error);
alert('Failed to refresh predictions');
} finally {
predictedIcon.classList.remove('spinning');
}
}
async function loadAllPlayers() {
const button = document.getElementById('load-all-btn');
const originalText = button.textContent;
button.textContent = 'Loading...';
button.style.pointerEvents = 'none';
try {
const progressSection = document.getElementById('progress-section');
const progressBar = document.getElementById('progress-bar');
const progressText = document.getElementById('progress-text');
const tableDiv = document.getElementById('ratings-table');
progressSection.style.display = 'block';
tableDiv.innerHTML = '';
const eventSource = new EventSource('/api/load-all-players');
eventSource.onmessage = function(event) {
const data = JSON.parse(event.data);
if (data.status === 'loading' || data.status === 'completed' || data.status === 'error') {
const percentage = Math.round((data.current / data.total) * 100);
progressBar.style.width = `${percentage}%`;
progressBar.textContent = `${percentage}%`;
if (data.status === 'loading') {
progressText.textContent = `Loading player ${data.current}/${data.total}: PDGA #${data.pdgaNumber}`;
} else if (data.status === 'completed') {
progressText.textContent = `Loaded ${data.name} (${data.current}/${data.total})`;
} else if (data.status === 'error') {
progressText.textContent = `Error loading PDGA #${data.pdgaNumber} (${data.current}/${data.total})`;
}
} else if (data.status === 'complete') {
progressSection.style.display = 'none';
displayRatings(data.ratings);
eventSource.close();
button.textContent = originalText;
button.style.pointerEvents = 'auto';
}
};
eventSource.onerror = function() {
progressSection.style.display = 'none';
tableDiv.innerHTML = '<p>Connection error. Please refresh the page.</p>';
eventSource.close();
button.textContent = originalText;
button.style.pointerEvents = 'auto';
};
} catch (error) {
console.error('Error loading all players:', error);
button.textContent = originalText;
button.style.pointerEvents = 'auto';
}
}
// Debug modal functions
let cachedDebugInfo = {};
async function showDebugInfo(pdgaNumber) {
const modal = document.getElementById('debug-modal');
const header = document.getElementById('debug-header');
const log = document.getElementById('debug-log');
// Get player name for header
const playerNameElement = document.querySelector(`#row-${pdgaNumber} .player-name a`);
const playerName = playerNameElement ? playerNameElement.textContent : `PDGA #${pdgaNumber}`;
header.textContent = `Prediction Calculation Details - ${playerName}`;
log.textContent = 'Loading calculation details...';
modal.style.display = 'flex';
try {
// Check if we have cached debug info
if (cachedDebugInfo[pdgaNumber]) {
log.textContent = cachedDebugInfo[pdgaNumber].join('\n');
return;
}
// Try to get debug info from the latest refresh call
const response = await fetch(`/api/refresh-round-history/${pdgaNumber}`, {
method: 'POST'
});
const data = await response.json();
if (data.success && data.debugLog) {
cachedDebugInfo[pdgaNumber] = data.debugLog;
log.textContent = data.debugLog.join('\n');
} else {
log.textContent = 'No debug information available. Try refreshing the prediction first.';
}
} catch (error) {
console.error('Error fetching debug info:', error);
log.textContent = 'Error loading debug information. Please try again.';
}
}
function closeDebugModal(event) {
const modal = document.getElementById('debug-modal');
modal.style.display = 'none';
}
// Add Player Functions
let pendingPlayerData = null;
async function searchAndAddPlayer() {
const input = document.getElementById('pdga-number-input');
const pdgaNumber = input.value.trim();
if (!pdgaNumber) {
alert('Please enter a PDGA number');
return;
}
const button = document.querySelector('.btn-add');
const originalHTML = button.innerHTML;
button.disabled = true;
button.innerHTML = '<i class="fas fa-sync-alt spinning"></i> Searching...';
try {
const response = await fetch(`/api/search-player/${pdgaNumber}`);
const data = await response.json();
if (!response.ok) {
showErrorModal(data.error || 'Player not found');
return;
}
if (data.alreadyExists) {
showInfoModal(`${data.player.name} is already being tracked!`);
return;
}
// Store player data and show confirmation modal
pendingPlayerData = data.player;
showConfirmationModal(data.player);
} catch (error) {
console.error('Error searching for player:', error);
showErrorModal('Failed to search for player. Please try again.');
} finally {
button.disabled = false;
button.innerHTML = originalHTML;
}
}
function showConfirmationModal(player) {
const modal = document.getElementById('add-player-modal');
const header = document.getElementById('add-player-modal-header');
const body = document.getElementById('add-player-modal-body');
const footer = document.getElementById('add-player-modal-footer');
header.textContent = 'Confirm Player';
body.innerHTML = `
<p>Is this the correct player you want to add?</p>
<div style="background-color: #f8f9fa; padding: 15px; border-radius: 4px; margin-top: 15px;">
<strong style="font-size: 18px; color: #007bff;">${player.name}</strong><br>
<span style="color: #6c757d;">PDGA #${player.pdgaNumber}</span><br>
${player.rating ? `<span style="color: #28a745; font-weight: bold;">Current Rating: ${player.rating}</span>` : '<span style="color: #999;">No rating available</span>'}
</div>
`;
footer.innerHTML = `
<button class="btn btn-cancel" onclick="closeAddPlayerModal()">Cancel</button>
<button class="btn btn-confirm" onclick="confirmAddPlayer()">Add Player</button>
`;
modal.style.display = 'flex';
}
function showErrorModal(message) {
const modal = document.getElementById('add-player-modal');
const header = document.getElementById('add-player-modal-header');
const body = document.getElementById('add-player-modal-body');
const footer = document.getElementById('add-player-modal-footer');
header.textContent = 'Player Not Found';
body.innerHTML = `
<p style="color: #dc3545;">
<i class="fas fa-exclamation-circle"></i> ${message}
</p>
<p style="margin-top: 10px; color: #6c757d; font-size: 14px;">
Please check the PDGA number and try again.
</p>
`;
footer.innerHTML = `
<button class="btn btn-cancel" onclick="closeAddPlayerModal()">Close</button>
`;
modal.style.display = 'flex';
}
function showInfoModal(message) {
const modal = document.getElementById('add-player-modal');
const header = document.getElementById('add-player-modal-header');
const body = document.getElementById('add-player-modal-body');
const footer = document.getElementById('add-player-modal-footer');
header.textContent = 'Information';
body.innerHTML = `
<p style="color: #007bff;">
<i class="fas fa-info-circle"></i> ${message}
</p>
`;
footer.innerHTML = `
<button class="btn btn-cancel" onclick="closeAddPlayerModal()">Close</button>
`;
modal.style.display = 'flex';
}
async function confirmAddPlayer() {
if (!pendingPlayerData) {
closeAddPlayerModal();
return;
}
const modal = document.getElementById('add-player-modal');
const body = document.getElementById('add-player-modal-body');
const footer = document.getElementById('add-player-modal-footer');
// Show loading state
body.innerHTML = '<p style="text-align: center;"><i class="fas fa-sync-alt spinning"></i> Adding player...</p>';
footer.innerHTML = '';
try {
const response = await fetch('/api/add-player', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ pdgaNumber: pendingPlayerData.pdgaNumber })
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || 'Failed to add player');
}
// Success! Show success message
body.innerHTML = `
<p style="color: #28a745; text-align: center;">
<i class="fas fa-check-circle" style="font-size: 48px; margin-bottom: 15px;"></i><br>
<strong>${data.player.name}</strong> has been added successfully!
</p>
`;
footer.innerHTML = `
<button class="btn btn-confirm" onclick="closeAddPlayerModal(); location.reload();">OK</button>
`;
// Clear input
document.getElementById('pdga-number-input').value = '';
pendingPlayerData = null;
} catch (error) {
console.error('Error adding player:', error);
body.innerHTML = `
<p style="color: #dc3545;">
<i class="fas fa-exclamation-circle"></i> ${error.message}
</p>
`;
footer.innerHTML = `
<button class="btn btn-cancel" onclick="closeAddPlayerModal()">Close</button>
`;
}
}
function closeAddPlayerModal(event) {
const modal = document.getElementById('add-player-modal');
modal.style.display = 'none';
pendingPlayerData = null;
}
fetchRatingsWithProgress();
</script>
</body>
</html>