class DartsScoring {
private currentScore: number = 0;
private selectedValue: number | null = null;
private selectedMultiplier: number = 1;
constructor() {
this.initEventListeners();
}
private initEventListeners(): void {
// Score buttons
document.querySelectorAll('.score-btn').forEach(button => {
button.addEventListener('click', (e) => {
this.selectedValue = parseInt((e.target as HTMLElement).dataset.value || '0');
this.updateDisplay();
});
});
// Multiplier buttons
document.querySelectorAll('.multiplier-btn').forEach(button => {
button.addEventListener('click', (e) => {
this.selectedMultiplier = parseInt((e.target as HTMLElement).dataset.multiplier || '1');
this.updateDisplay();
});
});
// Reset button
document.querySelector('.reset-btn')?.addEventListener('click', () => {
this.resetSelection();
});
// Submit button
document.getElementById('submit-score')?.addEventListener('click', () => {
this.submitScore();
});
}
private updateDisplay(): void {
const display = document.getElementById('current-score');
if (!display) return;
if (this.selectedValue !== null) {
this.currentScore = this.selectedValue * this.selectedMultiplier;
display.textContent = this.currentScore.toString();
}
}
private resetSelection(): void {
this.selectedValue = null;
this.selectedMultiplier = 1;
this.currentScore = 0;
const display = document.getElementById('current-score');
if (display) display.textContent = '0';
}
private getCookie(name: string): string | null {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop()?.split(';').shift() || null;
return null;
}
private async submitScore(): Promise<void> {
if (this.currentScore <= 0) {
alert('Please select a valid score before submitting');
return;
}
const userId = this.getCookie('user_id');
const gameId = this.getCookie('game_id');
if (!userId || !gameId) {
alert('User session information missing. Please log in again.');
return;
}
try {
const response = await fetch('/api/v1/score', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
user_id: userId,
game_id: gameId,
score: this.currentScore
})
});
if (!response.ok) {
throw new Error('Failed to submit score');
}
const result = await response.json();
console.log('Score submitted successfully:', result);
this.resetSelection();
// You might want to add some visual feedback here
} catch (error) {
console.error('Error submitting score:', error);
alert('There was an error submitting your score. Please try again.');
}
}
}
// Initialize the component when the DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
new DartsScoring();
});