// 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(); } async function loadHealthData() { // Simulate API call for health data try { // const response = await fetch('/api/health'); // const data = await response.json(); // Simulated data const healthData = { recovery: 72, strain: 8.5, sleep: 7.8, hrv: 52, rhr: 58, sleepStages: { deep: 23, rem: 19, light: 55, awake: 3 } }; updateHealthUI(healthData); } 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 const weatherData = { temperature: 38, humidity: 75, pm25: 85, aqi: 152 }; updateWeatherUI(weatherData); } 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 const trafficData = { homeToWork: 45, workToHome: 55, congestionLevel: 'high' }; updateTrafficUI(trafficData); } 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 const nutritionData = { calories: { consumed: 1250, goal: 2000 }, macros: { protein: 45, carbs: 180, fat: 55 }, meals: [ { name: 'ข้าวมันไก่', time: '08:30', calories: 450 }, { name: 'กะเพราหมูกรอบ', time: '12:00', calories: 550 } ] }; updateNutritionUI(nutritionData); } 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.textContent = message; if (type === 'error') { toast.style.backgroundColor = '#ef4444'; } document.body.appendChild(toast); setTimeout(() => { toast.remove(); }, 3000); } // Simulate real-time data updates setInterval(() => { // Update time-based data updateTime(); updateRealTimeMetrics(); }, 60000); // Update every minute 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 // This would fetch fresh data from APIs console.log('Updating real-time metrics...'); } // 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); }); }); }