secretadmin / script.js
shashankadari's picture
Upload 5 files
f409414 verified
Raw History Blame Contribute Delete
20.8 kB
// ============================================
// πŸ”₯ FIREBASE CONFIGURATION
// ============================================
// IMPORTANT: Replace the placeholder config below with your own Firebase config.
// Follow the instructions in firebase_setup.md to get your config.
// ============================================
const firebaseConfig = {
apiKey: "AIzaSyCX0LTwobIMY-E8uPKg5H0qw4icW5EQhKE",
authDomain: "officesanta-6441f.firebaseapp.com",
databaseURL: "https://officesanta-6441f-default-rtdb.asia-southeast1.firebasedatabase.app",
projectId: "officesanta-6441f",
storageBucket: "officesanta-6441f.firebasestorage.app",
messagingSenderId: "808912394412",
appId: "1:808912394412:web:bddea450897793b5d0a709",
measurementId: "G-B94PQMLYMD"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const database = firebase.database();
// ============================================
// πŸ—„οΈ STORAGE MODULE (Firebase Realtime Database)
// ============================================
const Storage = {
// --- Users ---
getUsers: async () => {
const snapshot = await database.ref('users').once('value');
const data = snapshot.val();
return data ? Object.values(data) : [];
},
setUsers: async (users) => {
// Store as an object keyed by name for easier access
const usersObj = {};
users.forEach(u => {
usersObj[u.name] = u;
});
await database.ref('users').set(usersObj);
},
getUser: async (name) => {
const snapshot = await database.ref(`users/${name}`).once('value');
return snapshot.val();
},
updateUser: async (name, data) => {
await database.ref(`users/${name}`).update(data);
},
// --- Game State ---
getGameState: async () => {
const snapshot = await database.ref('gameState').once('value');
return snapshot.val() || {
phase: 'interest',
endTime: null,
assignmentsGenerated: false
};
},
setGameState: async (state) => {
await database.ref('gameState').set(state);
},
// --- Preferences ---
getUserPrefs: async (username) => {
const snapshot = await database.ref(`preferences/${username}`).once('value');
return snapshot.val() || {};
},
setUserPrefs: async (username, prefs) => {
await database.ref(`preferences/${username}`).set(prefs);
},
// --- Clear All ---
clearAll: async () => {
await database.ref('/').remove();
}
};
// ============================================
// πŸ–₯️ DOM ELEMENTS
// ============================================
const DOM = {
loginSection: document.getElementById('login-section'),
adminSection: document.getElementById('admin-section'),
dashboardSection: document.getElementById('dashboard-section'),
// Login
loginForm: document.getElementById('login-form'),
usernameInput: document.getElementById('username'),
passwordInput: document.getElementById('password'),
errorMsg: document.getElementById('error-msg'),
// Admin
userList: document.getElementById('user-list'),
userCount: document.getElementById('user-count'),
newUserInput: document.getElementById('new-user-name'),
addUserBtn: document.getElementById('add-user-btn'),
userUpload: document.getElementById('user-upload'),
clearUsersBtn: document.getElementById('clear-users-btn'),
adminTimer: document.getElementById('admin-timer'),
startTimerBtn: document.getElementById('start-timer-btn'),
resetTimerBtn: document.getElementById('reset-timer-btn'),
generateBtn: document.getElementById('generate-btn'),
generationMsg: document.getElementById('generation-msg'),
adminLogoutBtn: document.getElementById('admin-logout-btn'),
// Dashboard
userDisplayName: document.getElementById('user-display-name'),
logoutBtn: document.getElementById('logout-btn'),
// Phases
interestPhase: document.getElementById('interest-phase'),
waitingPhase: document.getElementById('waiting-phase'),
revealPhase: document.getElementById('reveal-phase'),
// Interest Form
userTimer: document.getElementById('user-timer'),
preferencesForm: document.getElementById('preferences-form'),
saveMsg: document.getElementById('save-msg'),
// Reveal
giftBox: document.getElementById('gift-box'),
assignmentReveal: document.getElementById('assignment-reveal'),
gifteeName: document.getElementById('giftee-name'),
gifteeClues: document.getElementById('giftee-clues'),
cluesList: document.getElementById('clues-list'),
readOnlyPrefs: document.getElementById('read-only-prefs'),
// Tabs
tabBtns: document.querySelectorAll('.tab-btn'),
tabContents: document.querySelectorAll('.tab-content')
};
// ============================================
// 🧠 STATE
// ============================================
let currentUser = null;
let timerInterval = null;
// ============================================
// πŸš€ INITIALIZATION
// ============================================
async function init() {
await checkGameState();
setupEventListeners();
setupTabs();
createSnow();
}
async function checkGameState() {
const state = await Storage.getGameState();
updateTimerDisplay(state.endTime);
if (state.phase === 'interest' && state.endTime) {
startTimerInterval(state.endTime);
}
}
// ============================================
// πŸ“Œ EVENT LISTENERS
// ============================================
function setupEventListeners() {
DOM.loginForm.addEventListener('submit', handleLogin);
DOM.logoutBtn.addEventListener('click', handleLogout);
DOM.adminLogoutBtn.addEventListener('click', handleLogout);
DOM.addUserBtn.addEventListener('click', () => addUser(DOM.newUserInput.value));
DOM.userUpload.addEventListener('change', handleFileUpload);
DOM.clearUsersBtn.addEventListener('click', clearUsers);
DOM.startTimerBtn.addEventListener('click', startTimer);
DOM.resetTimerBtn.addEventListener('click', resetTimer);
DOM.generateBtn.addEventListener('click', generateAssignments);
DOM.preferencesForm.addEventListener('submit', savePreferences);
DOM.giftBox.addEventListener('click', revealGift);
document.getElementById('password-form').addEventListener('submit', handlePasswordChange);
}
// ============================================
// πŸ” LOGIN LOGIC
// ============================================
async function handleLogin(e) {
e.preventDefault();
const username = DOM.usernameInput.value.trim();
const password = DOM.passwordInput.value.trim();
// Admin Login
if (username === 'Admin' && password === 'Admin@2025') {
await loginAsAdmin();
return;
}
// User Login
const user = await Storage.getUser(username);
if (user) {
const validPassword = user.password
? user.password === password
: password === `${user.name}@2025`;
if (validPassword) {
if (!user.passwordChanged) {
currentUser = user;
showPasswordModal();
} else {
await loginAsUser(user);
}
} else {
showError('Invalid credentials.');
}
} else {
showError('User not found.');
}
}
function showPasswordModal() {
DOM.loginSection.classList.add('hidden');
document.getElementById('password-modal').classList.remove('hidden');
}
async function handlePasswordChange(e) {
e.preventDefault();
const newPwd = document.getElementById('new-password').value;
const confirmPwd = document.getElementById('confirm-password').value;
const errorDiv = document.getElementById('pwd-error');
if (newPwd !== confirmPwd) {
errorDiv.textContent = "Passwords do not match!";
errorDiv.classList.remove('hidden');
return;
}
await Storage.updateUser(currentUser.name, {
password: newPwd,
passwordChanged: true
});
document.getElementById('password-modal').classList.add('hidden');
const updatedUser = await Storage.getUser(currentUser.name);
await loginAsUser(updatedUser);
alert('Password updated successfully!');
}
async function loginAsAdmin() {
currentUser = { name: 'Admin', isAdmin: true };
DOM.loginSection.classList.add('hidden');
DOM.adminSection.classList.remove('hidden');
await renderUserList();
updateAdminControls();
}
async function loginAsUser(user) {
currentUser = user;
DOM.loginSection.classList.add('hidden');
DOM.dashboardSection.classList.remove('hidden');
DOM.userDisplayName.textContent = user.name;
await loadUserView();
}
function handleLogout() {
currentUser = null;
DOM.adminSection.classList.add('hidden');
DOM.dashboardSection.classList.add('hidden');
DOM.loginSection.classList.remove('hidden');
document.getElementById('password-modal').classList.add('hidden');
DOM.loginForm.reset();
DOM.errorMsg.classList.add('hidden');
}
// ============================================
// πŸ‘€ ADMIN LOGIC
// ============================================
async function addUser(name) {
if (!name) return;
name = name.trim();
const existingUser = await Storage.getUser(name);
if (existingUser) {
alert('User already exists!');
return;
}
const users = await Storage.getUsers();
users.push({ name: name, assignedTo: null, passwordChanged: false });
await Storage.setUsers(users);
DOM.newUserInput.value = '';
await renderUserList();
}
async function handleFileUpload(e) {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = async (event) => {
const lines = event.target.result.split(/\r\n|\n/);
let count = 0;
const users = await Storage.getUsers();
const existingNames = users.map(u => u.name.toLowerCase());
lines.forEach(line => {
const name = line.trim();
if (name && !existingNames.includes(name.toLowerCase())) {
users.push({ name: name, assignedTo: null, passwordChanged: false });
existingNames.push(name.toLowerCase());
count++;
}
});
await Storage.setUsers(users);
await renderUserList();
alert(`Added ${count} users.`);
DOM.userUpload.value = '';
};
reader.readAsText(file);
}
async function renderUserList() {
const users = await Storage.getUsers();
DOM.userList.innerHTML = users.map(u => `<li>${u.name}</li>`).join('');
DOM.userCount.textContent = users.length;
}
async function clearUsers() {
if (confirm('Are you sure? This will delete all users and assignments.')) {
await Storage.clearAll();
await renderUserList();
}
}
function updateAdminControls() {
DOM.generateBtn.disabled = false;
}
// ============================================
// ⏱️ TIMER LOGIC
// ============================================
async function startTimer() {
const minutes = 10;
const endTime = Date.now() + minutes * 60 * 1000;
const state = await Storage.getGameState();
state.phase = 'interest';
state.endTime = endTime;
await Storage.setGameState(state);
startTimerInterval(endTime);
}
async function resetTimer() {
const state = await Storage.getGameState();
state.endTime = null;
state.phase = 'interest';
await Storage.setGameState(state);
clearInterval(timerInterval);
DOM.adminTimer.textContent = "00:00";
if (DOM.userTimer) DOM.userTimer.textContent = "10:00";
}
function startTimerInterval(endTime) {
if (timerInterval) clearInterval(timerInterval);
timerInterval = setInterval(async () => {
const now = Date.now();
const diff = endTime - now;
if (diff <= 0) {
clearInterval(timerInterval);
await handleTimerFinished();
} else {
updateTimerDisplay(endTime);
}
}, 1000);
updateTimerDisplay(endTime);
}
function updateTimerDisplay(endTime) {
if (!endTime) return;
const now = Date.now();
const diff = Math.max(0, endTime - now);
const minutes = Math.floor(diff / 60000);
const seconds = Math.floor((diff % 60000) / 1000);
const display = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
if (DOM.adminTimer) DOM.adminTimer.textContent = display;
if (DOM.userTimer) DOM.userTimer.textContent = display;
}
async function handleTimerFinished() {
const state = await Storage.getGameState();
if (state.phase === 'interest') {
state.phase = 'waiting';
await Storage.setGameState(state);
if (currentUser && !currentUser.isAdmin) {
await loadUserView();
}
}
}
// ============================================
// 🎲 ASSIGNMENT LOGIC
// ============================================
async function generateAssignments() {
const users = await Storage.getUsers();
if (users.length < 2) {
alert('Need at least 2 users!');
return;
}
// Shuffle
for (let i = users.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[users[i], users[j]] = [users[j], users[i]];
}
// Assign in circle
for (let i = 0; i < users.length; i++) {
const receiverIndex = (i + 1) % users.length;
users[i].assignedTo = users[receiverIndex].name;
}
await Storage.setUsers(users);
const state = await Storage.getGameState();
state.phase = 'reveal';
state.assignmentsGenerated = true;
await Storage.setGameState(state);
DOM.generationMsg.classList.remove('hidden');
setTimeout(() => DOM.generationMsg.classList.add('hidden'), 3000);
}
// ============================================
// πŸ“‹ USER DASHBOARD LOGIC
// ============================================
async function loadUserView() {
const state = await Storage.getGameState();
DOM.interestPhase.classList.add('hidden');
DOM.waitingPhase.classList.add('hidden');
DOM.revealPhase.classList.add('hidden');
if (state.phase === 'interest') {
DOM.interestPhase.classList.remove('hidden');
await loadPreferences();
} else if (state.phase === 'waiting') {
DOM.waitingPhase.classList.remove('hidden');
} else if (state.phase === 'reveal') {
DOM.revealPhase.classList.remove('hidden');
await loadReadOnlyPrefs();
DOM.giftBox.classList.remove('hidden');
DOM.assignmentReveal.classList.add('hidden');
DOM.giftBox.classList.remove('gift-open');
}
}
async function loadPreferences() {
const prefs = await Storage.getUserPrefs(currentUser.name);
document.getElementById('likes').value = prefs.likes || '';
document.getElementById('dislikes').value = prefs.dislikes || '';
document.getElementById('shirt-size').value = prefs.shirtSize || '';
document.getElementById('wishlist').value = prefs.wishlist || '';
}
async function savePreferences(e) {
e.preventDefault();
const prefs = {
likes: document.getElementById('likes').value,
dislikes: document.getElementById('dislikes').value,
shirtSize: document.getElementById('shirt-size').value,
wishlist: document.getElementById('wishlist').value
};
await Storage.setUserPrefs(currentUser.name, prefs);
DOM.saveMsg.classList.remove('hidden');
setTimeout(() => DOM.saveMsg.classList.add('hidden'), 2000);
}
async function loadReadOnlyPrefs() {
const prefs = await Storage.getUserPrefs(currentUser.name);
DOM.readOnlyPrefs.innerHTML = `
<p><strong>Likes:</strong> ${prefs.likes || '-'}</p>
<p><strong>Dislikes:</strong> ${prefs.dislikes || '-'}</p>
<p><strong>Shirt Size:</strong> ${prefs.shirtSize || '-'}</p>
<p><strong>Wishlist:</strong> ${prefs.wishlist || '-'}</p>
`;
}
async function revealGift() {
const freshUser = await Storage.getUser(currentUser.name);
if (!freshUser || !freshUser.assignedTo) {
alert('Error: No assignment found. Contact Admin.');
return;
}
DOM.giftBox.classList.add('gift-open');
setTimeout(async () => {
DOM.giftBox.classList.add('hidden');
DOM.assignmentReveal.classList.remove('hidden');
DOM.gifteeName.textContent = freshUser.assignedTo;
await displayGifteeClues(freshUser.assignedTo);
fireConfetti();
}, 500);
}
async function displayGifteeClues(gifteeName) {
const prefs = await Storage.getUserPrefs(gifteeName);
DOM.cluesList.innerHTML = '';
const items = [
{ label: 'Likes', val: prefs.likes },
{ label: 'Dislikes', val: prefs.dislikes },
{ label: 'Shirt Size', val: prefs.shirtSize },
{ label: 'Wishlist', val: prefs.wishlist }
];
let hasClues = false;
items.forEach(item => {
if (item.val) {
DOM.cluesList.innerHTML += `<li><strong>${item.label}:</strong> ${item.val}</li>`;
hasClues = true;
}
});
if (hasClues) {
DOM.gifteeClues.classList.remove('hidden');
} else {
DOM.cluesList.innerHTML = '<li><em>They haven\'t filled out their preferences yet!</em> πŸ€·β€β™‚οΈ</li>';
DOM.gifteeClues.classList.remove('hidden');
}
}
// ============================================
// πŸ› οΈ UTILITIES
// ============================================
function showError(msg) {
DOM.errorMsg.textContent = msg;
DOM.errorMsg.classList.remove('hidden');
DOM.loginSection.classList.add('shake');
setTimeout(() => DOM.loginSection.classList.remove('shake'), 500);
}
function setupTabs() {
DOM.tabBtns.forEach(btn => {
btn.addEventListener('click', () => {
DOM.tabBtns.forEach(b => b.classList.remove('active'));
DOM.tabContents.forEach(c => c.classList.remove('active'));
btn.classList.add('active');
document.getElementById(btn.dataset.tab).classList.add('active');
});
});
}
function createSnow() {
const snowContainer = document.getElementById('snow-container');
for (let i = 0; i < 50; i++) {
const snowflake = document.createElement('div');
snowflake.classList.add('snowflake');
snowflake.style.left = Math.random() * 100 + 'vw';
snowflake.style.animationDuration = Math.random() * 3 + 2 + 's';
snowflake.style.opacity = Math.random();
snowflake.style.width = snowflake.style.height = Math.random() * 5 + 2 + 'px';
snowContainer.appendChild(snowflake);
}
}
function fireConfetti() {
const canvas = document.getElementById('confetti-canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const particles = [];
const colors = ['#D42426', '#165B33', '#F8B229', '#FFFFFF'];
for (let i = 0; i < 150; i++) {
particles.push({
x: window.innerWidth / 2,
y: window.innerHeight / 2,
w: Math.random() * 10 + 5,
h: Math.random() * 10 + 5,
color: colors[Math.floor(Math.random() * colors.length)],
vx: (Math.random() - 0.5) * 20,
vy: (Math.random() - 0.5) * 20 - 5,
gravity: 0.5,
rotation: Math.random() * 360
});
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
let active = false;
particles.forEach(p => {
p.x += p.vx;
p.y += p.vy;
p.vy += p.gravity;
if (p.y < window.innerHeight) {
active = true;
ctx.fillStyle = p.color;
ctx.fillRect(p.x, p.y, p.w, p.h);
}
});
if (active) requestAnimationFrame(animate);
}
animate();
}
// ============================================
// 🎬 START
// ============================================
init();