// βaspirin Digital Mental Health Platform - Main Application Logic // --- BACKEND API URL --- const SCRIPT_URL = 'https://docs.google.com/spreadsheets/d/1RcmdlpLuQfHahgw7zy-25VZ5FjJF5R5lxcMphBBeoT4/edit?usp=sharing'; // Keep this for registration for now const API_BASE_URL = 'http://127.0.0.1:5000/v1'; const API_ENDPOINTS = { predict: `${API_BASE_URL}/predict`, login: `${API_BASE_URL}/login`, register: `${API_BASE_URL}/register`, history: `${API_BASE_URL}/history`, userStats: `${API_BASE_URL}/user-stats`, health: `${API_BASE_URL}/health`, testScenarios: `${API_BASE_URL}/test-scenarios` }; // --- ENHANCED CHAT VARIABLES --- let messageCount = 0; let isTyping = false; let conversationHistory = []; let lastMessageTime = 0; // --- TRANSLATIONS --- const translations = { en: { login: "Student Login", register: "Register", welcome_title: "Welcome to βaspirin", welcome_subtitle: "Your Digital Mental Health Support System", take_assessment: "Take Assessment", assessment_description: "Complete PHQ-9 and GAD-7 screenings to understand your mental health", ai_support_chat: "AI Support Chat", chat_description: "Get immediate support and coping strategies from our AI assistant", resource_library: "Resource Library", resources_description: "Access CBT modules, mindfulness practices, and educational content", book_appointment: "Book Appointment", booking_description: "Schedule sessions with qualified counselors and therapists", my_dashboard: "My Dashboard", dashboard_description: "Track your progress and view your mental health journey", admin_panel: "Admin Panel", admin_description: "Institutional analytics and monitoring (Demo)", back_to_home: "← Back to Home", register_title: "Create Student Account", full_name: "Full Name", email_address: "Email Address", select_college: "Select College", password: "Password", assessment_title: "Mental Health Assessment", assessment_subtitle: "Complete the PHQ-9 and GAD-7 questionnaires to get personalized insights", phq9_title: "PHQ-9 Depression Screening", phq9_description: "9 questions about depression symptoms over the past 2 weeks", start_phq9: "Start PHQ-9", gad7_title: "GAD-7 Anxiety Screening", gad7_description: "7 questions about anxiety symptoms over the past 2 weeks", start_gad7: "Start GAD-7", question: "Question", previous: "Previous", next: "Next", results_title: "Your Assessment Results", recommendations_title: "Personalized Recommendations", talk_to_ai: "Talk to AI Support", explore_resources: "Explore Resources", retake_assessment: "Take Another Assessment", ai_assistant_title: "AI Support Assistant", ai_assistant_subtitle: "Get immediate support and guidance. I'm here to help 24/7.", chat_welcome: "Hello! I'm your AI mental health assistant. How are you feeling today? I'm here to provide support and resources.", crisis_detected: "Crisis Detected:", crisis_message: "I'm very concerned about what you've shared. Please reach out for immediate help:", contact_helpline: "Contact Crisis Helpline", find_counselor: "Find Counselor", send: "Send", feeling_anxious: "I'm feeling anxious", cant_sleep: "I can't sleep", exam_stress: "I'm stressed about exams", feeling_lonely: "I feel lonely", resource_library_title: "Resource Library", resource_library_subtitle: "Access educational content, exercises, and tools for mental wellness", booking_title: "Book Appointment", booking_subtitle: "Schedule a session with our qualified mental health professionals", select_counselor: "Select a Counselor", select_date_time: "Select Date & Time", select_appointment_type: "Select Appointment Type", individual_session: "Individual Session", individual_session_desc: "One-on-one counseling session (50 minutes)", group_session: "Group Session", group_session_desc: "Group therapy session (60 minutes)", crisis_intervention: "Crisis Intervention", crisis_intervention_desc: "Immediate support (30 minutes)", confirm_appointment: "Confirm Appointment", counselor: "Counselor", date: "Date", time: "Time", type: "Type", confirm_booking_btn: "Confirm Appointment", my_dashboard_title: "My Dashboard", my_dashboard_subtitle: "Track your mental health journey and progress", mood_tracking: "Mood Tracking", assessment_history: "Assessment History", recent_activities: "Recent Activities", today: "Today", activity1: "Completed PHQ-9 assessment", yesterday: "Yesterday", activity2: "Used breathing exercise", "2_days_ago": "2 days ago", activity3: "Booked appointment with Dr. Johnson", quick_actions: "Quick Actions", chat_support: "Chat Support", book_session: "Book Session", admin_dashboard_title: "Admin Dashboard", admin_dashboard_subtitle: "Institutional analytics and monitoring (Demo)", total_students: "Total Students", active_users: "Active Users", crisis_alerts: "Crisis Alerts", appointments: "Appointments", usage_analytics: "Usage Analytics", risk_level_distribution: "Risk Level Distribution", crisis_monitoring: "Crisis Monitoring", medium_priority: "Medium Priority:", medium_priority_desc: "Student ID #STU456 - Elevated anxiety scores", high_priority: "High Priority:", high_priority_desc: "Crisis keywords detected in chat - Student ID #STU789", success: "Success!", booking_success_message: "Your appointment has been booked successfully.", registration_success_message: "Your account has been created. Your unique Student ID is:", close: "Close", student_login: "Student Login", student_id: "Student ID", }, hi: { login: "छात्र लॉगिन", register: "पंजीकरण करें", welcome_title: "βaspirin में आपका स्वागत है", welcome_subtitle: "आपकी डिजिटल मानसिक स्वास्थ्य सहायता प्रणाली", take_assessment: "आकलन करें", assessment_description: "अपने मानसिक स्वास्थ्य को समझने के लिए PHQ-9 और GAD-7 स्क्रीनिंग पूरी करें", ai_support_chat: "एआई सहायता चैट", chat_description: "हमारे एआई सहायक से तत्काल सहायता और मुकाबला करने की रणनीतियाँ प्राप्त करें", resource_library: "संसाधन पुस्तकालय", resources_description: "सीबीटी मॉड्यूल, माइंडफुलनेस अभ्यास और शैक्षिक सामग्री तक पहुँचें", book_appointment: "अपॉइंटमेंट बुक करें", booking_description: "योग्य सलाहकारों और चिकित्सकों के साथ सत्र निर्धारित करें", my_dashboard: "मेरा डैशबोर्ड", dashboard_description: "अपनी प्रगति को ट्रैक करें और अपनी मानसिक स्वास्थ्य यात्रा देखें", admin_panel: "एडमिन पैनल", admin_description: "संस्थागत विश्लेषण और निगरानी (डेमो)", back_to_home: "← होम पर वापस जाएं", register_title: "छात्र खाता बनाएं", full_name: "पूरा नाम", email_address: "ईमेल पता", select_college: "कॉलेज चुनें", password: "पासवर्ड", assessment_title: "मानसिक स्वास्थ्य मूल्यांकन", assessment_subtitle: "व्यक्तिगत जानकारी प्राप्त करने के लिए PHQ-9 और GAD-7 प्रश्नावली पूरी करें", phq9_title: "PHQ-9 अवसाद स्क्रीनिंग", phq9_description: "पिछले 2 हफ्तों में अवसाद के लक्षणों के बारे में 9 प्रश्न", start_phq9: "PHQ-9 शुरू करें", gad7_title: "GAD-7 चिंता स्क्रीनिंग", gad7_description: "पिछले 2 हफ्तों में चिंता के लक्षणों के बारे में 7 प्रश्न", start_gad7: "GAD-7 शुरू करें", question: "प्रश्न", previous: "पिछला", next: "अगला", results_title: "आपके मूल्यांकन के परिणाम", recommendations_title: "व्यक्तिगत सिफारिशें", talk_to_ai: "एआई सहायता से बात करें", explore_resources: "संसाधन खोजें", retake_assessment: "एक और मूल्यांकन करें", ai_assistant_title: "एआई सहायता सहायक", ai_assistant_subtitle: "तत्काल सहायता और मार्गदर्शन प्राप्त करें। मैं 24/7 मदद के लिए यहाँ हूँ।", chat_welcome: "नमस्ते! मैं आपका एआई मानसिक स्वास्थ्य सहायक हूँ। आज आप कैसा महसूस कर रहे हैं? मैं सहायता और संसाधन प्रदान करने के लिए यहाँ हूँ।", crisis_detected: "संकट का पता चला:", crisis_message: "आपने जो साझा किया है, उसके बारे में मैं बहुत चिंतित हूँ। कृपया तत्काल मदद के लिए संपर्क करें:", contact_helpline: "संकट हेल्पलाइन से संपर्क करें", find_counselor: "परामर्शदाता खोजें", send: "भेजें", feeling_anxious: "मुझे चिंता हो रही है", cant_sleep: "मुझे नींद नहीं आ रही है", exam_stress: "मैं परीक्षाओं को लेकर तनाव में हूँ", feeling_lonely: "मुझे अकेलापन महसूस हो रहा है", resource_library_title: "संसाधन पुस्तकालय", resource_library_subtitle: "मानसिक कल्याण के लिए शैक्षिक सामग्री, व्यायाम और उपकरणों तक पहुँचें", booking_title: "अपॉइंटमेंट बुक करें", booking_subtitle: "हमारे योग्य मानसिक स्वास्थ्य पेशेवरों के साथ एक सत्र निर्धारित करें", select_counselor: "एक परामर्शदाता चुनें", select_date_time: "दिनांक और समय चुनें", select_appointment_type: "अपॉइंटमेंट का प्रकार चुनें", individual_session: "व्यक्तिगत सत्र", individual_session_desc: "एक-एक परामर्श सत्र (50 मिनट)", group_session: "समूह सत्र", group_session_desc: "समूह चिकित्सा सत्र (60 मिनट)", crisis_intervention: "संकट हस्तक्षेप", crisis_intervention_desc: "तत्काल सहायता (30 मिनट)", confirm_appointment: "अपॉइंटमेंट की पुष्टि करें", counselor: "परामर्शदाता", date: "दिनांक", time: "समय", type: "प्रकार", confirm_booking_btn: "अपॉइंटमेंट की पुष्टि करें", my_dashboard_title: "मेरा डैशबोर्ड", my_dashboard_subtitle: "अपनी मानसिक स्वास्थ्य यात्रा और प्रगति को ट्रैक करें", mood_tracking: "मूड ट्रैकिंग", assessment_history: "मूल्यांकन इतिहास", recent_activities: "हाल की गतिविधियाँ", today: "आज", activity1: "PHQ-9 मूल्यांकन पूरा किया", yesterday: "कल", activity2: "साँस लेने का व्यायाम इस्तेमाल किया", "2_days_ago": "2 दिन पहले", activity3: "डॉ. जॉनसन के साथ अपॉइंटमेंट बुक किया", quick_actions: "त्वरित कार्रवाइयां", chat_support: "चैट सहायता", book_session: "सत्र बुक करें", admin_dashboard_title: "एडमिन डैशबोर्ड", admin_dashboard_subtitle: "संस्थागत विश्लेषण और निगरानी (डेमो)", total_students: "कुल छात्र", active_users: "सक्रिय उपयोगकर्ता", crisis_alerts: "संकट अलर्ट", appointments: "अपॉइंटमेंट", usage_analytics: "उपयोग विश्लेषण", risk_level_distribution: "जोखिम स्तर वितरण", crisis_monitoring: "संकट की निगरानी", medium_priority: "मध्यम प्राथमिकता:", medium_priority_desc: "छात्र आईडी #STU456 - चिंता के अंक बढे", high_priority: "उच्च प्राथमिकता:", high_priority_desc: "चैट में संकट कीवर्ड का पता चला - छात्र आईडी #STU789", success: "सफलता!", booking_success_message: "आपका अपॉइंटमेंट सफलतापूर्वक बुक हो गया है।", registration_success_message: "आपका खाता बन गया है। आपकी विशिष्ट छात्र आईडी है:", close: "बंद करें", student_login: "छात्र लॉगिन", student_id: "छात्र आईडी", } }; // ─── Place this just below your `translations` constant ─── const CATEGORY_LABELS = { Stress: "Stress", Anxiety: "Anxiety", Depression: "Depression", "Sleep Issues": "Sleep Issues", Isolation: "Isolation", // ── New crisis categories ── self_harm: "Self-Harm", eating_disorders: "Eating Disorder", substance_abuse: "Substance Abuse" }; // Application data const appData = { colleges: [ "Indian Institute of Technology Madras", "Indian Institute of Technology Delhi", "Indian Institute of Technology Bombay", "Jadavpur University", "Vellore Institute of Technology", "National Institute of Technology Tiruchirappalli", "Birla Institute of Technology and Science, Pilani", "Amity University", "S.R.M. Institute of Science and Technology" ], phq9_questions: { en: [ {"id": "PHQ9_Q1", "text": "Little interest or pleasure in doing things", "options": ["Not at all (0)", "Several days (1)", "More than half the days (2)", "Nearly every day (3)"]}, {"id": "PHQ9_Q2", "text": "Feeling down, depressed, or hopeless", "options": ["Not at all (0)", "Several days (1)", "More than half the days (2)", "Nearly every day (3)"]}, {"id": "PHQ9_Q3", "text": "Trouble falling or staying asleep, or sleeping too much", "options": ["Not at all (0)", "Several days (1)", "More than half the days (2)", "Nearly every day (3)"]}, {"id": "PHQ9_Q4", "text": "Feeling tired or having little energy", "options": ["Not at all (0)", "Several days (1)", "More than half the days (2)", "Nearly every day (3)"]}, {"id": "PHQ9_Q5", "text": "Poor appetite or overeating", "options": ["Not at all (0)", "Several days (1)", "More than half the days (2)", "Nearly every day (3)"]}, {"id": "PHQ9_Q6", "text": "Feeling bad about yourself — or that you are a failure", "options": ["Not at all (0)", "Several days (1)", "More than half the days (2)", "Nearly every day (3)"]}, {"id": "PHQ9_Q7", "text": "Trouble concentrating on things", "options": ["Not at all (0)", "Several days (1)", "More than half the days (2)", "Nearly every day (3)"]}, {"id": "PHQ9_Q8", "text": "Moving or speaking slowly or being restless", "options": ["Not at all (0)", "Several days (1)", "More than half the days (2)", "Nearly every day (3)"]}, {"id": "PHQ9_Q9", "text": "Thoughts that you would be better off dead", "options": ["Not at all (0)", "Several days (1)", "More than half the days (2)", "Nearly every day (3)"]} ], hi: [ {"id": "PHQ9_Q1", "text": "चीजों को करने में कम रुचि या आनंद", "options": ["बिल्कुल नहीं (0)", "कई दिन (1)", "आधे से ज्यादा दिन (2)", "लगभग हर दिन (3)"]}, {"id": "PHQ9_Q2", "text": "उदास, निराश या हताश महसूस करना", "options": ["बिल्कुल नहीं (0)", "कई दिन (1)", "आधे से ज्यादा दिन (2)", "लगभग हर दिन (3)"]}, {"id": "PHQ9_Q3", "text": "सोने या सोते रहने में परेशानी, या बहुत ज्यादा सोना", "options": ["बिल्कुल नहीं (0)", "कई दिन (1)", "आधे से ज्यादा दिन (2)", "लगभग हर दिन (3)"]}, {"id": "PHQ9_Q4", "text": "थका हुआ महसूस करना या बहुत कम ऊर्जा होना", "options": ["बिल्कुल नहीं (0)", "कई दिन (1)", "आधे से ज्यादा दिन (2)", "लगभग हर दिन (3)"]}, {"id": "PHQ9_Q5", "text": "खराब भूख या ज्यादा खाना", "options": ["बिल्कुल नहीं (0)", "कई दिन (1)", "आधे से ज्यादा दिन (2)", "लगभग हर दिन (3)"]}, {"id": "PHQ9_Q6", "text": "अपने बारे में बुरा महसूस करना - या कि आप एक विफलता हैं", "options": ["बिल्कुल नहीं (0)", "कई दिन (1)", "आधे से ज्यादा दिन (2)", "लगभग हर दिन (3)"]}, {"id": "PHQ9_Q7", "text": "चीजों पर ध्यान केंद्रित करने में परेशानी", "options": ["बिल्कुल नहीं (0)", "कई दिन (1)", "आधे से ज्यादा दिन (2)", "लगभग हर दिन (3)"]}, {"id": "PHQ9_Q8", "text": "धीरे-धीरे चलना या बोलना या बेचैन होना", "options": ["बिल्कुल नहीं (0)", "कई दिन (1)", "आधे से ज्यादा दिन (2)", "लगभग हर दिन (3)"]}, {"id": "PHQ9_Q9", "text": "ऐसे विचार कि आप मर गए होते तो बेहतर होता", "options": ["बिल्कुल नहीं (0)", "कई दिन (1)", "आधे से ज्यादा दिन (2)", "लगभग हर दिन (3)"]} ] }, gad7_questions: { en: [ {"id": "GAD7_Q1", "text": "Feeling nervous, anxious or on edge", "options": ["Not at all (0)", "Several days (1)", "More than half the days (2)", "Nearly every day (3)"]}, {"id": "GAD7_Q2", "text": "Not being able to stop or control worrying", "options": ["Not at all (0)", "Several days (1)", "More than half the days (2)", "Nearly every day (3)"]}, {"id": "GAD7_Q3", "text": "Worrying too much about different things", "options": ["Not at all (0)", "Several days (1)", "More than half the days (2)", "Nearly every day (3)"]}, {"id": "GAD7_Q4", "text": "Trouble relaxing", "options": ["Not at all (0)", "Several days (1)", "More than half the days (2)", "Nearly every day (3)"]}, {"id": "GAD7_Q5", "text": "Being so restless that it is hard to sit still", "options": ["Not at all (0)", "Several days (1)", "More than half the days (2)", "Nearly every day (3)"]}, {"id": "GAD7_Q6", "text": "Becoming easily annoyed or irritable", "options": ["Not at all (0)", "Several days (1)", "More than half the days (2)", "Nearly every day (3)"]}, {"id": "GAD7_Q7", "text": "Feeling afraid as if something awful might happen", "options": ["Not at all (0)", "Several days (1)", "More than half the days (2)", "Nearly every day (3)"]} ], hi: [ {"id": "GAD7_Q1", "text": "घबराहट, चिंता या किनारे पर महसूस करना", "options": ["बिल्कुल नहीं (0)", "कई दिन (1)", "आधे से ज्यादा दिन (2)", "लगभग हर दिन (3)"]}, {"id": "GAD7_Q2", "text": "चिंता को रोकने या नियंत्रित करने में सक्षम नहीं होना", "options": ["बिल्कुल नहीं (0)", "कई दिन (1)", "आधे से ज्यादा दिन (2)", "लगभग हर दिन (3)"]}, {"id": "GAD7_Q3", "text": "विभिन्न चीजों के बारे में बहुत ज्यादा चिंता करना", "options": ["बिल्कुल नहीं (0)", "कई दिन (1)", "आधे से ज्यादा दिन (2)", "लगभग हर दिन (3)"]}, {"id": "GAD7_Q4", "text": "आराम करने में परेशानी", "options": ["बिल्कुल नहीं (0)", "कई दिन (1)", "आधे से ज्यादा दिन (2)", "लगभग हर दिन (3)"]}, {"id": "GAD7_Q5", "text": "इतना बेचैन होना कि चुपचाप बैठना मुश्किल हो", "options": ["बिल्कुल नहीं (0)", "कई दिन (1)", "आधे से ज्यादा दिन (2)", "लगभग हर दिन (3)"]}, {"id": "GAD7_Q6", "text": "आसानी से नाराज या चिड़चिड़ा हो जाना", "options": ["बिल्कुल नहीं (0)", "कई दिन (1)", "आधे से ज्यादा दिन (2)", "लगभग हर दिन (3)"]}, {"id": "GAD7_Q7", "text": "ऐसा महसूस करना कि कुछ भयानक हो सकता है", "options": ["बिल्कुल नहीं (0)", "कई दिन (1)", "आधे से ज्यादा दिन (2)", "लगभग हर दिन (3)"]} ] }, counselors: [ {"id": "C001", "name": "Dr. Sarah Johnson", "specialization": "Anxiety and Depression", "languages": ["English"], "availability": ["Monday 10-12", "Wednesday 2-4", "Friday 10-12"]}, {"id": "C002", "name": "Dr. Rajesh Kumar", "specialization": "Student Counseling", "languages": ["English", "Hindi"], "availability": ["Tuesday 9-11", "Thursday 1-3"]} ], resources: [ { category: "CBT Modules", category_hi: "सीबीटी मॉड्यूल", items: [ { title: "Thought Record Exercise", title_hi: "विचार रिकॉर्ड व्यायाम", description: "Track and analyze your thoughts and feelings", description_hi: "अपने विचारों और भावनाओं को ट्रैक और विश्लेषण करें", type: "Worksheet", type_hi: "कार्यपत्रक" }, { title: "Cognitive Restructuring", title_hi: "संज्ञानात्मक पुनर्गठन", description: "Challenge negative thinking patterns", description_hi: "नकारात्मक सोच पैटर्न को चुनौती दें", type: "Module", type_hi: "मॉड्यूल" } ] }, { category: "Mindfulness & Relaxation", category_hi: "माइंडफुलनेस और आराम", items: [ { title: "Breathing Exercises for Anxiety", title_hi: "चिंता के लिए साँस लेने के व्यायाम", description: "Simple breathing techniques to manage anxiety", description_hi: "चिंता को प्रबंधित करने के लिए सरल साँस लेने की तकनीक", type: "Video - 5 min", type_hi: "वीडियो - 5 मिनट" }, { title: "Mindfulness Meditation", title_hi: "माइंडफुलनेस ध्यान", description: "Guided meditation for stress relief", description_hi: "तनाव से राहत के लिए निर्देशित ध्यान", type: "Audio - 10 min", type_hi: "ऑडियो - 10 मिनट" } ] }, { category: "Educational Content", category_hi: "शैक्षिक सामग्री", items: [ { title: "Understanding Depression", title_hi: "अवसाद को समझना", description: "Learn about symptoms, causes, and treatment options", description_hi: "लक्षणों, कारणों और उपचार के विकल्पों के बारे में जानें", type: "Article", type_hi: "लेख" }, { title: "Managing Academic Stress", title_hi: "शैक्षणिक तनाव का प्रबंधन", description: "Practical tips for handling college pressure", description_hi: "कॉलेज के दबाव को संभालने के लिए व्यावहारिक सुझाव", type: "Guide", type_hi: "गाइड" } ] }, { category: "Peer Support", category_hi: "सहकर्मी सहायता", items: [ { title: "Student Success Stories", title_hi: "छात्र सफलता की कहानियाँ", description: "Read how other students overcame challenges", description_hi: "पढ़ें कि कैसे अन्य छात्रों ने चुनौतियों पर विजय प्राप्त की", type: "Stories", type_hi: "कहानियाँ" }, { title: "Support Group Directory", title_hi: "सहायता समूह निर्देशिका", description: "Find peer support groups in your area", description_hi: "अपने क्षेत्र में सहकर्मी सहायता समूह खोजें", type: "Directory", type_hi: "निर्देशिका" } ] } ] }; // Application state let currentLanguage = 'en'; let currentAssessment = null; let currentQuestionIndex = 0; let assessmentAnswers = []; let selectedCounselor = null; let selectedDate = null; let selectedTime = null; let bookingStep = 0; let userId; // Will be set during initialization // Initialize application document.addEventListener('DOMContentLoaded', function() { initializeApp(); }); function initializeApp() { // Get or create a persistent userId for the session let storedUserId = sessionStorage.getItem('baspirin_userId'); if (storedUserId) { userId = storedUserId; } else { userId = 'user-' + Math.random().toString(36).substr(2, 9); sessionStorage.setItem('baspirin_userId', userId); } setupEventListeners(); setupLogin(); initializeCharts(); generateCalendar(); generateResources(); generateCounselors(); populateCollegeDropdown(); updateUIText(); // Initialize enhanced chat features initializeChat(); } // ─── AUTH HANDLERS ─────────────────────────────────────────────────────── async function handleLogin(e) { e.preventDefault(); const sid = document.getElementById('studentId').value.trim(); const pwd = document.getElementById('loginPassword').value.trim(); if (!sid || !pwd) return alert('Enter both ID and password'); try { const r = await fetch(API_ENDPOINTS.login, { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({ studentId: sid, password: pwd }) }); const d = await r.json(); if (d.success) { userId = sid; sessionStorage.setItem('baspirin_userId', sid); showScreen('chatScreen'); } else alert(d.message || 'Login failed'); } catch { alert('Login error'); } } async function handleRegistration(e) { e.preventDefault(); const f = new FormData(e.target); const payload = { fullName: f.get('fullName'), email: f.get('email'), password: f.get('password') }; try { const r = await fetch(API_ENDPOINTS.register, { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify(payload) }); const d = await r.json(); if (d.success) { alert(`Your ID: ${d.studentId}`); showScreen('landingScreen'); } else alert(d.message || 'Registration failed'); } catch { alert('Registration error'); } } // ─── ENHANCED CHAT ──────────────────────────────────────────────────────── function showTyping() { isTyping = true; document.getElementById('typing-indicator').classList.remove('hidden'); } function hideTyping() { isTyping = false; document.getElementById('typing-indicator').classList.add('hidden'); } async function sendMessage() { const inp = document.getElementById('chatInput'); const txt = inp.value.trim(); if (!txt || isTyping) return; inp.value = ''; addMessage(txt, true); conversationHistory.push({ role: 'user', content: txt }); showTyping(); try { const response = await fetch(API_ENDPOINTS.predict, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: txt, userId: userId }) }); const data = await response.json(); hideTyping(); if (!response.ok || data.error) { throw new Error(data.message || 'API request failed'); } // The new backend provides a consistent structure. We check the 'is_crisis_response' flag. if (data.is_crisis_response) { // For crisis, we use a special display function but still get the text from the main 'response' field. addCrisisMessage(data.response); conversationHistory.push({ role: 'assistant', content: data.response, metadata: { crisis: true } }); } else { // For all non-crisis messages, we use the standard display function. // We pass the 'analysis' object as metadata. addMessage(data.response, false, data.analysis); conversationHistory.push({ role: 'assistant', content: data.response, metadata: data.analysis }); } } catch (err) { console.error("Error sending message:", err); hideTyping(); addMessage("I'm having trouble connecting right now. Please try again in a moment.", false); } } function handleNormalResponse(d) { const meta = { category: d.intent_addressed, confidence: d.confidence }; addMessage(d.response, false, meta); conversationHistory.push({ role:'assistant', content:d.response, metadata:meta }); } function handleCrisisResponse(d) { addCrisisMessage(d.response) conversationHistory.push({ role:'assistant', content:d.response, metadata:{ crisis:true } }); } function handleOutOfScopeResponse(d) { addMessage(d.response, false, { out_of_scope:true }); conversationHistory.push({ role:'assistant', content:d.response, metadata:{ out_of_scope:true } }); } function updateUIText() { document.querySelectorAll('[data-key]').forEach(element => { const key = element.getAttribute('data-key'); if (translations[currentLanguage][key]) { element.textContent = translations[currentLanguage][key]; } }); updateCategoryLabels(); } function updateCategoryLabels() { CATEGORY_LABELS.Stress = translations[currentLanguage].feeling_anxious; CATEGORY_LABELS.Anxiety = translations[currentLanguage].feeling_anxious; CATEGORY_LABELS.Depression = translations[currentLanguage].exam_stress; CATEGORY_LABELS['Sleep Issues'] = translations[currentLanguage].cant_sleep; CATEGORY_LABELS.Isolation = translations[currentLanguage].feeling_lonely; CATEGORY_LABELS.help_seeking = "Help Request"; CATEGORY_LABELS.method_feedback = "Feedback"; CATEGORY_LABELS.session_continuity = "Follow-Up"; CATEGORY_LABELS.guidance_request = "Guidance"; } function setupEventListeners() { // Navigation event listeners setupNavigation(); // Assessment event listeners setupAssessment(); // Enhanced chat event listeners setupEnhancedChat(); // Booking event listeners setupBooking(); // Modal event listeners setupModal(); // Registration event listeners // The registration form submit is handled directly in `handleRegistration` // The login form submit is handled directly in `handleLogin` // Language switching document.getElementById('languageSelect').addEventListener('change', handleLanguageChange); // Auth modals document.getElementById('loginBtn').addEventListener('click', () => showModalById('loginModal')); document.getElementById('registerBtn').addEventListener('click', () => showScreen('registrationScreen')); document.getElementById('loginForm').addEventListener('submit', handleLogin); document.getElementById('registrationForm').addEventListener('submit', handleRegistration); document.getElementById('closeLoginModal').addEventListener('click', () => hideModalById('loginModal')); } function setupNavigation() { // Feature card navigation document.querySelectorAll('.feature-card').forEach(card => { card.addEventListener('click', () => { const targetScreen = card.getAttribute('data-screen'); showScreen(targetScreen); }); }); // Back button navigation - Fixed to properly handle navigation document.querySelectorAll('.back-btn').forEach(btn => { btn.addEventListener('click', (e) => { e.preventDefault(); const targetScreen = btn.getAttribute('data-target'); if (targetScreen) { showScreen(targetScreen); } else { showScreen('landingScreen'); } }); }); // Dashboard quick actions and other navigation buttons document.querySelectorAll('button[data-screen]').forEach(btn => { if (!btn.closest('.feature-card')) { btn.addEventListener('click', (e) => { e.preventDefault(); const targetScreen = btn.getAttribute('data-screen'); if (targetScreen) { showScreen(targetScreen); } }); } }); // Brand logo click to go home document.querySelector('.nav__brand').addEventListener('click', (e) => { e.preventDefault(); showScreen('landingScreen'); }); } function showScreen(screenId) { // Hide all screens document.querySelectorAll('.screen').forEach(screen => { screen.classList.remove('active'); }); // Show target screen const targetScreen = document.getElementById(screenId); if (targetScreen) { targetScreen.classList.add('active'); } // Scroll to top window.scrollTo(0, 0); // Initialize chat if switching to chat screen if (screenId === 'chatScreen') { initializeChatScreen(); } } // Enhanced Chat Functions function initializeChat() { const storedHistory = sessionStorage.getItem('baspirin_chatHistory'); if (storedHistory) { conversationHistory = JSON.parse(storedHistory); } else { conversationHistory = []; } messageCount = conversationHistory.length; isTyping = false; // Add welcome message only if chat is new if (conversationHistory.length === 0) { setTimeout(() => { const welcomeMessage = translations[currentLanguage].chat_welcome; addMessage(welcomeMessage, false); // Save welcome message to history conversationHistory.push({ role: 'assistant', content: welcomeMessage, timestamp: Date.now() }); sessionStorage.setItem('baspirin_chatHistory', JSON.stringify(conversationHistory)); }, 1000); } } async function initializeChatScreen() { const messagesContainer = document.getElementById('chatMessages'); if (!messagesContainer) return; // Clear previous messages messagesContainer.innerHTML = ''; // Fetch and display persistent history from the database if user is logged in if (sessionStorage.getItem('baspirin_userId') && sessionStorage.getItem('baspirin_userId').startsWith('STU')) { try { const response = await fetch(API_ENDPOINTS.history, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userId: userId }), }); const result = await response.json(); if (result.success && result.history) { conversationHistory = result.history; sessionStorage.setItem('baspirin_chatHistory', JSON.stringify(conversationHistory)); } } catch (error) { console.error('Failed to fetch chat history:', error); } } // Render the conversation history (either from DB or session) conversationHistory.forEach(msg => { addMessage(msg.content, msg.role === 'user', msg.metadata); }); // Add the typing indicator structure back const typingIndicatorHTML = `
${metadata.suggested_resource.title} - ${metadata.suggested_resource.type}
${currentLanguage === 'hi' ? item.description_hi : item.description}
${currentLanguage === 'hi' ? item.type_hi : item.type} `; gridDiv.appendChild(itemDiv); }); container.appendChild(categoryDiv); }); } function generateCounselors() { const container = document.getElementById('counselorList'); if (!container) return; container.innerHTML = ''; appData.counselors.forEach(counselor => { const card = document.createElement('div'); card.className = 'counselor-card'; card.setAttribute('data-counselor', counselor.id); card.innerHTML = `${counselor.specialization}
Languages: ${counselor.languages.join(', ')}