retropulse/public/js/main.js
2025-09-02 22:27:25 +05:30

195 lines
6.3 KiB
JavaScript

// main.js - Frontend logic for the main page
let currentUsername = '';
// DOM elements
const userForm = document.getElementById('userForm');
const usernameInput = document.getElementById('username');
const loadingSection = document.getElementById('loading');
const errorSection = document.getElementById('error');
const userInfoSection = document.getElementById('userInfo');
// Initialize event listeners
document.addEventListener('DOMContentLoaded', function() {
userForm.addEventListener('submit', handleFormSubmit);
// Auto-focus username input
usernameInput.focus();
// Allow Enter key to submit
usernameInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
handleFormSubmit(e);
}
});
});
// Handle form submission
async function handleFormSubmit(e) {
e.preventDefault();
const username = usernameInput.value.trim();
if (!username) {
showError('Please enter a username');
return;
}
// Validate username format
if (!/^[a-zA-Z0-9_-]+$/.test(username)) {
showError('Username can only contain letters, numbers, underscores, and hyphens');
return;
}
currentUsername = username;
await fetchUserData(username);
}
// Fetch user data from API
async function fetchUserData(username) {
showLoading();
try {
console.log(`Fetching data for user: ${username}`);
const response = await fetch(`/api/userinfo?username=${encodeURIComponent(username)}`);
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Failed to fetch user data');
}
console.log('User data received:', data);
displayUserData(data);
} catch (error) {
console.error('Error fetching user data:', error);
showError(error.message || 'Failed to load user data. Please try again.');
}
}
// Display user data in the UI
function displayUserData(data) {
const { user, lastGame, lastAchievement } = data;
// Update user profile
document.getElementById('userName').textContent = user.displayName;
document.getElementById('userMotto').textContent = user.motto || 'No motto set';
document.getElementById('totalPoints').textContent = user.totalPoints.toLocaleString();
document.getElementById('truePoints').textContent = user.totalTruePoints.toLocaleString();
// Format member since date
if (user.memberSince) {
const memberDate = new Date(user.memberSince);
document.getElementById('memberSince').textContent = memberDate.toLocaleDateString();
}
// Set avatar
const avatarImg = document.getElementById('userAvatar');
if (user.avatar) {
avatarImg.src = user.avatar;
avatarImg.style.display = 'block';
} else {
avatarImg.style.display = 'none';
}
// Display last game
const lastGameSection = document.getElementById('lastGameSection');
if (lastGame) {
document.getElementById('gameTitle').textContent = lastGame.title;
document.getElementById('consoleName').textContent = lastGame.consoleName;
const gameIconImg = document.getElementById('gameIcon');
if (lastGame.icon) {
gameIconImg.src = lastGame.icon;
gameIconImg.style.display = 'block';
} else {
gameIconImg.style.display = 'none';
}
lastGameSection.style.display = 'block';
} else {
lastGameSection.style.display = 'none';
}
// Display last achievement
const lastAchievementSection = document.getElementById('lastAchievementSection');
if (lastAchievement) {
document.getElementById('achievementTitle').textContent = lastAchievement.title;
document.getElementById('achievementDescription').textContent = lastAchievement.description;
document.getElementById('achievementPoints').textContent = lastAchievement.points;
document.getElementById('achievementTrueRatio').textContent = lastAchievement.trueRatio;
// Set achievement badge (try badgeName first, then gameIcon as fallback)
const achievementBadgeImg = document.getElementById('achievementBadge');
// For now, we'll use the game icon since badges aren't in the current API response
if (lastAchievement.gameIcon) {
achievementBadgeImg.src = lastAchievement.gameIcon;
achievementBadgeImg.style.display = 'block';
} else {
achievementBadgeImg.style.display = 'none';
}
lastAchievementSection.style.display = 'block';
} else {
lastAchievementSection.style.display = 'none';
}
// Setup overlay URL and link
const overlayUrl = `${window.location.origin}/overlay/${encodeURIComponent(currentUsername)}`;
document.getElementById('overlayUrl').value = overlayUrl;
document.getElementById('overlayLink').href = overlayUrl;
showUserInfo();
}
// UI state management functions
function showLoading() {
hideAllSections();
loadingSection.classList.remove('hidden');
}
function showError(message) {
hideAllSections();
document.querySelector('.error-message').textContent = message;
errorSection.classList.remove('hidden');
}
function showUserInfo() {
hideAllSections();
userInfoSection.classList.remove('hidden');
}
function hideAllSections() {
loadingSection.classList.add('hidden');
errorSection.classList.add('hidden');
userInfoSection.classList.add('hidden');
}
function clearError() {
showUserInfo();
}
// Copy overlay URL to clipboard
async function copyOverlayUrl() {
const overlayUrlInput = document.getElementById('overlayUrl');
try {
await navigator.clipboard.writeText(overlayUrlInput.value);
// Show feedback
const button = event.target;
const originalText = button.textContent;
button.textContent = 'Copied!';
button.style.background = '#28a745';
setTimeout(() => {
button.textContent = originalText;
button.style.background = '';
}, 2000);
} catch (err) {
// Fallback for older browsers
overlayUrlInput.select();
document.execCommand('copy');
alert('Overlay URL copied to clipboard!');
}
}