// Pulse App Main JavaScript class PulseApp { constructor() { this.currentPage = 'dashboard'; this.isIFActive = false; this.ifTimer = null; this.ifStartTime = null; this.init(); } init() { // Set current date this.updateDate(); // Initialize navigation this.initNavigation(); // Initialize IF timer this.initIFTimer(); // Initialize page-specific features this.initMoodLogging(); this.initNutritionTracking(); this.initActivityTracking(); this.initSleepTracking(); // Simulate real-time data updates this.startRealTimeUpdates(); // Initialize location services this.requestLocationPermission(); // Check device capabilities this.checkDeviceCapabilities(); } updateDate() { const date = new Date(); const options = { day: 'numeric', month: 'short', year: 'numeric' }; const thaiDate = date.toLocaleDateString('th-TH', options); const dateElement = document.getElementById('currentDate'); if (dateElement) { dateElement.textContent = thaiDate; } } initNavigation() { // Set active navigation this.setActiveNav('dashboard'); } setActiveNav(page) { const navButtons = document.querySelectorAll('.nav-btn'); navButtons.forEach(btn => { btn.classList.remove('active'); if (btn.dataset.page === page) { btn.classList.add('active'); } }); // Hide all navigation items for special pages const specialPages = ['recovery', 'strain']; const nav = document.querySelector('nav.fixed.bottom-0'); if (nav) { if (specialPages.includes(page)) { nav.classList.add('hidden'); } else { nav.classList.remove('hidden'); } } } // Initialize mood logging initMoodLogging() { const moodButtons = document.querySelectorAll('.mood-btn'); moodButtons.forEach(btn => { btn.addEventListener('click', (e) => { moodButtons.forEach(b => b.classList.remove('selected')); btn.classList.add('selected'); const mood = btn.querySelector('span:last-child').textContent; this.logMood(mood); }); }); } logMood(mood) { // Save mood to localStorage const today = new Date().toISOString().split('T')[0]; const moodLog = JSON.parse(localStorage.getItem('moodLog') || '{}'); moodLog[today] = { mood: mood, timestamp: new Date().toISOString(), factors: this.getSelectedStressFactors() }; localStorage.setItem('moodLog', JSON.stringify(moodLog)); this.showNotification(`บันทึกอารมณ์: ${mood}`); } getSelectedStressFactors() { const checkboxes = document.querySelectorAll('input[type="checkbox"]:checked'); return Array.from(checkboxes).map(cb => { const label = cb.parentElement.querySelector('span'); return label ? label.textContent : ''; }).filter(text => text); } // Initialize nutrition tracking initNutritionTracking() { this.updateNutritionDisplay(); this.loadRecentMeals(); } updateNutritionDisplay() { const today = new Date().toISOString().split('T')[0]; const nutritionData = JSON.parse(localStorage.getItem('nutritionData') || '{}'); if (nutritionData[today]) { const data = nutritionData[today]; const caloriesElement = document.querySelector('.nutrition-calories'); const carbsElement = document.querySelector('.nutrition-carbs'); const proteinElement = document.querySelector('.nutrition-protein'); if (caloriesElement) caloriesElement.textContent = data.calories || 0; if (carbsElement) carbsElement.textContent = (data.carbs || 0) + 'g'; if (proteinElement) proteinElement.textContent = (data.protein || 0) + 'g'; } } loadRecentMeals() { const today = new Date().toISOString().split('T')[0]; const mealsData = JSON.parse(localStorage.getItem('mealsData') || '{}'); if (mealsData[today]) { const recentMeals = mealsData[today].slice(-3); // Update recent meals display this.displayRecentMeals(recentMeals); } } displayRecentMeals(meals) { const recentMealsContainer = document.querySelector('#nutrition .space-y-3'); if (!recentMealsContainer) return; let mealsHTML = ''; meals.forEach(meal => { mealsHTML += `
${meal.name}
แคลอรี่: ${meal.calories} kcal
${guide.title}
`; guide.content.forEach(line => { html += `${line}
`; }); html += `เคล็ดลับ:
`; guide.tips.forEach(tip => { html += `${tip}
`; }); guideContent.innerHTML = html; } } } changeIFType() { const select = document.getElementById('ifTypeSelect'); if (select) { this.ifType = select.value; localStorage.setItem('ifType', this.ifType); this.updateIFConfiguration(); // Update display const ifTypeDisplay = document.getElementById('ifTypeDisplay'); if (ifTypeDisplay) { ifTypeDisplay.textContent = this.ifType; } // Reset IF if active if (this.isIFActive) { if (confirm('การเปลี่ยนประเภท IF จะรีเซ็ตการนับเวลา ต้องการเปลี่ยนหรือไม่?')) { this.stopIF(); } else { // Revert selection select.value = localStorage.getItem('ifType') || '16:8'; } } } } startIF(startTime = new Date()) { this.isIFActive = true; this.isIFPaused = false; this.ifStartTime = startTime; this.ifPausedTime = 0; localStorage.setItem('ifState', 'active'); localStorage.setItem('ifStartTime', startTime); localStorage.setItem('ifPausedTime', 0); localStorage.setItem('ifType', this.ifType); this.ifTimer = setInterval(() => { this.updateIFDisplay(); }, 1000); this.updateIFDisplay(); this.updateIFButtons('running'); this.showNotification(`เริ่ม ${this.ifType} แล้ว! 💪`); } stopIF() { this.isIFActive = false; this.isIFPaused = false; clearInterval(this.ifTimer); localStorage.setItem('ifState', 'inactive'); localStorage.removeItem('ifStartTime'); localStorage.removeItem('ifPausedTime'); this.updateIFDisplay(); this.updateIFButtons('stopped'); this.showNotification('หยุด IF แล้ว'); } pauseIF() { if (!this.isIFActive || this.isIFPaused) return; this.isIFPaused = true; this.ifPausedTime = Date.now() - this.ifStartTime; localStorage.setItem('ifState', 'paused'); localStorage.setItem('ifPausedTime', this.ifPausedTime); clearInterval(this.ifTimer); this.updateIFButtons('paused'); this.showNotification('พัก IF ชั่วคราว'); } resumeIF() { if (!this.isIFActive || !this.isIFPaused) return; this.isIFPaused = false; this.ifStartTime = new Date(Date.now() - this.ifPausedTime); localStorage.setItem('ifState', 'active'); this.ifTimer = setInterval(() => { this.updateIFDisplay(); }, 1000); this.updateIFButtons('running'); this.showNotification('ทำ IF ต่อ'); } updateIFDisplay() { const timerElement = document.getElementById('ifTimer'); const statusElement = document.getElementById('ifStatus'); const ifTypeDisplay = document.getElementById('ifTypeDisplay'); if (ifTypeDisplay) { ifTypeDisplay.textContent = this.ifType; } if (!timerElement || !statusElement) return; if (!this.isIFActive) { timerElement.textContent = '--:--:--'; statusElement.textContent = 'ยังไม่ได้เริ่ม'; return; } if (this.isIFPaused) { const pausedDuration = this.ifPausedTime; const hours = Math.floor(pausedDuration / 3600000); const minutes = Math.floor((pausedDuration % 3600000) / 60000); const seconds = Math.floor((pausedDuration % 60000) / 1000); timerElement.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; statusElement.textContent = 'พักชั่วคราว'; return; } const now = new Date(); const diff = now - this.ifStartTime; const hours = Math.floor(diff / 3600000); const minutes = Math.floor((diff % 3600000) / 60000); const seconds = Math.floor((diff % 60000) / 1000); timerElement.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; // Calculate progress const fastHours = this.ifType === '5:2' ? 0 : parseInt(this.ifType.split(':')[0]); const totalDuration = fastHours * 60 * 60 * 1000; if (this.ifType !== '5:2') { const progress = (diff / totalDuration) * 100; if (progress >= 100) { statusElement.textContent = 'ครบกำหนดแล้ว! 🎉'; this.completeIF(); } else if (progress >= 75) { statusElement.textContent = 'ใกล้ครบแล้ว!'; } else if (progress >= 50) { statusElement.textContent = 'ผ่านครึ่งทางแล้ว'; } else if (progress >= 25) { statusElement.textContent = 'กำลังดำเนินการ'; } else { statusElement.textContent = 'เริ่มต้น'; } } else { statusElement.textContent = 'วันลดแคลอรี่'; } } updateIFButtons(state) { const startBtn = document.getElementById('startIFBtn'); const stopBtn = document.getElementById('stopIFBtn'); const pauseBtn = document.getElementById('pauseIFBtn'); const resumeBtn = document.getElementById('resumeIFBtn'); // Hide all buttons first if (startBtn) startBtn.classList.add('hidden'); if (stopBtn) stopBtn.classList.add('hidden'); if (pauseBtn) pauseBtn.classList.add('hidden'); if (resumeBtn) resumeBtn.classList.add('hidden'); // Show buttons based on state switch(state) { case 'stopped': if (startBtn) startBtn.classList.remove('hidden'); break; case 'running': if (stopBtn) stopBtn.classList.remove('hidden'); if (pauseBtn) pauseBtn.classList.remove('hidden'); break; case 'paused': if (stopBtn) stopBtn.classList.remove('hidden'); if (resumeBtn) resumeBtn.classList.remove('hidden'); break; } } showPausedIF() { this.updateIFDisplay(); this.updateIFButtons('paused'); } completeIF() { this.stopIF(); // Save completion record const today = new Date().toISOString().split('T')[0]; const ifHistory = JSON.parse(localStorage.getItem('ifHistory') || '{}'); if (!ifHistory[today]) { ifHistory[today] = []; } ifHistory[today].push({ type: this.ifType, completedAt: new Date().toISOString(), duration: this.ifTotalDuration }); localStorage.setItem('ifHistory', JSON.stringify(ifHistory)); this.showNotification('🎉 ทำ IF ครบกำหนดแล้ว! เยี่ยมมาก!'); // Show achievement notification setTimeout(() => { this.showNotification('🏆 ได้รับความสำเร็จ: IF Warrior'); }, 2000); } toggleIF() { if (this.isIFActive) { if (this.isIFPaused) { this.resumeIF(); } else { this.pauseIF(); } } else { this.startIF(); } } startRealTimeUpdates() { // Update vitals every minute setInterval(() => { this.updateVitals(); }, 60000); // Update environmental data every 5 minutes setInterval(() => { this.updateEnvironmentalData(); }, 300000); } updateVitals() { // Simulate HRV and other vital changes // In real app, this would fetch from HealthKit/Health Connect console.log('Updating vitals...'); } async updateEnvironmentalData() { try { // Get user location if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(async (position) => { const { latitude, longitude } = position.coords; // Fetch AQI data (using Thailand AQI API if available) // This is a placeholder - replace with actual API const aqiData = await this.fetchAQIData(latitude, longitude); this.updateAQIDisplay(aqiData); // Fetch weather data const weatherData = await this.fetchWeatherData(latitude, longitude); this.updateWeatherDisplay(weatherData); // Fetch traffic data (for home/work routes) const trafficData = await this.fetchTrafficData(); this.updateTrafficDisplay(trafficData); }); } } catch (error) { console.error('Error updating environmental data:', error); } } async fetchAQIData(lat, lon) { // Placeholder for AQI API // In production, use GISTDA or other Thai AQI APIs return { pm25: 65, aqi: 102, quality: 'ปานกลาง' }; } async fetchWeatherData(lat, lon) { // Placeholder for weather API // In production, use Thai Meteorological Department API return { temperature: 35, heatIndex: 39, uvIndex: 9, humidity: 75 }; } async fetchTrafficData() { // Placeholder for traffic API // In production, use Google Maps or Longdo Maps API return { status: 'ติดขัด', route: 'กลับบ้าน', delay: '45 นาที' }; } updateAQIDisplay(data) { // Update AQI display in UI const aqiElements = document.querySelectorAll('[data-aqi]'); aqiElements.forEach(el => { if (data.aqi > 100) { el.classList.add('text-red-600'); el.classList.remove('text-green-600', 'text-yellow-600'); } else if (data.aqi > 50) { el.classList.add('text-yellow-600'); el.classList.remove('text-green-600', 'text-red-600'); } else { el.classList.add('text-green-600'); el.classList.remove('text-yellow-600', 'text-red-600'); } }); } updateWeatherDisplay(data) { // Update weather display in UI if (data.heatIndex > 37) { // Show heat warning this.showNotification('⚠️ คำเตือน: ดัชนีความร้อนสูง งดออกกำลังกายกลางแจ้ง'); } } updateTrafficDisplay(data) { // Update traffic display in UI if (data.status === 'ติดขัดหนัก') { // Suggest stress management this.showNotification('🚗 รถติดหนัก ลองใช้ฟีเจอร์ฝึกหายใจก่อนถึงบ้านนะครับ'); } } requestLocationPermission() { if ('geolocation' in navigator) { navigator.permissions.query({ name: 'geolocation' }).then((result) => { if (result.state === 'granted') { console.log('Location permission granted'); } else if (result.state === 'prompt') { // User hasn't decided yet console.log('Location permission not decided'); } else { // Permission denied console.log('Location permission denied'); this.showNotification('📍 ต้องการอนุญาตตำแหน่งเพื่อแสดงข้อมูล AQI และสภาพอากาศ'); } }); } } checkDeviceCapabilities() { // Check if device supports HealthKit/Health Connect const supportsHealthKit = 'HealthKit' in window; const supportsHealthConnect = 'HealthConnect' in window; if (supportsHealthKit || supportsHealthConnect) { console.log('Device supports health data integration'); // Initialize health data sync this.initHealthDataSync(); } else { console.log('Device does not support health data integration'); // Show alternative input methods this.showManualInputOptions(); } } initHealthDataSync() { // Placeholder for health data integration // In production, integrate with HealthKit (iOS) or Health Connect (Android) console.log('Initializing health data sync...'); } showManualInputOptions() { // Show manual input options for devices without health integration console.log('Showing manual input options...'); } showNotification(message) { // Create notification element const notification = document.createElement('div'); notification.className = 'fixed top-4 right-4 bg-white rounded-lg shadow-lg p-4 max-w-xs z-50 animate-pulse'; notification.innerHTML = `${message}
`; document.body.appendChild(notification); // Remove after 5 seconds setTimeout(() => { notification.remove(); }, 5000); } // Modal functions showAirQualityModal() { document.getElementById('airQualityModal').classList.remove('hidden'); feather.replace(); } showHeatIndexModal() { document.getElementById('heatIndexModal').classList.remove('hidden'); feather.replace(); } showTrafficModal() { document.getElementById('trafficModal').classList.remove('hidden'); feather.replace(); } showUVIndexModal() { document.getElementById('uvIndexModal').classList.remove('hidden'); feather.replace(); } closeModal(modalId) { document.getElementById(modalId).classList.add('hidden'); } updateAirQualityData() { const location = document.getElementById('airQualityLocation').value; console.log('Updating air quality data for:', location); // In real app, fetch new data based on location this.showNotification('อัพเดทข้อมูลคุณภาพอากาศ'); } updateHeatIndexData() { const location = document.getElementById('heatIndexLocation').value; console.log('Updating heat index data for:', location); // In real app, fetch new data based on location this.showNotification('อัพเดทข้อมูลดัชนีความร้อน'); } updateTrafficData() { const route = document.getElementById('trafficRoute').value; console.log('Updating traffic data for route:', route); // In real app, fetch new data based on route this.showNotification('อัพเดทข้อมูลการจราจร'); } updateUVIndexData() { const location = document.getElementById('uvIndexLocation').value; console.log('Updating UV index data for:', location); // In real app, fetch new data based on location this.showNotification('อัพเดทข้อมูลดัชนี UV'); } setAirQualityTimeRange(range) { // Update button states const buttons = document.querySelectorAll('#airQualityModal .flex button'); buttons.forEach(btn => { btn.classList.remove('bg-primary-600', 'text-white'); btn.classList.add('bg-gray-200', 'text-gray-700'); }); event.target.classList.remove('bg-gray-200', 'text-gray-700'); event.target.classList.add('bg-primary-600', 'text-white'); console.log('Setting air quality time range:', range); this.showNotification(`แสดงข้อมูล ${range === 'today' ? 'วันนี้' : range === 'week' ? '7 วัน' : '30 วัน'}`); } setTrafficTime(time) { // Update button states const buttons = document.querySelectorAll('#trafficModal .flex button'); buttons.forEach(btn => { btn.classList.remove('bg-primary-600', 'text-white'); btn.classList.add('bg-gray-200', 'text-gray-700'); }); event.target.classList.remove('bg-gray-200', 'text-gray-700'); event.target.classList.add('bg-primary-600', 'text-white'); console.log('Setting traffic time:', time); this.showNotification(`แสดงข้อมูลการจราจร ${time === 'now' ? 'ตอนนี้' : time === 'morning' ? 'ช่วงเช้า' : 'ช่วงเย็น'}`); } // Thai food database helper searchThaiFood(query) { const thaiFoodDatabase = [ { name: 'ข้าวมันไก่', calories: 450, protein: 30, carbs: 45, fat: 15 }, { name: 'กะเพราไข่ดาว', calories: 520, protein: 25, carbs: 35, fat: 30 }, { name: 'แกงเขียวหวาน', calories: 380, protein: 20, carbs: 25, fat: 22 }, { name: 'ต้มยำกุ้ง', calories: 180, protein: 25, carbs: 10, fat: 5 }, { name: 'ส้มตำไทย', calories: 120, protein: 3, carbs: 20, fat: 4 }, { name: 'ขนมจีนน้ำยา', calories: 420, protein: 12, carbs: 65, fat: 15 }, { name: 'ข้าวผัด', calories: 480, protein: 15, carbs: 70, fat: 15 }, { name: 'มักกะโรนีผัด', calories: 550, protein: 18, carbs: 65, fat: 25 }, { name: 'ชานมไข่มุก', calories: 320, protein: 8, carbs: 55, fat: 8 }, { name: 'โอเลี้ยง', calories: 400, protein: 12, carbs: 50, fat: 18 } ]; return thaiFoodDatabase.filter(food => food.name.toLowerCase().includes(query.toLowerCase()) ); } // Activity detection detectActivity() { // Placeholder for activity detection // In production, use device sensors or manual input console.log('Detecting activity...'); } // AI Coach insights generation generateAIInsight() { const insights = [ 'วันนี้ฝุ่นเยอะ Recovery 60% แนะนำออกกำลังในร่ม และทานอาหารต้านอักเสบเช่นขิง ข่า ตะไคร้', 'เราสังเกตว่า HRV ลดลง 15% หลังจากวันที่ PM2.5 สูง ลองพักผ่อนมากขึ้นนะครับ', 'การจราจรติดขัดเมื่อวานทำให้ HR สูงค้าง ลองใช้ฟีเจอร์ฝึกหายใจก่อนถึงบ้าน', 'ดัชนีความร้อนสูง การวิ่งสร้าง Strain สูงกว่าปกติ 30% แนะนำให้ดื่มน้ำเกลือแร่' ]; return insights[Math.floor(Math.random() * insights.length)]; } } // Initialize app const app = new PulseApp(); // Global functions for onclick handlers function showPage(page) { app.showPage(page); } function toggleIF() { app.toggleIF(); } function startIF() { app.startIF(); } function stopIF() { app.stopIF(); } function pauseIF() { app.pauseIF(); } function resumeIF() { app.resumeIF(); } function changeIFType() { app.changeIFType(); } function showAirQualityModal() { app.showAirQualityModal(); } function showHeatIndexModal() { app.showHeatIndexModal(); } function showTrafficModal() { app.showTrafficModal(); } function showUVIndexModal() { app.showUVIndexModal(); } function closeModal(modalId) { app.closeModal(modalId); } function updateAirQualityData() { app.updateAirQualityData(); } function updateHeatIndexData() { app.updateHeatIndexData(); } function updateTrafficData() { app.updateTrafficData(); } function updateUVIndexData() { app.updateUVIndexData(); } function setAirQualityTimeRange(range) { app.setAirQualityTimeRange(range); } function setTrafficTime(time) { app.setTrafficTime(time); } // Add to global scope for component access window.PulseApp = PulseApp;