// β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 = ` `; messagesContainer.insertAdjacentHTML('beforeend', typingIndicatorHTML); // Scroll to the bottom messagesContainer.scrollTop = messagesContainer.scrollHeight; } function setupEnhancedChat() { const chatInput = document.getElementById('chatInput'); const sendButton = document.getElementById('sendMessage'); if (sendButton) { sendButton.addEventListener('click', sendMessage); } if (chatInput) { chatInput.addEventListener('keypress', (e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); } }); // Auto-resize textarea chatInput.addEventListener('input', (e) => { adjustTextareaHeight(e.target); }); } // Quick response buttons document.querySelectorAll('.quick-response').forEach(btn => { btn.addEventListener('click', (e) => { const message = e.target.getAttribute('data-message'); if (chatInput) { chatInput.value = message; sendMessage(); } }); }); } function addMessage(text, isUser, metadata = null) { const messagesContainer = document.getElementById('chatMessages'); if (!messagesContainer) return; const messageDiv = document.createElement('div'); messageDiv.className = `message ${isUser ? 'user-message' : 'bot-message'}`; const now = new Date(); const timeString = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); let metadataHTML = ''; // The new metadata object is the 'analysis' object from the backend if (metadata && !isUser) { metadataHTML = `
`; if (metadata.intent) { // <-- New property from 'analysis' object const label = metadata.intent.replace(/_/g, ' '); metadataHTML += `${label}`; } if (metadata.severity !== undefined) { const severityPercentage = (metadata.severity * 100).toFixed(0); let severityClass = 'low'; if (metadata.severity >= 0.85) { severityClass = 'crisis'; } else if (metadata.severity >= 0.6) { severityClass = 'high'; } else if (metadata.severity >= 0.4) { severityClass = 'medium'; } metadataHTML += `Severity: ${severityPercentage}%`; } if (metadata.confidence) { // <-- New property from 'analysis' object metadataHTML += `Conf: ${(metadata.confidence * 100).toFixed(0)}%`; } metadataHTML += `
`; } // The rest of the function remains the same let resourceHTML = ''; if (metadata && metadata.suggested_resource) { resourceHTML = `

You might find this helpful:

${metadata.suggested_resource.title} - ${metadata.suggested_resource.type}

`; } messageDiv.innerHTML = `
${text}
${resourceHTML}
${timeString}
${metadataHTML} `; const typingIndicator = document.getElementById('typing-indicator'); if (typingIndicator) { messagesContainer.insertBefore(messageDiv, typingIndicator); } else { messagesContainer.appendChild(messageDiv); } messagesContainer.scrollTop = messagesContainer.scrollHeight; } async function fetchDashboardData() { if (!userId || !userId.startsWith('STU')) { console.log("Not logged in, using static chart data."); return null; } try { const response = await fetch(API_ENDPOINTS.dashboardData, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userId: userId }), }); const result = await response.json(); if (result.success) { return result.data; } return null; } catch (error) { console.error('Failed to fetch dashboard data:', error); return null; } } function addCrisisMessage(text) { const messagesContainer = document.getElementById('chatMessages'); if (!messagesContainer) return; const messageDiv = document.createElement('div'); messageDiv.className = 'message bot-message crisis-message'; const now = new Date(); const timeString = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); messageDiv.innerHTML = `
⚠️ ${translations[currentLanguage].crisis_detected}
${text}
${timeString}
`; // Insert before typing indicator const typingIndicator = document.getElementById('typing-indicator'); if (typingIndicator) { messagesContainer.insertBefore(messageDiv, typingIndicator); } else { messagesContainer.appendChild(messageDiv); } messagesContainer.scrollTop = messagesContainer.scrollHeight; } function adjustTextareaHeight(textarea) { textarea.style.height = 'auto'; textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px'; } // Continue with existing functions (setupAssessment, setupBooking, etc.) function setupAssessment() { // Assessment type selection document.querySelectorAll('.assessment-option button').forEach(btn => { btn.addEventListener('click', (e) => { const assessmentType = e.target.closest('.assessment-option').getAttribute('data-type'); startAssessment(assessmentType); }); }); // Question navigation document.getElementById('nextQuestion').addEventListener('click', nextQuestion); document.getElementById('prevQuestion').addEventListener('click', prevQuestion); document.getElementById('retakeAssessment').addEventListener('click', resetAssessment); } function startAssessment(type) { currentAssessment = type; currentQuestionIndex = 0; assessmentAnswers = []; const questions = type === 'phq9' ? appData.phq9_questions[currentLanguage] : appData.gad7_questions[currentLanguage]; document.getElementById('totalQuestions').textContent = questions.length; showAssessmentStep('assessmentQuestions'); displayQuestion(); } function displayQuestion() { const questions = currentAssessment === 'phq9' ? appData.phq9_questions[currentLanguage] : appData.gad7_questions[currentLanguage]; const question = questions[currentQuestionIndex]; document.getElementById('currentQuestion').textContent = currentQuestionIndex + 1; document.getElementById('questionText').textContent = question.text; const optionsContainer = document.getElementById('questionOptions'); optionsContainer.innerHTML = ''; question.options.forEach((option, index) => { const optionDiv = document.createElement('div'); optionDiv.className = 'question-option'; optionDiv.textContent = option; optionDiv.setAttribute('data-value', index); optionDiv.addEventListener('click', () => selectOption(optionDiv, index)); if (assessmentAnswers[currentQuestionIndex] === index) { optionDiv.classList.add('selected'); } optionsContainer.appendChild(optionDiv); }); updateProgress(); updateNavigationButtons(); } function selectOption(optionElement, value) { document.querySelectorAll('.question-option').forEach(opt => { opt.classList.remove('selected'); }); optionElement.classList.add('selected'); assessmentAnswers[currentQuestionIndex] = value; updateNavigationButtons(); } function nextQuestion() { const questions = currentAssessment === 'phq9' ? appData.phq9_questions[currentLanguage] : appData.gad7_questions[currentLanguage]; if (currentQuestionIndex < questions.length - 1) { currentQuestionIndex++; displayQuestion(); } else { calculateResults(); } } function prevQuestion() { if (currentQuestionIndex > 0) { currentQuestionIndex--; displayQuestion(); } } function updateProgress() { const questions = currentAssessment === 'phq9' ? appData.phq9_questions[currentLanguage] : appData.gad7_questions[currentLanguage]; const progress = ((currentQuestionIndex + 1) / questions.length) * 100; document.querySelector('.progress-fill').style.width = progress + '%'; } function updateNavigationButtons() { const prevBtn = document.getElementById('prevQuestion'); const nextBtn = document.getElementById('nextQuestion'); prevBtn.disabled = currentQuestionIndex === 0; nextBtn.disabled = assessmentAnswers[currentQuestionIndex] === undefined; } function calculateResults() { const totalScore = assessmentAnswers.reduce((sum, answer) => sum + answer, 0); const maxScore = currentAssessment === 'phq9' ? 27 : 21; let riskLevel, riskClass, recommendations; if (currentAssessment === 'phq9') { if (totalScore <= 4) { riskLevel = 'Minimal Depression'; riskClass = 'risk-minimal'; recommendations = [ 'Continue with healthy lifestyle habits', 'Regular exercise and good sleep hygiene', 'Stay connected with friends and family' ]; } else if (totalScore <= 9) { riskLevel = 'Mild Depression'; riskClass = 'risk-mild'; recommendations = [ 'Consider talking to a counselor', 'Practice stress management techniques', 'Monitor your mood regularly', 'Consider CBT exercises' ]; } else if (totalScore <= 14) { riskLevel = 'Moderate Depression'; riskClass = 'risk-moderate'; recommendations = [ 'Strongly recommend professional counseling', 'Consider therapy or psychiatric evaluation', 'Use our AI chat support for daily guidance', 'Practice mindfulness and relaxation techniques' ]; } else { riskLevel = 'Severe Depression'; riskClass = 'risk-severe'; recommendations = [ 'Immediate professional help is recommended', 'Contact our crisis helpline if needed', 'Book an urgent appointment with a counselor', 'Consider psychiatric evaluation' ]; } } else { // GAD-7 if (totalScore <= 4) { riskLevel = 'Minimal Anxiety'; riskClass = 'risk-minimal'; recommendations = [ 'Continue with healthy coping strategies', 'Regular physical activity', 'Practice relaxation techniques' ]; } else if (totalScore <= 9) { riskLevel = 'Mild Anxiety'; riskClass = 'risk-mild'; recommendations = [ 'Learn anxiety management techniques', 'Practice breathing exercises', 'Consider counseling support', 'Monitor anxiety triggers' ]; } else if (totalScore <= 14) { riskLevel = 'Moderate Anxiety'; riskClass = 'risk-moderate'; recommendations = [ 'Professional counseling is recommended', 'Practice CBT techniques for anxiety', 'Use our mindfulness resources', 'Consider therapy sessions' ]; } else { riskLevel = 'Severe Anxiety'; riskClass = 'risk-severe'; recommendations = [ 'Immediate professional help is needed', 'Book an urgent counseling appointment', 'Practice grounding techniques', 'Contact crisis support if overwhelmed' ]; } } displayResults(totalScore, maxScore, riskLevel, riskClass, recommendations); } function displayResults(score, maxScore, riskLevel, riskClass, recommendations) { document.getElementById('resultTitle').textContent = currentAssessment === 'phq9' ? 'PHQ-9 Results' : 'GAD-7 Results'; document.getElementById('scoreNumber').textContent = score; document.getElementById('scoreTotal').textContent = `/ ${maxScore}`; const riskElement = document.getElementById('riskLevel'); riskElement.textContent = riskLevel; riskElement.className = `risk-level ${riskClass}`; const recommendationsList = document.getElementById('recommendationsList'); recommendationsList.innerHTML = ''; recommendations.forEach(rec => { const item = document.createElement('div'); item.className = 'recommendation-item'; item.textContent = rec; recommendationsList.appendChild(item); }); showAssessmentStep('assessmentResults'); } function showAssessmentStep(stepId) { document.querySelectorAll('.assessment-step').forEach(step => { step.classList.remove('active'); }); document.getElementById(stepId).classList.add('active'); } function resetAssessment() { showAssessmentStep('assessmentSelection'); currentAssessment = null; currentQuestionIndex = 0; assessmentAnswers = []; } // Additional functions for booking, modals, etc. (keeping the existing ones) function setupBooking() { // Counselor selection document.addEventListener('click', (e) => { if (e.target.classList.contains('select-counselor-btn')) { const counselorCard = e.target.closest('.counselor-card'); const counselorId = counselorCard.getAttribute('data-counselor'); selectedCounselor = appData.counselors.find(c => c.id === counselorId); document.querySelectorAll('.counselor-card').forEach(card => { card.classList.remove('selected'); }); counselorCard.classList.add('selected'); nextBookingStep(); } }); // Date selection document.addEventListener('click', (e) => { if (e.target.classList.contains('calendar-day') && !e.target.classList.contains('disabled')) { selectedDate = e.target.textContent; document.querySelectorAll('.calendar-day').forEach(day => { day.classList.remove('selected'); }); e.target.classList.add('selected'); generateTimeSlots(); } }); // Time selection document.addEventListener('click', (e) => { if (e.target.classList.contains('time-slot')) { selectedTime = e.target.textContent; document.querySelectorAll('.time-slot').forEach(slot => { slot.classList.remove('selected'); }); e.target.classList.add('selected'); nextBookingStep(); } }); // Appointment type selection document.addEventListener('click', (e) => { if (e.target.classList.contains('appointment-type')) { document.querySelectorAll('.appointment-type').forEach(type => { type.classList.remove('selected'); }); e.target.classList.add('selected'); nextBookingStep(); } }); // Confirm booking const confirmButton = document.querySelector('#confirmBooking .btn--primary'); if(confirmButton) { confirmButton.addEventListener('click', confirmBooking); } } function nextBookingStep() { const steps = document.querySelectorAll('.booking-step'); steps[bookingStep].classList.remove('active'); bookingStep++; if (bookingStep < steps.length) { steps[bookingStep].classList.add('active'); } if (bookingStep === 3) { // Confirmation step updateBookingConfirmation(); } } function updateBookingConfirmation() { if (selectedCounselor) { document.getElementById('confirmCounselor').textContent = selectedCounselor.name; } if (selectedDate) { document.getElementById('confirmDate').textContent = selectedDate; } if (selectedTime) { document.getElementById('confirmTime').textContent = selectedTime; } const selectedType = document.querySelector('.appointment-type.selected'); if (selectedType) { document.getElementById('confirmType').textContent = selectedType.querySelector('h4').textContent; } } function confirmBooking() { // Here you would typically send the booking data to your backend showModal(translations[currentLanguage].booking_success_message); resetBooking(); showScreen('dashboardScreen'); } function resetBooking() { bookingStep = 0; selectedCounselor = null; selectedDate = null; selectedTime = null; document.querySelectorAll('.booking-step').forEach((step, index) => { step.classList.toggle('active', index === 0); }); } function generateCalendar() { const calendar = document.getElementById('calendar'); const today = new Date(); const currentMonth = today.getMonth(); const currentYear = today.getFullYear(); // Simple calendar generation (you might want to use a library for production) const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate(); const firstDay = new Date(currentYear, currentMonth, 1).getDay(); let calendarHTML = '
January 2025
'; // Add day headers const dayHeaders = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; dayHeaders.forEach(day => { calendarHTML += `
${day}
`; }); // Add empty cells for days before month starts for (let i = 0; i < firstDay; i++) { calendarHTML += '
'; } // Add days of the month for (let day = 1; day <= daysInMonth; day++) { const isToday = day === today.getDate() && currentMonth === today.getMonth(); const isPast = day < today.getDate() && currentMonth === today.getMonth(); calendarHTML += `
${day}
`; } calendarHTML += '
'; if (calendar) { calendar.innerHTML = calendarHTML; } } function generateTimeSlots() { const timeSlotsContainer = document.getElementById('timeSlots'); if (!timeSlotsContainer) return; const timeSlots = ['9:00 AM', '10:00 AM', '11:00 AM', '2:00 PM', '3:00 PM', '4:00 PM']; let slotsHTML = ''; timeSlots.forEach(time => { slotsHTML += `
${time}
`; }); timeSlotsContainer.innerHTML = slotsHTML; } function generateResources() { const container = document.querySelector('#resourcesScreen .resources-categories'); if (!container) return; container.innerHTML = ''; appData.resources.forEach(category => { const categoryDiv = document.createElement('div'); categoryDiv.className = 'resource-category'; categoryDiv.innerHTML = `

${currentLanguage === 'hi' ? category.category_hi : category.category}

`; const gridDiv = categoryDiv.querySelector('.resource-grid'); category.items.forEach(item => { const itemDiv = document.createElement('div'); itemDiv.className = 'resource-item'; itemDiv.innerHTML = `

${currentLanguage === 'hi' ? item.title_hi : item.title}

${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.name}

${counselor.specialization}

Languages: ${counselor.languages.join(', ')}

Available: ${counselor.availability.map(slot => `${slot}`).join('')}
`; container.appendChild(card); }); } function populateCollegeDropdown() { const select = document.getElementById('college'); if (!select) return; appData.colleges.forEach(college => { const option = document.createElement('option'); option.value = college; option.textContent = college; select.appendChild(option); }); } function setupModal() { // Close modal when clicking outside document.addEventListener('click', (e) => { if (e.target.classList.contains('modal')) { hideModalById(e.target.id); } }); // Close modal buttons document.querySelectorAll('.modal-close').forEach(btn => { btn.addEventListener('click', (e) => { const modal = e.target.closest('.modal'); if (modal) { hideModalById(modal.id); } }); }); } function setupLogin() { const form = document.getElementById('loginForm'); if (!form) return; form.addEventListener('submit', async (e) => { e.preventDefault(); const formData = new FormData(form); const data = Object.fromEntries(formData); try { const response = await fetch(API_ENDPOINTS.login, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }); const result = await response.json(); if (response.ok) { hideModalById('loginModal'); alert(result.message); // Welcome message // --- KEY CHANGE: Update session with logged-in user ID --- userId = result.user.studentId; sessionStorage.setItem('baspirin_userId', userId); // Clear previous anonymous chat history to start a fresh, authenticated session sessionStorage.removeItem('baspirin_chatHistory'); initializeChat(); // Re-initialize chat initializeChatScreen(); // Refresh the chat screen // Update UI to show logged-in state document.getElementById('loginBtn').textContent = result.user.fullName; document.getElementById('registerBtn').style.display = 'none'; } else { alert(`Login failed: ${result.message}`); } } catch (error) { console.error('Login error:', error); alert('Could not connect to the server. Please try again later.'); } }); } function handleLanguageChange(e) { currentLanguage = e.target.value; updateUIText(); generateResources(); } function showModalById(modalId) { const modal = document.getElementById(modalId); if (modal) { modal.style.display = 'flex'; } } function hideModalById(modalId) { const modal = document.getElementById(modalId); if (modal) { modal.style.display = 'none'; } } function showModal(message) { // Create and show a simple modal with the message const modal = document.createElement('div'); modal.className = 'modal'; modal.id = 'successModal'; // Give it an ID to be found modal.innerHTML = ` `; document.body.appendChild(modal); modal.style.display = 'flex'; // Add listener for the new close button modal.querySelector('.modal-close').addEventListener('click', () => hideModalById('successModal')); } // Chart initialization functions async function initializeCharts() { if (typeof Chart === 'undefined') return; const data = await fetchDashboardData(); // Use fetched data if available, otherwise use static demo data const moodData = data && data.mood_history.data.length > 0 ? data.mood_history.data : [6, 7, 5, 8, 6, 9, 7]; const moodLabels = data && data.mood_history.labels.length > 0 ? data.mood_history.labels : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; const assessmentDataPHQ9 = data ? data.assessment_history.phq9 : [12, 9, 7, 5]; const assessmentDataGAD7 = data ? data.assessment_history.gad7 : [14, 11, 8, 6]; const assessmentLabels = data ? data.assessment_history.labels : ['Week 1', 'Week 2', 'Week 3', 'Week 4']; initializeMoodChart(moodLabels, moodData); initializeAssessmentChart(assessmentLabels, assessmentDataPHQ9, assessmentDataGAD7); initializeUsageChart(); initializeRiskChart(); } function initializeMoodChart(labels, data) { const ctx = document.getElementById('moodChart'); if (!ctx) return; new Chart(ctx, { type: 'line', data: { labels: labels, datasets: [{ label: 'Daily Mood', data: data, borderColor: '#1FB8CD', backgroundColor: 'rgba(31, 184, 205, 0.1)', fill: true, tension: 0.4 }] }, options: { responsive: true, maintainAspectRatio: false, scales: { y: { beginAtZero: true, max: 10, title: { display: true, text: 'Mood (1-10)' } } }, plugins: { legend: { display: false } } } }); } function initializeAssessmentChart(labels, phq9Data, gad7Data) { const ctx = document.getElementById('assessmentChart'); if (!ctx) return; new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: 'PHQ-9 Score', data: phq9Data, backgroundColor: '#FFC185' }, { label: 'GAD-7 Score', data: gad7Data, backgroundColor: '#B4413C' }] }, options: { responsive: true, maintainAspectRatio: false, scales: { y: { beginAtZero: true, title: { display: true, text: 'Score' } } } } }); } function initializeUsageChart() { const ctx = document.getElementById('usageChart'); if (!ctx) return; new Chart(ctx, { type: 'line', data: { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'], datasets: [{ label: 'Active Users', data: [450, 520, 680, 750, 850, 856], borderColor: '#1FB8CD', backgroundColor: 'rgba(31, 184, 205, 0.1)', fill: true }, { label: 'Assessments Taken', data: [120, 150, 200, 280, 350, 380], borderColor: '#FFC185', backgroundColor: 'rgba(255, 193, 133, 0.1)', fill: true }] }, options: { responsive: true, maintainAspectRatio: false, scales: { y: { beginAtZero: true } } } }); } function initializeRiskChart() { const ctx = document.getElementById('riskChart'); if (!ctx) return; new Chart(ctx, { type: 'doughnut', data: { labels: ['Minimal', 'Mild', 'Moderate', 'Severe'], datasets: [{ data: [45, 30, 20, 5], backgroundColor: ['#1FB8CD', '#FFC185', '#B4413C', '#ECEBD5'] }] }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'bottom' } } } }); }