Files
Sdk_TV_app/templates/results_calculator.html
T
2025-11-11 17:34:42 +01:00

1394 lines
40 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title data-i18n="scoring.results_calculator">Results Calculator</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/static/css/base.css">
<link rel="stylesheet" href="/static/css/navbar.css">
<link rel="stylesheet" href="/static/css/buttons.css">
<link rel="stylesheet" href="/static/css/components.css">
<link rel="stylesheet" href="/static/css/responsive.css">
<style>
/* Results Calculator specific styles */
.container {
max-width: 1000px;
margin: 0 auto;
padding: 30px 20px;
}
.header-section {
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
padding: 20px;
margin-bottom: 30px;
text-align: center;
color: white;
position: relative;
overflow: hidden;
}
/* Dynamic header colors based on tournament type */
.header-section.tournament-4_targets {
background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
}
.header-section.tournament-20_targets {
background: linear-gradient(135deg, #ff6b6b 0%, #ff8e53 100%);
}
.header-section.tournament-40_targets {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.header-section.tournament-default {
background: linear-gradient(135deg, #ff6b6b 0%, #ff8e53 100%);
}
.header-section::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: linear-gradient(45deg, rgba(255, 255, 255, 0.1) 0%, transparent 50%, rgba(255, 255, 255, 0.05) 100%);
pointer-events: none;
}
.header-section * {
position: relative;
z-index: 2;
}
.header-logo {
height: 50px;
max-width: 140px;
object-fit: contain;
margin-bottom: 15px;
filter: brightness(1.2) contrast(1.1);
background-color: white;
padding: 8px;
border-radius: 6px;
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.2);
}
.header-title {
font-size: 1.6rem;
font-weight: 700;
color: rgb(255, 255, 255);
margin-bottom: 8px;
text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}
.header-subtitle {
font-size: 1rem;
color: rgba(255, 255, 255, 0.95);
margin-bottom: 15px;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}
.progress-info {
display: flex;
justify-content: center;
gap: 30px;
flex-wrap: wrap;
margin-bottom: 15px;
}
.progress-item {
text-align: center;
}
.progress-number {
font-size: 1.4rem;
font-weight: 700;
color: #ffffff;
display: block;
text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}
.progress-label {
font-size: 0.75rem;
color: rgba(255, 255, 255, 0.9);
text-transform: uppercase;
letter-spacing: 0.5px;
font-weight: 500;
}
.global-actions {
display: flex;
justify-content: center;
gap: 15px;
flex-wrap: wrap;
margin-top: 20px;
}
.global-btn {
padding: 12px 24px;
border: none;
border-radius: 8px;
font-size: 1rem;
font-weight: bold;
cursor: pointer;
transition: all 0.2s ease;
}
.fill-all-btn {
background: #ff6b35;
color: white;
}
.fill-all-btn:hover {
background: #e55a2b;
transform: translateY(-1px);
box-shadow: 0 4px 8px rgba(255, 107, 53, 0.3);
}
.save-all-btn {
background: #17a2b8;
color: white;
}
.save-all-btn:hover {
background: #138496;
transform: translateY(-1px);
box-shadow: 0 4px 8px rgba(23, 162, 184, 0.3);
}
.participants-list {
display: flex;
flex-direction: column;
gap: 20px;
margin-bottom: 30px;
}
.participant-card {
background: white;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
overflow: hidden;
transition: all 0.2s ease;
border-left: 5px solid #e9ecef;
}
.participant-card.completed {
border-left-color: #28a745;
}
.participant-card.in-progress {
border-left-color: #ffc107;
}
.participant-card.collapsed {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
.participant-header {
padding: 20px 25px;
background: #f8f9fa;
display: flex;
justify-content: space-between;
align-items: center;
cursor: pointer;
transition: all 0.2s ease;
}
.participant-card.completed .participant-header {
background: #f8fff9;
}
.participant-card.in-progress .participant-header {
background: #fffbf0;
}
.participant-header:hover {
background: #e9ecef;
}
.participant-card.completed .participant-header:hover {
background: #f0fff1;
}
.participant-card.in-progress .participant-header:hover {
background: #fff8e1;
}
.participant-info {
display: flex;
align-items: center;
gap: 15px;
}
.participant-name {
font-size: 1.4rem;
font-weight: bold;
color: #333;
}
.participant-id {
background: #007bff;
color: white;
padding: 6px 15px;
border-radius: 15px;
font-size: 0.9rem;
font-weight: bold;
}
.participant-status {
display: flex;
align-items: center;
gap: 15px;
}
.score-display {
text-align: right;
display: flex;
flex-direction: column;
gap: 5px;
}
.score-row {
display: flex;
align-items: center;
gap: 15px;
}
.total-score {
text-align: right;
}
.score-number {
font-size: 1.8rem;
font-weight: bold;
color: #28a745;
}
.score-label {
font-size: 0.8rem;
color: #666;
text-transform: uppercase;
}
.tens-count {
text-align: right;
}
.tens-number {
font-size: 1.4rem;
font-weight: bold;
color: #ffc107;
}
.tens-label {
font-size: 0.8rem;
color: #666;
text-transform: uppercase;
}
.completion-badge {
padding: 6px 15px;
border-radius: 15px;
font-size: 0.9rem;
font-weight: bold;
text-transform: uppercase;
}
.badge-completed {
background: #28a745;
color: white;
}
.badge-in-progress {
background: #ffc107;
color: #856404;
}
.badge-not-started {
background: #6c757d;
color: white;
}
.collapse-icon {
font-size: 1.2rem;
transition: transform 0.3s ease;
color: #666;
}
.participant-card.collapsed .collapse-icon {
transform: rotate(-90deg);
}
.participant-content {
max-height: 1000px;
overflow: hidden;
transition: max-height 0.3s ease;
}
.participant-card.collapsed .participant-content {
max-height: 0;
}
.targets-section {
padding: 25px;
}
.targets-grid {
display: grid;
gap: 15px;
margin-bottom: 20px;
max-width: 100%;
}
/* Grid layouts for different target counts */
.targets-grid.targets-4 {
grid-template-columns: repeat(4, 1fr);
}
.targets-grid.targets-20 {
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}
.targets-grid.targets-40 {
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}
/* Responsive adjustments */
@media (max-width: 768px) {
.targets-grid.targets-20 {
grid-template-columns: repeat(5, 1fr);
gap: 8px;
}
.targets-grid.targets-40 {
grid-template-columns: repeat(8, 1fr);
gap: 6px;
}
.targets-grid.targets-4 {
grid-template-columns: repeat(2, 1fr);
gap: 12px;
}
}
@media (max-width: 480px) {
.targets-grid.targets-20 {
grid-template-columns: repeat(4, 1fr);
gap: 6px;
padding: 15px;
}
.targets-grid.targets-40 {
grid-template-columns: repeat(6, 1fr);
gap: 4px;
}
.targets-grid.targets-4 {
grid-template-columns: repeat(2, 1fr);
gap: 10px;
}
.score-row {
flex-direction: column;
gap: 8px;
}
.participant-header {
flex-direction: column;
align-items: flex-start;
gap: 15px;
}
.participant-status {
width: 100%;
justify-content: space-between;
flex-wrap: wrap;
}
}
.target-group {
border: 2px solid #e9ecef;
border-radius: 8px;
padding: 15px 12px;
background: #f8f9fa;
text-align: center;
}
.target-group.completed {
border-color: #28a745;
background: #f8fff9;
}
.target-number {
font-size: 1rem;
font-weight: bold;
color: #333;
margin-bottom: 10px;
}
.shots-container {
display: flex;
flex-direction: column;
gap: 3px;
}
.shots-container.shots-5 {
gap: 2px;
}
.shot-input {
width: 100%;
padding: 12px 8px;
border: 2px solid #ddd;
border-radius: 6px;
text-align: center;
font-size: 1.2rem;
font-weight: bold;
color: #333;
background-color: #ffffff;
min-height: 45px;
display: flex;
align-items: center;
justify-content: center;
}
.shots-container.shots-5 .shot-input {
padding: 10px 6px;
font-size: 1rem;
min-height: 40px;
}
.shot-input:focus {
outline: none;
border-color: #007bff;
box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}
.shot-input.valid {
border-color: #28a745;
background: #f8fff9;
}
.shot-input.ten {
border-color: #ffc107;
background: #fff9e6;
font-weight: bold;
}
.participant-actions {
display: flex;
justify-content: space-between;
align-items: center;
gap: 10px;
margin-top: 20px;
padding-top: 20px;
border-top: 1px solid #f0f0f0;
}
.action-btn {
padding: 10px 18px;
border: none;
border-radius: 6px;
font-size: 0.9rem;
font-weight: bold;
cursor: pointer;
transition: all 0.2s ease;
}
.clear-btn {
background: #6c757d;
color: white;
}
.clear-btn:hover {
background: #5a6268;
}
.save-btn {
background: #007bff;
color: white;
}
.save-btn:hover {
background: #0056b3;
}
.auto-fill-btn {
background: #ffc107;
color: #856404;
}
.auto-fill-btn:hover {
background: #e0a800;
}
.finish-section {
background: white;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
padding: 25px;
text-align: center;
}
.finish-title {
font-size: 1.5rem;
font-weight: bold;
color: #333;
margin-bottom: 15px;
}
.finish-description {
color: #666;
margin-bottom: 20px;
}
.finish-btn {
background: #28a745;
border: none;
color: white;
padding: 15px 30px;
border-radius: 8px;
cursor: pointer;
font-size: 1.1rem;
font-weight: bold;
transition: all 0.2s ease;
}
.finish-btn:hover {
background: #1e7e34;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
}
.finish-btn:disabled {
background: #6c757d;
cursor: not-allowed;
transform: none;
box-shadow: none;
}
.warning-message {
background: #fff3cd;
border: 1px solid #ffeaa7;
color: #856404;
padding: 12px 15px;
border-radius: 6px;
margin: 15px 0;
}
/* Loading and saving indicators */
.saving {
opacity: 0.7;
pointer-events: none;
}
.saving::after {
content: '';
position: absolute;
top: 50%;
left: 50%;
width: 20px;
height: 20px;
margin: -10px 0 0 -10px;
border: 2px solid #f3f3f3;
border-top: 2px solid #007bff;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
<script src="/static/js/i18n.js"></script>
</head>
<body>
<div class="navbar">
<div class="navbar-title">🎯 <span data-i18n="scoring.results_calculator">Results Calculator</span></div>
<div class="navbar-controls">
<a href="/" class="nav-btn">📺 <span data-i18n="navigation.dashboard">Dashboard</span></a>
<a href="/tournament" class="nav-btn">🏆 <span data-i18n="navigation.tournament">Tournament</span></a>
<a href="/tournament/draft" class="nav-btn">📋 <span data-i18n="tournament.view_draft">Draft</span></a>
<a href="/results/calculator" class="nav-btn active">🎯 <span data-i18n="navigation.calculator">Results Calculator</span></a>
</div>
</div>
<div class="container">
<div class="header-section tournament-{{ results.tournament_type if results and results.tournament_type else 'default' }}">
<img src="/static/logo.png" alt="Logo" class="header-logo" onerror="this.style.display='none'" />
<div class="header-title">
{% if results and results.tournament_type == '4_targets' %}
🎯 <span data-i18n="scoring.tournament_scoring">Tournament Scoring</span>
{% elif results and results.tournament_type == '40_targets' %}
💪 <span data-i18n="scoring.tournament_scoring">Tournament Scoring</span>
{% else %}
<span data-i18n="scoring.tournament_scoring">Tournament Scoring</span>
{% endif %}
</div>
<div class="header-subtitle" id="tournamentSubtitle">
{% if results.tournament_type == '40_targets' %}
<span data-i18n="scoring.enter_scores_40_targets">Enter scores for each participant (40 targets, 2 shots each). Score 0 = miss.</span>
{% elif results.tournament_type == '4_targets' %}
<span data-i18n="scoring.enter_scores_4_targets">Enter scores for each participant (4 targets, 5 shots each). Score 0 = miss.</span>
{% else %}
<span data-i18n="scoring.enter_scores_20_targets">Enter scores for each participant (20 targets, 2 shots each). Score 0 = miss.</span>
{% endif %}
</div>
<div class="progress-info">
<div class="progress-item">
<div class="progress-number" id="completedCount">0</div>
<div class="progress-label" data-i18n="scoring.completed">Zaključeno</div>
</div>
<div class="progress-item">
<div class="progress-number" id="totalParticipants">{{ results.participants|length }}</div>
<div class="progress-label" data-i18n="scoring.total">Skupaj</div>
</div>
<div class="progress-item">
<div class="progress-number" id="totalShots">0</div>
<div class="progress-label" data-i18n="scoring.total_shots">Skupaj Strelov</div>
</div>
<div class="progress-item">
<div class="progress-number" id="totalTens">0</div>
<div class="progress-label" data-i18n="results.tens">Tens</div>
</div>
</div>
<div class="global-actions">
<button class="global-btn fill-all-btn" onclick="fillAllPlayersRandom()">
🎲 <span data-i18n="scoring.fill_all_players_random">Napolni Vse Igralce Naključno</span>
</button>
</div>
</div>
<div class="participants-list">
{% for player_id, participant in results.participants.items() %}
<div class="participant-card" id="card-{{ player_id }}" data-player-id="{{ player_id }}">
<div class="participant-header" onclick="toggleParticipant({{ player_id }})">
<div class="participant-info">
<div class="participant-name">{{ participant.name }}</div>
<div class="participant-id">ID: {{ player_id }}</div>
</div>
<div class="participant-status">
<div class="score-display">
<div class="score-row">
<div class="total-score">
<div class="score-number" id="total-{{ player_id }}">{{ participant.total_score }}</div>
<div class="score-label" data-i18n="scoring.points">Točke</div>
</div>
<div class="tens-count">
<div class="tens-number" id="tens-{{ player_id }}">0</div>
<div class="tens-label">10s</div>
</div>
</div>
</div>
<div class="completion-badge" id="badge-{{ player_id }}">
{% if participant.completed %}
<span class="badge-completed" data-i18n="scoring.completed">Zaključeno</span>
{% else %}
<span class="badge-not-started" data-i18n="scoring.not_started">Ni Začeto</span>
{% endif %}
</div>
<div class="collapse-icon"></div>
</div>
</div>
<div class="participant-content">
<div class="targets-section">
<div class="targets-grid" id="targets-{{ player_id }}">
<!-- Targets will be populated by JavaScript based on tournament type -->
</div>
<div class="participant-actions">
<button class="action-btn clear-btn" onclick="clearParticipant({{ player_id }})">
🗑️ <span data-i18n="scoring.clear">Počisti</span>
</button>
<button class="action-btn save-btn" onclick="saveParticipant({{ player_id }})">
💾 <span data-i18n="scoring.save">Shrani</span>
</button>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
<div class="finish-section">
<div class="finish-title">🏁 <span data-i18n="scoring.finish_tournament">Zaključi Turnir</span></div>
<div class="warning-message" id="finishWarning" style="display: none;">
<strong data-i18n="scoring.warning">Opozorilo:</strong> <span data-i18n="scoring.finish_warning">Niso vsi udeleženci zaključili s točkovanjem. Prosimo, da poskrbite, da je vse točkovanje zaključeno pred zaključkom.</span>
</div>
<button class="finish-btn" id="finishBtn" onclick="finishTournament()" data-i18n="scoring.finish_tournament_button">🏁 Finish Tournament & Show Results
🏆 Finish Tournament & Show Results
</button>
</div>
</div>
<script>
let results = {{ results|tojson }};
let saveTimeout = {};
// Tournament configuration
const tournamentType = results.tournament_type || '20_targets';
let numTargets, shotsPerTarget;
// Set tournament parameters
if (tournamentType === '40_targets') {
numTargets = 40;
shotsPerTarget = 2;
} else if (tournamentType === '4_targets') {
numTargets = 4;
shotsPerTarget = 5;
} else {
numTargets = 20;
shotsPerTarget = 2;
}
// Calculate 10s count for a player
function calculateTensCount(playerId) {
const playerIdStr = playerId.toString();
const targets = results.participants[playerIdStr].targets;
let tensCount = 0;
for (let target in targets) {
const targetData = targets[target];
for (let i = 1; i <= shotsPerTarget; i++) {
const shotValue = targetData[`shot${i}`];
if (shotValue === 10) {
tensCount++;
}
}
}
return tensCount;
}
// Update participant's 10s display
function updateParticipantTens(playerId) {
const tensCount = calculateTensCount(playerId);
const tensElement = document.getElementById(`tens-${playerId}`);
if (tensElement) {
tensElement.textContent = tensCount;
// Add visual feedback
tensElement.style.color = '#ffc107';
setTimeout(() => {
tensElement.style.color = '';
}, 300);
}
}
// Update overall 10s count
function updateOverallTens() {
let totalTens = 0;
for (let playerId in results.participants) {
totalTens += calculateTensCount(parseInt(playerId));
}
document.getElementById('totalTens').textContent = totalTens;
}
// Debounce function for auto-saving
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
function generateTargetsHTML(playerId) {
const participant = results.participants[playerId.toString()];
let html = '';
for (let i = 1; i <= numTargets; i++) {
const targetData = participant.targets[i.toString()] || {};
html += `
<div class="target-group" id="target-group-${playerId}-${i}">
<div class="target-number">${i}</div>
<div class="shots-container shots-${shotsPerTarget}">
`;
for (let shot = 1; shot <= shotsPerTarget; shot++) {
const shotKey = `shot${shot}`;
const value = targetData[shotKey];
const displayValue = value !== null && value !== undefined ? value : '';
html += `
<input type="number"
class="shot-input ${value === 10 ? 'ten' : ''}"
id="shot${shot}-${playerId}-${i}"
data-player="${playerId}"
data-target="${i}"
data-shot="${shot}"
min="0"
max="10"
value="${displayValue}"
placeholder="S${shot}"
oninput="updateScore(${playerId}, ${i}, ${shot}, this.value)">
`;
}
html += `
</div>
</div>
`;
}
return html;
}
function initializeTargetsForPlayer(playerId) {
const targetsContainer = document.getElementById(`targets-${playerId}`);
if (targetsContainer) {
targetsContainer.className = `targets-grid targets-${numTargets}`;
targetsContainer.innerHTML = generateTargetsHTML(playerId);
}
}
function toggleParticipant(playerId) {
const card = document.getElementById(`card-${playerId}`);
card.classList.toggle('collapsed');
}
function updateScore(playerId, targetNum, shotNum, value) {
const playerIdStr = playerId.toString();
const targetStr = targetNum.toString();
// Parse input - allow empty string, treat as null/undefined for completion check
let numValue = null;
if (value !== '' && value !== null && value !== undefined) {
numValue = parseInt(value);
if (isNaN(numValue)) numValue = null;
else numValue = Math.max(0, Math.min(10, numValue)); // Clamp between 0-10
}
// Update the input field with clamped value
const input = document.getElementById(`shot${shotNum}-${playerId}-${targetNum}`);
if (input && numValue !== null && input.value !== numValue.toString()) {
input.value = numValue;
}
// Update local data
if (!results.participants[playerIdStr]) {
console.error('Player not found:', playerIdStr);
return;
}
if (!results.participants[playerIdStr].targets[targetStr]) {
// Initialize target with all shots as null
const target = {};
for (let i = 1; i <= shotsPerTarget; i++) {
target[`shot${i}`] = null;
}
results.participants[playerIdStr].targets[targetStr] = target;
}
results.participants[playerIdStr].targets[targetStr][`shot${shotNum}`] = numValue;
// Update target group styling
updateTargetGroupStyling(playerId, targetNum);
// Recalculate totals
updateParticipantTotal(playerId);
updateParticipantTens(playerId);
updateParticipantStatus(playerId);
updateOverallProgress();
updateOverallTens();
// Visual feedback for input - highlight 10s
if (input) {
input.classList.remove('valid', 'ten');
if (numValue !== null) {
if (numValue === 10) {
input.classList.add('ten');
} else {
input.classList.add('valid');
}
}
}
// Auto-save with debounce
clearTimeout(saveTimeout[playerId]);
saveTimeout[playerId] = setTimeout(() => {
saveParticipant(playerId, true);
}, 1000);
}
function updateTargetGroupStyling(playerId, targetNum) {
const playerIdStr = playerId.toString();
const targetStr = targetNum.toString();
const targetGroup = document.getElementById(`target-group-${playerId}-${targetNum}`);
if (targetGroup && results.participants[playerIdStr].targets[targetStr]) {
const targetData = results.participants[playerIdStr].targets[targetStr];
// Check if all shots are completed
let allCompleted = true;
for (let i = 1; i <= shotsPerTarget; i++) {
const shotValue = targetData[`shot${i}`];
if (shotValue === null || shotValue === undefined) {
allCompleted = false;
break;
}
}
if (allCompleted) {
targetGroup.classList.add('completed');
} else {
targetGroup.classList.remove('completed');
}
}
}
function updateParticipantTotal(playerId) {
const playerIdStr = playerId.toString();
const targets = results.participants[playerIdStr].targets;
let total = 0;
for (let target in targets) {
const targetData = targets[target];
for (let i = 1; i <= shotsPerTarget; i++) {
const shotValue = targetData[`shot${i}`];
total += (shotValue !== null && shotValue !== undefined ? shotValue : 0);
}
}
results.participants[playerIdStr].total_score = total;
// Update display
const totalElement = document.getElementById(`total-${playerId}`);
if (totalElement) {
totalElement.textContent = total;
// Add visual feedback
totalElement.style.color = '#28a745';
setTimeout(() => {
totalElement.style.color = '';
}, 300);
}
}
function updateParticipantStatus(playerId) {
const playerIdStr = playerId.toString();
const targets = results.participants[playerIdStr].targets;
const card = document.getElementById(`card-${playerId}`);
const badge = document.getElementById(`badge-${playerId}`);
let completedTargets = 0;
let totalShots = 0;
for (let target in targets) {
const targetData = targets[target];
let targetCompleted = true;
for (let i = 1; i <= shotsPerTarget; i++) {
const shotValue = targetData[`shot${i}`];
// Count shots that have been entered (including 0)
if (shotValue !== null && shotValue !== undefined) {
totalShots++;
} else {
targetCompleted = false;
}
}
if (targetCompleted) {
completedTargets++;
}
}
const isCompleted = completedTargets === numTargets;
const isInProgress = totalShots > 0 && !isCompleted;
results.participants[playerIdStr].completed = isCompleted;
// Update card styling
card.classList.remove('completed', 'in-progress');
if (isCompleted) {
card.classList.add('completed');
badge.innerHTML = `<span class="badge-completed">${t('scoring.completed')}</span>`;
} else if (isInProgress) {
card.classList.add('in-progress');
badge.innerHTML = `<span class="badge-in-progress">${t('scoring.in_progress')}</span>`;
} else {
badge.innerHTML = `<span class="badge-not-started">${t('scoring.not_started')}</span>`;
}
}
function updateOverallProgress() {
let completedCount = 0;
let totalShots = 0;
for (let playerId in results.participants) {
const participant = results.participants[playerId];
if (participant.completed) {
completedCount++;
}
for (let target in participant.targets) {
const targetData = participant.targets[target];
for (let i = 1; i <= shotsPerTarget; i++) {
const shotValue = targetData[`shot${i}`];
if (shotValue !== null && shotValue !== undefined) totalShots++;
}
}
}
document.getElementById('completedCount').textContent = completedCount;
document.getElementById('totalShots').textContent = totalShots;
// Update finish button state
const finishBtn = document.getElementById('finishBtn');
const finishWarning = document.getElementById('finishWarning');
const allCompleted = completedCount === Object.keys(results.participants).length;
if (allCompleted) {
finishBtn.disabled = false;
finishWarning.style.display = 'none';
} else {
finishBtn.disabled = true;
finishWarning.style.display = 'block';
}
}
async function saveParticipant(playerId, silent = false) {
const card = document.getElementById(`card-${playerId}`);
if (!silent) card.classList.add('saving');
try {
const playerIdStr = playerId.toString();
const participantData = results.participants[playerIdStr];
const response = await fetch(`/api/results/participant/${playerId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
targets: participantData.targets
})
});
if (response.ok) {
const result = await response.json();
if (!silent) {
// Show success feedback
const saveBtn = card.querySelector('.save-btn');
const originalText = saveBtn.innerHTML;
saveBtn.innerHTML = `${t('scoring.all_saved')}`;
saveBtn.style.background = '#28a745';
setTimeout(() => {
saveBtn.innerHTML = originalText;
saveBtn.style.background = '';
}, 2000);
}
} else {
throw new Error('Failed to save');
}
} catch (error) {
console.error('Error saving participant:', error);
if (!silent) {
alert('Failed to save participant data. Please try again.');
}
} finally {
if (!silent) card.classList.remove('saving');
}
}
async function saveAllPlayers() {
const saveAllBtn = document.querySelector('.save-all-btn');
const originalText = saveAllBtn.textContent;
saveAllBtn.textContent = `💾 ${t('scoring.saving_all')}`;
saveAllBtn.disabled = true;
try {
const playerIds = Object.keys(results.participants);
for (const playerId of playerIds) {
await saveParticipant(parseInt(playerId), true);
}
// Show success feedback
saveAllBtn.textContent = `${t('scoring.all_saved')}`;
saveAllBtn.style.background = '#28a745';
setTimeout(() => {
saveAllBtn.textContent = originalText;
saveAllBtn.style.background = '';
saveAllBtn.disabled = false;
}, 2000);
} catch (error) {
console.error('Error saving all players:', error);
alert('Failed to save all player data. Please try again.');
saveAllBtn.textContent = originalText;
saveAllBtn.disabled = false;
}
}
function clearParticipant(playerId) {
if (!confirm('Are you sure you want to clear all scores for this participant?')) {
return;
}
const playerIdStr = playerId.toString();
// Clear all inputs
for (let i = 1; i <= numTargets; i++) {
for (let shot = 1; shot <= shotsPerTarget; shot++) {
const shotInput = document.getElementById(`shot${shot}-${playerId}-${i}`);
if (shotInput) {
shotInput.value = '';
shotInput.classList.remove('valid', 'ten');
}
}
// Update data
const target = {};
for (let shot = 1; shot <= shotsPerTarget; shot++) {
target[`shot${shot}`] = null;
}
results.participants[playerIdStr].targets[i.toString()] = target;
// Update target group styling
updateTargetGroupStyling(playerId, i);
}
updateParticipantTotal(playerId);
updateParticipantTens(playerId);
updateParticipantStatus(playerId);
updateOverallProgress();
updateOverallTens();
// Save changes
saveParticipant(playerId);
}
function autoFillDemo(playerId) {
if (!confirm('Fill with random demo scores? This will overwrite existing data.')) {
return;
}
fillPlayerRandom(playerId);
saveParticipant(playerId);
}
function fillPlayerRandom(playerId) {
const playerIdStr = playerId.toString();
// Fill with random scores (0-10) - all fields will be filled
for (let i = 1; i <= numTargets; i++) {
const target = {};
for (let shot = 1; shot <= shotsPerTarget; shot++) {
const randomScore = Math.floor(Math.random() * 11);
const shotInput = document.getElementById(`shot${shot}-${playerId}-${i}`);
if (shotInput) {
shotInput.value = randomScore;
shotInput.classList.remove('valid', 'ten');
if (randomScore === 10) {
shotInput.classList.add('ten');
} else {
shotInput.classList.add('valid');
}
}
target[`shot${shot}`] = randomScore;
}
// Update data
results.participants[playerIdStr].targets[i.toString()] = target;
// Update target group styling
updateTargetGroupStyling(playerId, i);
}
updateParticipantTotal(playerId);
updateParticipantTens(playerId);
updateParticipantStatus(playerId);
updateOverallProgress();
updateOverallTens();
}
async function fillAllPlayersRandom() {
if (!confirm('Fill ALL players with random demo scores? This will overwrite all existing data and enable tournament finish.')) {
return;
}
const fillAllBtn = document.querySelector('.fill-all-btn');
const originalText = fillAllBtn.textContent;
fillAllBtn.textContent = `🎲 ${t('scoring.filling_all')}`;
fillAllBtn.disabled = true;
try {
// Fill all players with random data
const playerIds = Object.keys(results.participants);
for (const playerId of playerIds) {
fillPlayerRandom(parseInt(playerId));
}
// Save all players
for (const playerId of playerIds) {
await saveParticipant(parseInt(playerId), true);
}
// Show success feedback
fillAllBtn.textContent = `${t('scoring.all_filled')}`;
fillAllBtn.style.background = '#28a745';
// Show notification
const notification = document.createElement('div');
notification.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
background: #28a745;
color: white;
padding: 15px 25px;
border-radius: 8px;
z-index: 1000;
font-weight: bold;
box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
`;
setTimeout(() => {
document.body.removeChild(notification);
fillAllBtn.textContent = originalText;
fillAllBtn.style.background = '';
fillAllBtn.disabled = false;
}, 4000);
} catch (error) {
console.error('Error filling all players:', error);
alert('Failed to fill all players. Please try again.');
fillAllBtn.textContent = originalText;
fillAllBtn.disabled = false;
}
}
async function finishTournament() {
const allCompleted = Object.values(results.participants).every(p => p.completed);
if (!allCompleted) {
alert('Please complete scoring for all participants before finishing the tournament.');
return;
}
if (!confirm('Are you sure you want to finish the tournament? This will finalize all results and make them viewable.')) {
return;
}
const finishBtn = document.getElementById('finishBtn');
finishBtn.disabled = true;
finishBtn.textContent = '🔄 Finishing Tournament...';
try {
const response = await fetch('/api/results/finish', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
});
if (response.ok) {
const responseData = await response.json();
// Determine where to redirect based on tournament type and archive
let redirectUrl = '/results';
// Priority 1: If league finished, redirect to league archive
if (responseData.league_archived && responseData.league_archive_filename) {
redirectUrl = `/archive/league/${responseData.league_archive_filename}`;
}
// Priority 2: If standalone tournament, redirect to tournament archive
else if (responseData.archived && responseData.archive_filename) {
redirectUrl = `/archive/tournament/${responseData.archive_filename}`;
}
// Priority 3: If league tournament (not final), show league standings
else if (responseData.league && !responseData.league_finished) {
redirectUrl = '/results'; // This will show league standings with current tournament
}
// Always show results after tournament finishes
alert('Tournament finished successfully! Showing results...');
setTimeout(() => {
window.location.href = redirectUrl;
}, 1000);
} else {
const error = await response.json();
throw new Error(error.message || 'Failed to finish tournament');
}
} catch (error) {
console.error('Error finishing tournament:', error);
alert('Failed to finish tournament: ' + error.message);
finishBtn.disabled = false;
finishBtn.textContent = '🏆 Finish Tournament & Show Results';
}
}
// Keyboard shortcuts
document.addEventListener('keydown', function(event) {
if (event.ctrlKey && event.key === 's') {
event.preventDefault();
saveAllPlayers();
}
});
// Initialize
document.addEventListener('DOMContentLoaded', function() {
// Initialize targets for all players
Object.keys(results.participants).forEach(playerId => {
initializeTargetsForPlayer(parseInt(playerId));
// Update initial states
for (let i = 1; i <= numTargets; i++) {
updateTargetGroupStyling(parseInt(playerId), i);
}
updateParticipantStatus(parseInt(playerId));
updateParticipantTens(parseInt(playerId));
});
updateOverallProgress();
updateOverallTens();
// Add input validation and navigation
document.addEventListener('input', function(e) {
if (e.target.classList.contains('shot-input')) {
if (e.target.value !== '') {
const value = parseInt(e.target.value);
const clampedValue = Math.max(0, Math.min(10, isNaN(value) ? 0 : value));
if (e.target.value !== clampedValue.toString()) {
e.target.value = clampedValue;
}
}
}
});
document.addEventListener('keydown', function(e) {
if (e.target.classList.contains('shot-input') && e.key === 'Enter') {
const inputs = Array.from(document.querySelectorAll('.shot-input'));
const currentIndex = inputs.indexOf(e.target);
const nextInput = inputs[currentIndex + 1];
if (nextInput) {
nextInput.focus();
nextInput.select();
}
}
});
});
</script>
</body>
</html>