Spaces:
Runtime error
Runtime error
File size: 25,074 Bytes
b6aabbb c359d3c 1495155 c359d3c 043cba6 c359d3c 043cba6 c359d3c 043cba6 c359d3c 1495155 c359d3c 043cba6 c359d3c b6aabbb c359d3c b930736 b6aabbb b930736 f2d5457 c359d3c b930736 c359d3c b930736 c359d3c b930736 c359d3c f2d5457 b6aabbb f2d5457 b6aabbb f2d5457 b6aabbb f2d5457 b6aabbb f2d5457 b6aabbb f2d5457 b6aabbb af0efc6 b6aabbb 834213e b6aabbb 834213e b6aabbb 834213e b6aabbb 004b0e5 b6aabbb 20dab02 a8e7134 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 |
// Helper function to sanitize religion names for IDs
function sanitizeReligionName(name) {
return name.replace(/\s+/g, '-');
}
// ==================== FIREBASE AUTHENTICATION ====================
// Google Sign-In with Firebase
async function signInWithGoogle() {
if (!window.firebaseEnabled || !window.firebaseAuth) {
const resultDiv = document.getElementById('result');
if (resultDiv) {
resultDiv.innerHTML = '<p class="error-msg">⚠️ Firebase not configured</p>';
}
return;
}
const provider = new firebase.auth.GoogleAuthProvider();
// Configure provider for better popup behavior
provider.setCustomParameters({
prompt: 'select_account' // Always show account selection
});
try {
// Show loading state
const resultDiv = document.getElementById('result');
if (resultDiv) {
resultDiv.innerHTML = '<p style="color: #666;">Opening sign-in window...</p>';
}
const result = await window.firebaseAuth.signInWithPopup(provider);
const user = result.user;
if (resultDiv) {
resultDiv.innerHTML = '<p style="color: #666;">Signing in...</p>';
}
// Get ID token to send to backend
const idToken = await user.getIdToken();
// Send to backend for session creation
const endpoint = window.location.pathname === '/signup' ? '/signup' : '/login';
const response = await fetch(endpoint, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({idToken}),
credentials: 'same-origin'
});
const data = await response.json();
if (data.success) {
window.location.href = '/assessment';
} else {
const resultDiv = document.getElementById('result');
if (resultDiv) {
resultDiv.innerHTML = `<p class="error-msg">${data.message || 'Authentication failed'}</p>`;
}
}
} catch (error) {
console.error('Google Sign-In Error:', error);
console.error('Error code:', error.code);
console.error('Error details:', error);
const resultDiv = document.getElementById('result');
let errorMsg = '';
// Handle specific error cases
if (error.code === 'auth/popup-closed-by-user') {
errorMsg = '❌ Sign-in window was closed. Please try again and complete the sign-in process.';
} else if (error.code === 'auth/popup-blocked') {
errorMsg = '❌ Pop-up was blocked by your browser. Please allow pop-ups for this site and try again.';
} else if (error.code === 'auth/cancelled-popup-request') {
errorMsg = '❌ Another sign-in is in progress. Please wait a moment and try again.';
} else if (error.code === 'auth/unauthorized-domain') {
errorMsg = '❌ This domain is not authorized for Google Sign-In. Please contact the administrator.';
} else if (error.code === 'auth/operation-not-allowed') {
errorMsg = '❌ Google Sign-In is not enabled. Please contact the administrator.';
} else if (error.code === 'auth/network-request-failed') {
errorMsg = '❌ Network error. Please check your internet connection and try again.';
} else {
errorMsg = `❌ ${error.message || 'Google Sign-In failed. Please try again.'}`;
}
if (resultDiv) {
resultDiv.innerHTML = `<p class="error-msg">${errorMsg}</p>`;
}
}
}
// Firebase Email/Password Authentication
async function authenticateWithFirebase(email, password, isSignup) {
if (!window.firebaseEnabled || !window.firebaseAuth) {
return null; // Fall back to legacy auth
}
try {
let userCredential;
if (isSignup) {
// Create new user with Firebase
userCredential = await window.firebaseAuth.createUserWithEmailAndPassword(email, password);
// Send email verification
await userCredential.user.sendEmailVerification();
} else {
// Sign in existing user
userCredential = await window.firebaseAuth.signInWithEmailAndPassword(email, password);
// Check if email is verified
if (!userCredential.user.emailVerified) {
document.getElementById('result').innerHTML =
'<p class="error-msg">⚠️ Please verify your email first. Check your inbox.</p>';
await window.firebaseAuth.signOut();
return null;
}
}
// Get ID token
const idToken = await userCredential.user.getIdToken();
return idToken;
} catch (error) {
console.error('Firebase Auth Error:', error);
throw error;
}
}
// ==================== AUTHENTICATION ====================
async function authenticate() {
const email = document.getElementById('authEmail').value.trim();
const username = document.getElementById('authUsername') ? document.getElementById('authUsername').value.trim() : '';
const password = document.getElementById('authPassword').value;
if (!email || !password) {
document.getElementById('result').innerHTML =
'<p class="error-msg">⚠️ Please fill in all fields</p>';
return;
}
const isSignup = window.location.pathname === '/signup';
const endpoint = isSignup ? '/signup' : '/login';
// Try Firebase authentication first if available
if (window.firebaseEnabled) {
try {
const idToken = await authenticateWithFirebase(email, password, isSignup);
if (!idToken) {
return; // Error already displayed
}
// Send token to backend
const response = await fetch(endpoint, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({idToken}),
credentials: 'same-origin'
});
const data = await response.json();
if (data.success) {
if (isSignup) {
document.getElementById('result').innerHTML =
'<p class="success-msg">✅ Account created! Please check your email to verify.</p>';
} else {
window.location.href = '/assessment';
}
} else {
document.getElementById('result').innerHTML =
`<p class="error-msg">${data.message || 'Authentication failed'}</p>`;
}
return;
} catch (error) {
console.error('Firebase auth error:', error);
document.getElementById('result').innerHTML =
`<p class="error-msg">${error.message || 'Authentication failed'}</p>`;
return;
}
}
// Legacy authentication fallback (if Firebase is disabled)
const body = isSignup
? {username, password, email}
: {username, password};
fetch(endpoint, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(body),
credentials: 'same-origin'
})
.then(response => {
if (!response.ok) {
return response.json().then(err => Promise.reject(err));
}
return response.json();
})
.then(data => {
if (data.success) {
if (data.verification_sent) {
document.getElementById('result').innerHTML =
'<p class="success-msg">✅ ' + (data.message || 'Account created! Please check your email to verify.') + '</p>';
} else {
window.location.href = '/assessment';
}
} else {
document.getElementById('result').innerHTML =
`<p class="error-msg">${data.message || 'Authentication failed'}</p>`;
}
})
.catch(error => {
document.getElementById('result').innerHTML =
`<p class="error-msg">${error.message || 'Network error. Please try again.'}</p>`;
});
}
function switchAuth() {
const newPath = window.location.pathname === '/signup' ? '/login' : '/signup';
window.location.href = newPath;
}
function resetPassword() {
const email = document.getElementById('resetEmail').value.trim();
if (!email) {
document.getElementById('result').innerHTML =
'<p class="error-msg">⚠️ Please enter your email</p>';
return;
}
fetch('/forgot-password', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({email}),
credentials: 'same-origin'
})
.then(response => {
if (!response.ok) {
return response.json().then(err => Promise.reject(err));
}
return response.json();
})
.then(data => {
if (data.success) {
document.getElementById('result').innerHTML =
'<p class="success-msg">✅ Password reset link sent! Check your email (or server console in dev mode).</p>';
} else {
document.getElementById('result').innerHTML =
`<p class="error-msg">${data.message || 'Failed to send reset link'}</p>`;
}
})
.catch(error => {
document.getElementById('result').innerHTML =
`<p class="error-msg">${error.message || 'Network error. Please try again.'}</p>`;
});
}
function submitPasswordReset() {
const token = document.getElementById('resetToken').value;
const password = document.getElementById('resetPassword').value;
if (!password) {
document.getElementById('result').innerHTML =
'<p class="error-msg">⚠️ Please enter a new password</p>';
return;
}
fetch('/reset-password-submit', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({token, password}),
credentials: 'same-origin'
})
.then(response => {
if (!response.ok) {
return response.json().then(err => Promise.reject(err));
}
return response.json();
})
.then(data => {
if (data.success) {
document.getElementById('result').innerHTML =
'<p class="success-msg">✅ Password reset successfully! Redirecting to login...</p>';
setTimeout(() => window.location.href = '/login', 1500);
} else {
document.getElementById('result').innerHTML =
`<p class="error-msg">${data.message || 'Failed to reset password'}</p>`;
}
})
.catch(error => {
document.getElementById('result').innerHTML =
`<p class="error-msg">${error.message || 'Network error. Please try again.'}</p>`;
});
}
// ==================== ASSESSMENT ====================
var currentQuestion = 1;
var maxQuestionReached = 1;
var assessmentDataEl = document.getElementById('assessmentData');
var totalQuestions = assessmentDataEl ? parseInt(assessmentDataEl.getAttribute('data-total')) : 0;
var questionIds = assessmentDataEl ? JSON.parse(assessmentDataEl.getAttribute('data-ids')) : [];
// Show first question on load
window.addEventListener('DOMContentLoaded', function() {
if (assessmentDataEl) {
showQuestion(1);
}
// Add Enter key listener for password field if it exists
const passwordField = document.getElementById('authPassword');
if (passwordField) {
passwordField.addEventListener('keypress', function(e) {
if (e.key === 'Enter') authenticate();
});
}
});
function showQuestion(questionIndex) {
if (questionIndex > maxQuestionReached + 1) return;
if (questionIndex > maxQuestionReached) maxQuestionReached = questionIndex;
document.querySelectorAll('.question-block').forEach(function(block) {
block.classList.remove('active');
var blockIndex = parseInt(block.getAttribute('data-question-index'));
if (blockIndex === questionIndex) block.classList.add('active');
});
currentQuestion = questionIndex;
document.getElementById('questionCounter').textContent = 'Question ' + questionIndex + ' of ' + totalQuestions;
document.getElementById('progressBar').style.width = ((questionIndex - 1) / (totalQuestions - 1)) * 100 + '%';
updateNavigationButtons();
}
function updateNavigationButtons() {
// Check if we're on the last question and it's answered
var currentQuestionId = questionIds[currentQuestion - 1];
var radioName = 'q' + currentQuestionId;
var isAnswered = document.querySelector('input[name="' + radioName + '"]:checked') !== null;
if (currentQuestion === totalQuestions && isAnswered) {
document.getElementById('submitBtn').style.display = 'block';
}
}
function handleAnswer(radioElement) {
var questionIndex = parseInt(radioElement.getAttribute('data-question-index'));
// Only process if this is the current question
if (questionIndex !== currentQuestion) {
return;
}
// Auto-advance to next question after selection
setTimeout(function() {
if (questionIndex < totalQuestions) {
showQuestion(questionIndex + 1);
} else {
// Last question - show submit button
document.getElementById('submitBtn').style.display = 'block';
}
}, 400);
}
function goToNext() {
if (currentQuestion < totalQuestions) {
showQuestion(currentQuestion + 1);
}
}
function goToPrev() {
if (currentQuestion > 1) {
showQuestion(currentQuestion - 1);
}
}
function submitAssessment() {
var form = document.getElementById('assessmentForm');
var answers = [];
questionIds.forEach(function(qId) {
var radioName = 'q' + qId;
var selectedRadio = form.querySelector('input[name="' + radioName + '"]:checked');
if (selectedRadio) {
answers.push({
question_id: qId,
answer: selectedRadio.value
});
}
});
if (answers.length !== totalQuestions) {
document.getElementById('errorMsg').innerHTML =
'<p class="error-msg">⚠️ Please answer all questions</p>';
return;
}
document.getElementById('submitBtn').disabled = true;
document.getElementById('submitBtn').textContent = '✨ Calculating...';
fetch('/submit_assessment', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({answers: answers})
})
.then(function(response) { return response.json(); })
.then(function(data) {
if (data.success) {
window.location.reload();
} else {
document.getElementById('errorMsg').innerHTML =
'<p class="error-msg">' + data.message + '</p>';
document.getElementById('submitBtn').disabled = false;
document.getElementById('submitBtn').textContent = '✨ Discover Your Path';
}
});
}
function resetAssessment() {
if (!confirm('Are you sure you want to retake the assessment? Your current results will be cleared.')) {
return;
}
fetch('/reset_assessment', {
method: 'POST',
headers: {'Content-Type': 'application/json'}
})
.then(function(response) { return response.json(); })
.then(function(data) {
if (data.success) {
window.location.reload();
}
});
}
// ==================== SHARE RESULTS ====================
function shareResults() {
const results = getResultsSummary();
const text = `My Spiritual Path Results:\n\n${results}\n\nTake the assessment: ${window.location.origin}`;
if (navigator.share) {
navigator.share({ title: 'Spiritual Path Results', text: text });
} else {
navigator.clipboard.writeText(text);
alert('Results copied to clipboard!');
}
}
function getResultsSummary() {
const cards = document.querySelectorAll('.result-card');
return Array.from(cards).map((card, i) => {
const title = card.querySelector('h3').textContent;
const percentage = card.querySelector('.result-percentage').textContent;
return `${i+1}. ${title} (${percentage})`;
}).join('\n');
}
// ==================== CHAT FUNCTIONALITY ====================
var chatHistories = {};
function formatBotResponse(text) {
var div = document.createElement('div');
div.textContent = text;
var escaped = div.innerHTML;
// Check for bullet points
if (escaped.match(/\*\s+/g) || escaped.match(/•\s+/g) || escaped.match(/^\s*-\s+/gm)) {
var lines = escaped.split(/(?:\*|•|\n-)\s+/);
if (lines.length > 1) {
var formatted = lines[0].trim() ? lines[0].trim() + '<br><br>' : '';
formatted += '<ul style="margin: 0; padding-left: 20px; line-height: 1.8;">';
for (var i = 1; i < lines.length; i++) {
if (lines[i].trim()) {
formatted += '<li style="margin-bottom: 6px;">' + lines[i].trim() + '</li>';
}
}
return formatted + '</ul>';
}
}
return escaped.replace(/\n/g, '<br>');
}
function toggleChat(religionName) {
var chatId = 'chat-' + sanitizeReligionName(religionName);
var chatWindow = document.getElementById(chatId);
if (chatWindow.classList.contains('open')) {
chatWindow.classList.remove('open');
} else {
chatWindow.classList.add('open');
var inputId = 'input-' + sanitizeReligionName(religionName);
setTimeout(function() {
document.getElementById(inputId).focus();
}, 300);
}
}
function sendMessage(religionName) {
var inputId = 'input-' + sanitizeReligionName(religionName);
var messagesId = 'messages-' + sanitizeReligionName(religionName);
var sendBtnId = 'send-' + sanitizeReligionName(religionName);
var inputEl = document.getElementById(inputId);
var messagesEl = document.getElementById(messagesId);
var sendBtn = document.getElementById(sendBtnId);
var message = inputEl.value.trim();
if (!message) return;
// Initialize chat history if not exists
if (!chatHistories[religionName]) {
chatHistories[religionName] = [];
}
// Add user message to UI
var userMsgDiv = document.createElement('div');
userMsgDiv.className = 'chat-message user';
userMsgDiv.textContent = message;
messagesEl.appendChild(userMsgDiv);
// Clear input and disable send button
inputEl.value = '';
sendBtn.disabled = true;
// Show typing indicator
var typingDiv = document.createElement('div');
typingDiv.className = 'chat-typing';
typingDiv.textContent = '💭 Thinking...';
messagesEl.appendChild(typingDiv);
// Scroll to bottom
messagesEl.scrollTop = messagesEl.scrollHeight;
// Add to chat history
chatHistories[religionName].push({
role: 'user',
content: message
});
// Send to backend
fetch('/chat', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
message: message,
religion: religionName,
history: chatHistories[religionName]
})
})
.then(function(response) { return response.json(); })
.then(function(data) {
messagesEl.removeChild(typingDiv);
if (data.success) {
var botMsgDiv = document.createElement('div');
botMsgDiv.className = 'chat-message bot';
// Format the response with proper bullet points
var formattedResponse = formatBotResponse(data.response);
botMsgDiv.innerHTML = formattedResponse;
messagesEl.appendChild(botMsgDiv);
chatHistories[religionName].push({
role: 'assistant',
content: data.response
});
} else {
var errorMsgDiv = document.createElement('div');
errorMsgDiv.className = 'chat-message bot';
errorMsgDiv.style.color = '#EF4444';
errorMsgDiv.textContent = '❌ ' + data.message;
messagesEl.appendChild(errorMsgDiv);
}
sendBtn.disabled = false;
messagesEl.scrollTop = messagesEl.scrollHeight;
})
.catch(function(error) {
messagesEl.removeChild(typingDiv);
var errorMsgDiv = document.createElement('div');
errorMsgDiv.className = 'chat-message bot';
errorMsgDiv.style.color = '#EF4444';
errorMsgDiv.textContent = '❌ Connection error';
messagesEl.appendChild(errorMsgDiv);
sendBtn.disabled = false;
messagesEl.scrollTop = messagesEl.scrollHeight;
});
}
// ==================== VOICE CHAT ====================
var recognition = null;
var currentReligion = null;
var isRecording = false;
function initializeSpeechRecognition() {
if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
recognition.continuous = true;
recognition.interimResults = true;
recognition.lang = 'en-US';
recognition.onresult = function(event) {
var interimTranscript = '';
var finalTranscript = '';
for (var i = event.resultIndex; i < event.results.length; i++) {
var transcript = event.results[i][0].transcript;
if (event.results[i].isFinal) {
finalTranscript += transcript + ' ';
} else {
interimTranscript += transcript;
}
}
// Update input field with live transcription
if (currentReligion) {
var inputId = 'input-' + sanitizeReligionName(currentReligion);
var inputEl = document.getElementById(inputId);
if (inputEl) {
inputEl.value = finalTranscript + interimTranscript;
}
}
};
recognition.onerror = function(event) {
console.error('Speech recognition error:', event.error);
if (event.error === 'no-speech') {
stopVoiceInput();
}
};
recognition.onend = function() {
if (isRecording) {
// Restart if it stopped unexpectedly
try {
recognition.start();
} catch(e) {
stopVoiceInput();
}
}
};
}
}
function startVoiceInput(religionName) {
if (!recognition) {
alert('Speech recognition not supported in your browser');
return;
}
currentReligion = religionName;
isRecording = true;
try {
recognition.start();
document.getElementById('voice-' + sanitizeReligionName(religionName)).classList.add('recording');
} catch(e) {
console.log('Already started or error:', e);
}
}
function stopVoiceInput(religionName) {
if (recognition && isRecording) {
isRecording = false;
recognition.stop();
document.getElementById('voice-' + sanitizeReligionName(religionName)).classList.remove('recording');
}
}
// Initialize on page load
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initializeSpeechRecognition);
} else {
initializeSpeechRecognition();
}
// Make tooltips appear instantly on hover
document.addEventListener('DOMContentLoaded', function() {
const micButtons = document.querySelectorAll('button[title]');
micButtons.forEach(button => {
const tooltipText = button.getAttribute('title');
button.removeAttribute('title'); // Remove native tooltip
// Create custom tooltip element
const tooltip = document.createElement('div');
tooltip.className = 'custom-tooltip';
tooltip.textContent = tooltipText;
// Add tooltip to button
button.style.position = 'relative';
button.appendChild(tooltip);
button.addEventListener('mouseenter', function() {
tooltip.style.opacity = '1';
});
button.addEventListener('mouseleave', function() {
tooltip.style.opacity = '0';
});
});
});
|