// Main App JavaScript document.addEventListener('DOMContentLoaded', function() { // Initialize app initializeApp(); // Set up event listeners setupEventListeners(); // Load initial data loadInitialData(); }); function initializeApp() { // Set today's date in Thai const today = new Date(); const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; const thaiDate = today.toLocaleDateString('th-TH', options); const dateElement = document.getElementById('todayDate'); if (dateElement) { dateElement.textContent = thaiDate; } // Initialize charts and animations initializeCharts(); initializeAnimations(); } function setupEventListeners() { // Page navigation document.querySelectorAll('nav a, .bottom-nav a').forEach(link => { link.addEventListener('click', handleNavigation); }); // Quick action buttons document.querySelectorAll('.quick-action').forEach(button => { button.addEventListener('click', handleQuickAction); }); // Tab switching document.querySelectorAll('.tab-button').forEach(button => { button.addEventListener('click', handleTabSwitch); }); // Modal triggers document.querySelectorAll('[data-modal]').forEach(trigger => { trigger.addEventListener('click', handleModalOpen); }); // Form submissions document.querySelectorAll('form').forEach(form => { form.addEventListener('submit', handleFormSubmit); }); } function handleNavigation(e) { e.preventDefault(); const targetId = e.target.getAttribute('href').substring(1); // Hide all pages document.querySelectorAll('.page-content').forEach(page => { page.classList.remove('active'); }); // Show target page const targetPage = document.getElementById(targetId); if (targetPage) { targetPage.classList.add('active'); } // Update navigation active states document.querySelectorAll('nav a, .bottom-nav a').forEach(link => { link.classList.remove('active', 'text-indigo-600'); }); e.target.classList.add('active', 'text-indigo-600'); } function handleQuickAction(e) { const action = e.currentTarget.dataset.action; switch(action) { case 'camera': openCamera(); break; case 'add-activity': showActivityModal(); break; case 'add-food': showFoodModal(); break; case 'start-meditation': startMeditation(); break; default: console.log('Unknown action:', action); } } function handleTabSwitch(e) { const tabContainer = e.target.closest('.tab-container'); const tabButtons = tabContainer.querySelectorAll('.tab-button'); // Remove active class from all tabs tabButtons.forEach(button => { button.classList.remove('active'); }); // Add active class to clicked tab e.target.classList.add('active'); // Switch content based on tab const tabName = e.target.dataset.tab; switchTabContent(tabName); } function switchTabContent(tabName) { // Implementation for switching tab content console.log('Switching to tab:', tabName); } function handleModalOpen(e) { const modalId = e.target.dataset.modal; const modal = document.getElementById(modalId); if (modal) { modal.style.display = 'flex'; } } function handleFormSubmit(e) { e.preventDefault(); const formData = new FormData(e.target); const data = Object.fromEntries(formData.entries()); // Process form data console.log('Form submitted:', data); // Show success message showToast('บันทึกสำเร็จ!'); // Close modal if exists const modal = e.target.closest('.modal'); if (modal) { modal.style.display = 'none'; } } function loadInitialData() { // Simulate loading data from APIs loadHealthData(); loadWeatherData(); loadTrafficData(); loadNutritionData(); loadMentalHealthData(); loadCommunityData(); } async function loadMentalHealthData() { try { const mentalData = { stressLevel: 45, mood: 'calm', meditationStreak: 7, meditationMinutes: 35, moodHistory: [ { date: '2024-01-01', mood: 'happy', stress: 40 }, { date: '2024-01-02', mood: 'neutral', stress: 50 }, { date: '2024-01-03', mood: 'stressed', stress: 65 }, { date: '2024-01-04', mood: 'calm', stress: 45 } ], recommendedActivities: [ { name: 'นั่งสมาธิ 5 นาที', duration: '5:00', type: 'meditation' }, { name: 'สวดมนต์ ชินบัญชร', duration: '10:00', type: 'prayer' }, { name: 'ฟังเพลงสมาธิ', duration: '15:00', type: 'music' } ], officeSyndromeAlert: { sittingTime: 45, reminderInterval: 30 } }; updateMentalHealthUI(mentalData); } catch (error) { console.error('Error loading mental health data:', error); } } async function loadCommunityData() { try { const communityData = { teams: [ { name: 'บริษัท Pulse Tech', members: 12, rank: 3, points: 2850, avatar: 'บ' }, { name: 'วิ่งสวนลุม', members: 28, rank: 1, points: 3200, avatar: 'ว' } ], challenges: [ { id: 1, name: 'นอน 7 ชั่วโมง 30 วัน', progress: 15, total: 30, status: 'active', reward: '100 points' }, { id: 2, name: 'ลดพุงหลังสงกรานต์', progress: 2, total: 30, status: 'active', reward: '250 points' }, { id: 3, name: 'วิ่ง 100 กม. เดือนนี้', progress: 68, total: 100, status: 'active', reward: '500 points' } ], leaderboard: [ { rank: 1, name: 'สมชาย', points: 3250, avatar: 'ส' }, { rank: 2, name: 'มานี', points: 2980, avatar: 'ม' }, { rank: 3, name: 'คุณ', points: 2850, avatar: 'จ' } ] }; updateCommunityUI(communityData); } catch (error) { console.error('Error loading community data:', error); } } async function loadHealthData() { // Simulate API call for health data with realistic mock data try { // const response = await fetch('/api/health'); // const data = await response.json(); // Simulated data with realistic Thai user patterns const healthData = { recovery: 72, strain: 8.5, sleep: 7.8, hrv: 52, rhr: 58, sleepStages: { deep: 23, rem: 19, light: 55, awake: 3 }, weeklyData: { monday: { recovery: 68, strain: 9.2, sleep: 7.2 }, tuesday: { recovery: 75, strain: 8.8, sleep: 8.1 }, wednesday: { recovery: 72, strain: 8.5, sleep: 7.8 }, thursday: { recovery: 70, strain: 9.0, sleep: 7.5 }, friday: { recovery: 65, strain: 10.5, sleep: 6.8 }, saturday: { recovery: 80, strain: 15.8, sleep: 8.5 }, sunday: { recovery: 78, strain: 6.3, sleep: 9.0 } }, activities: [ { name: 'วิ่งในสวน', time: '07:30-08:00', strain: 10.2, calories: 280, type: 'running' }, { name: 'โยคะ', time: '18:00-18:30', strain: 4.5, calories: 120, type: 'yoga' }, { name: 'เดินทางไปทำงาน', time: '08:30-09:15', strain: 3.2, calories: 95, type: 'walking' } ], heartRateVariability: { current: 52, baseline: 55, trend: 'slightly_down' }, restingHeartRate: { current: 58, baseline: 60, trend: 'stable' } }; updateHealthUI(healthData); loadWeeklyTrends(healthData.weeklyData); loadActivities(healthData.activities); } catch (error) { console.error('Error loading health data:', error); showToast('ไม่สามารถโหลดข้อมูลสุขภาพได้', 'error'); } } function updateHealthUI(data) { // Update vitals circles updateVitalCircles(data); // Update sleep stages chart updateSleepStages(data.sleepStages); // Update recovery factors updateRecoveryFactors(data); } function updateVitalCircles(data) { // Update vital circle components document.querySelectorAll('vital-circle').forEach(circle => { const label = circle.dataset.label; let value, max, color; switch(label) { case 'Recovery': value = data.recovery; max = 100; color = data.recovery >= 70 ? 'green' : data.recovery >= 50 ? 'yellow' : 'red'; break; case 'Strain': value = data.strain; max = 21; color = data.strain <= 10 ? 'green' : data.strain <= 14 ? 'yellow' : 'red'; break; case 'Sleep': value = data.sleep; max = 12; color = data.sleep >= 7 ? 'green' : data.sleep >= 6 ? 'yellow' : 'red'; break; } circle.setAttribute('value', value); circle.setAttribute('max', max); circle.setAttribute('color', color); }); } function updateSleepStages(stages) { // Update sleep stages progress bars Object.keys(stages).forEach(stage => { const progressBar = document.querySelector(`[data-sleep-stage="${stage}"]`); if (progressBar) { progressBar.style.width = `${stages[stage]}%`; } }); } function updateRecoveryFactors(data) { // Update recovery factor analysis // This would be implemented based on the actual recovery calculation } async function loadWeatherData() { try { // Simulate API call for weather data with Bangkok realistic data const weatherData = { temperature: 38, humidity: 75, pm25: 85, aqi: 152, location: 'กรุงเทพมหานคร', weatherCondition: 'ร้อนจัด', uvIndex: 10, windSpeed: 12, visibility: 5, hourlyForecast: [ { time: '09:00', temp: 35, pm25: 78 }, { time: '12:00', temp: 38, pm25: 85 }, { time: '15:00', temp: 37, pm25: 82 }, { time: '18:00', temp: 34, pm25: 75 }, { time: '21:00', temp: 30, pm25: 68 } ] }; updateWeatherUI(weatherData); updateHourlyForecast(weatherData.hourlyForecast); } catch (error) { console.error('Error loading weather data:', error); } } function updateWeatherUI(data) { // Update weather cards const pm25Element = document.querySelector('[data-weather="pm25"]'); if (pm25Element) { pm25Element.textContent = `PM2.5: ${data.pm25}`; } const tempElement = document.querySelector('[data-weather="temperature"]'); if (tempElement) { tempElement.textContent = `${data.temperature}°C`; } } async function loadTrafficData() { try { // Simulate API call for traffic data with Bangkok realistic data const trafficData = { homeToWork: 45, workToHome: 55, congestionLevel: 'high', route: 'สุขุมวิท - อโศก', distance: 12.5, alternativeRoutes: [ { route: 'ถนนพระราม 4', time: 52, distance: 14.2 }, { route: 'BTS', time: 28, distance: 12.8 } ], trafficConditions: { current: 'ติดขัดหนัก', peakHours: ['07:00-09:00', '17:00-19:00'], incidents: [ { location: 'แยกอโศก', type: 'อุบัติเหตุ', delay: 15 } ] } }; updateTrafficUI(trafficData); updateTrafficAlternatives(trafficData.alternativeRoutes); } catch (error) { console.error('Error loading traffic data:', error); } } function updateTrafficUI(data) { const trafficElement = document.querySelector('[data-traffic="time"]'); if (trafficElement) { trafficElement.textContent = `${data.homeToWork} นาที`; } } async function loadNutritionData() { try { // Simulate API call for nutrition data with Thai food const nutritionData = { calories: { consumed: 1250, goal: 2000, burned: 320, remaining: 750 }, macros: { protein: { consumed: 45, goal: 75 }, carbs: { consumed: 180, goal: 250 }, fat: { consumed: 55, goal: 65 } }, meals: [ { name: 'ข้าวมันไก่', time: '08:30', calories: 450, protein: 25, carbs: 45, fat: 18, image: 'http://static.photos/food/80x80/1' }, { name: 'กะเพราหมูกรอบ', time: '12:00', calories: 550, protein: 28, carbs: 52, fat: 25, image: 'http://static.photos/food/80x80/2' }, { name: 'ขนมปังกับไข่ต้ม', time: '15:30', calories: 250, protein: 12, carbs: 28, fat: 12, image: 'http://static.photos/food/80x80/3' } ], waterIntake: { consumed: 1600, goal: 2500, unit: 'ml' }, nutritionScore: 78, recommendations: [ 'เพิ่มผักให้ครบ 5 สี', 'ลดโซเดียมจากอาหาร', 'ดื่มน้ำเพิ่ม 900 มล.' ] }; updateNutritionUI(nutritionData); updateWaterIntake(nutritionData.waterIntake); updateNutritionScore(nutritionData.nutritionScore); } catch (error) { console.error('Error loading nutrition data:', error); } } function updateNutritionUI(data) { // Update calories display const caloriesElement = document.querySelector('[data-nutrition="calories"]'); if (caloriesElement) { caloriesElement.textContent = `${data.calories.consumed} / ${data.calories.goal}`; } // Update macros display Object.keys(data.macros).forEach(macro => { const macroElement = document.querySelector(`[data-nutrition="${macro}"]`); if (macroElement) { macroElement.textContent = `${data.macros[macro]}g`; } }); } function initializeCharts() { // Initialize any chart libraries // This would use Chart.js or similar library console.log('Charts initialized'); } function initializeAnimations() { // Initialize animations and transitions console.log('Animations initialized'); } // Utility functions function openCamera() { // Implement camera functionality console.log('Opening camera...'); showToast('กำลังเปิดกล้อง...'); } function showActivityModal() { // Show activity logging modal console.log('Showing activity modal...'); } function showFoodModal() { // Show food logging modal console.log('Showing food modal...'); } function startMeditation() { // Start meditation session console.log('Starting meditation...'); showToast('เริ่มการนั่งสมาธิ...'); } function showToast(message, type = 'success') { // Create and show toast notification const toast = document.createElement('div'); toast.className = `toast toast-${type}`; // Add icon based on type const icons = { success: '✓', error: '✕', warning: '⚠', info: 'ℹ' }; toast.innerHTML = `
${icons[type] || icons.info} ${message}
`; // Style the toast const colors = { success: '#10b981', error: '#ef4444', warning: '#f59e0b', info: '#3b82f6' }; toast.style.backgroundColor = colors[type] || colors.info; document.body.appendChild(toast); // Animate in setTimeout(() => { toast.style.transform = 'translateY(0)'; toast.style.opacity = '1'; }, 10); // Remove after timeout setTimeout(() => { toast.style.transform = 'translateY(20px)'; toast.style.opacity = '0'; setTimeout(() => { toast.remove(); }, 300); }, 3000); } // Simulate real-time data updates setInterval(() => { // Update time-based data updateTime(); updateRealTimeMetrics(); checkAlerts(); }, 30000); // Update every 30 seconds for more responsiveness function updateTime() { const now = new Date(); const timeElements = document.querySelectorAll('[data-time]'); timeElements.forEach(element => { element.textContent = now.toLocaleTimeString('th-TH'); }); } function updateRealTimeMetrics() { // Update metrics that change in real-time // Simulate heart rate changes const heartRateElement = document.querySelector('[data-metric="heartRate"]'); if (heartRateElement) { const baseHR = 72; const variation = Math.floor(Math.random() * 10) - 5; heartRateElement.textContent = baseHR + variation; } // Update steps counter const stepsElement = document.querySelector('[data-metric="steps"]'); if (stepsElement) { const currentSteps = parseInt(stepsElement.textContent.replace(',', '')); const newSteps = currentSteps + Math.floor(Math.random() * 50); stepsElement.textContent = newSteps.toLocaleString('th-TH'); } } function checkAlerts() { // Check for important alerts const alerts = [ { condition: () => Math.random() > 0.95, message: 'ถึงเวลาลุกขึ้นเดิน! นั่งนิ่งมานานแล้ว', type: 'warning' }, { condition: () => new Date().getHours() === 12 && new Date().getMinutes() === 0, message: 'ถึงเวลาทานยาตามนัด', type: 'info' } ]; alerts.forEach(alert => { if (alert.condition()) { showToast(alert.message, alert.type); } }); } // New utility functions for updating UI with mock data function loadWeeklyTrends(weeklyData) { // Update weekly trend charts Object.keys(weeklyData).forEach(day => { const element = document.querySelector(`[data-weekly="${day}"]`); if (element && weeklyData[day]) { element.setAttribute('data-recovery', weeklyData[day].recovery); element.setAttribute('data-strain', weeklyData[day].strain); } }); } function loadActivities(activities) { const activitiesContainer = document.querySelector('.activities-list'); if (activitiesContainer && activities) { activitiesContainer.innerHTML = activities.map(activity => `
${activity.name}
${activity.time}
${activity.strain}
${activity.calories} kcal
`).join(''); feather.replace(); } } function getActivityColor(type) { const colors = { running: 'blue', yoga: 'green', walking: 'purple', cycling: 'orange' }; return colors[type] || 'blue'; } function getActivityIcon(type) { const icons = { running: 'target', yoga: 'heart', walking: 'navigation', cycling: 'zap' }; return icons[type] || 'activity'; } function updateHourlyForecast(forecast) { const forecastContainer = document.querySelector('.hourly-forecast'); if (forecastContainer && forecast) { forecastContainer.innerHTML = forecast.map(hour => `
${hour.time}
${hour.temp}°
PM2.5: ${hour.pm25}
`).join(''); } } function updateTrafficAlternatives(alternatives) { const alternativesContainer = document.querySelector('.traffic-alternatives'); if (alternativesContainer && alternatives) { alternativesContainer.innerHTML = alternatives.map(route => `
${route.route}
${route.distance} กม.
${route.time} นาที
`).join(''); } } function updateWaterIntake(waterData) { const waterProgress = document.querySelector('[data-water="progress"]'); const waterText = document.querySelector('[data-water="text"]'); if (waterProgress && waterText && waterData) { const percentage = (waterData.consumed / waterData.goal) * 100; waterProgress.style.width = `${percentage}%`; waterText.textContent = `${waterData.consumed} / ${waterData.goal} ${waterData.unit}`; } } function updateNutritionScore(score) { const scoreElement = document.querySelector('[data-nutrition="score"]'); if (scoreElement) { scoreElement.textContent = score; scoreElement.className = `text-2xl font-bold ${score >= 80 ? 'text-green-600' : score >= 60 ? 'text-yellow-600' : 'text-red-600'}`; } } function updateMentalHealthUI(mentalData) { // Update stress level const stressElement = document.querySelector('[data-mental="stress"]'); if (stressElement && mentalData) { stressElement.textContent = `${mentalData.stressLevel}%`; // Update stress color const stressColor = mentalData.stressLevel <= 30 ? 'green' : mentalData.stressLevel <= 60 ? 'yellow' : 'red'; stressElement.className = `text-2xl font-bold text-${stressColor}-500`; } // Update mood buttons const moodButtons = document.querySelectorAll('.mood-button'); moodButtons.forEach(button => { const mood = button.dataset.mood; if (mood === mentalData.mood) { button.classList.add('ring-2', 'ring-purple-500', 'scale-110'); } }); } function updateCommunityUI(communityData) { // Update teams if (communityData && communityData.teams) { const teamsContainer = document.querySelector('.teams-list'); if (teamsContainer) { teamsContainer.innerHTML = communityData.teams.map(team => `
${team.avatar}
${team.name}
${team.members} สมาชิก
${team.points} pts
อันดับ ${team.rank}
`).join(''); } } // Update challenges if (communityData && communityData.challenges) { const challengesContainer = document.querySelector('.challenges-list'); if (challengesContainer) { challengesContainer.innerHTML = communityData.challenges.map(challenge => `

${challenge.name}

${challenge.status === 'active' ? 'กำลังทำ' : 'สิ้นสุด'}
วันที่ ${challenge.progress}/${challenge.total} • ${challenge.reward}
`).join(''); } } } // Handle visibility change document.addEventListener('visibilitychange', function() { if (document.visibilityState === 'visible') { // App is visible, refresh data loadInitialData(); } }); // Handle network connectivity window.addEventListener('online', function() { showToast('กลับมาออนไลน์แล้ว'); loadInitialData(); }); window.addEventListener('offline', function() { showToast('ขาดการเชื่อมต่อ', 'error'); }); // Performance monitoring if ('PerformanceObserver' in window) { const perfObserver = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { console.log('Performance:', entry.name, entry.duration); }); }); perfObserver.observe({ entryTypes: ['measure'] }); } // Service Worker registration (for PWA) if ('serviceWorker' in navigator) { window.addEventListener('load', function() { navigator.serviceWorker.register('/sw.js') .then((registration) => { console.log('SW registered: ', registration); }) .catch((registrationError) => { console.log('SW registration failed: ', registrationError); }); }); }