// Mock data for 30 days - Bangkok office worker marathon runner const mockData = { days: Array.from({ length: 30 }, (_, i) => { const dayOffset = 29 - i; const date = new Date(); date.setDate(date.getDate() - dayOffset); // Simulate realistic patterns const isWeekend = date.getDay() === 0 || date.getDay() === 6; const isHotDay = date.getMonth() >= 2 && date.getMonth() <= 5; // March-May hot season const pollutionLevel = Math.random() > 0.7 ? 'high' : 'normal'; return { date: date.toISOString().split('T')[0], recoveryScore: Math.max(20, Math.min(100, Math.floor( 70 + (isWeekend ? 10 : 0) - (pollutionLevel === 'high' ? 15 : 0) - (isHotDay ? 5 : 0) + Math.random() * 20 - 10 ))), hrv: Math.floor(40 + Math.random() * 60 + (isWeekend ? 15 : 0) - (pollutionLevel === 'high' ? 10 : 0)), rhr: Math.floor(55 + Math.random() * 15 + (pollutionLevel === 'high' ? 5 : 0)), sleepScore: Math.floor(65 + Math.random() * 25 + (isWeekend ? 8 : 0)), respiratoryRate: Math.floor(14 + Math.random() * 4 + (Math.random() > 0.9 ? 3 : 0)), tempDelta: (Math.random() * 1 - 0.5).toFixed(2), aqi_pm25: pollutionLevel === 'high' ? Math.floor(100 + Math.random() * 150) : Math.floor(20 + Math.random() * 50), ambientTemp: isHotDay ? Math.floor(35 + Math.random() * 5) : Math.floor(28 + Math.random() * 5), trafficIndex: Math.floor(2 + Math.random() * 6 + (isWeekend ? -3 : 0)), spicyIntake: Math.floor(Math.random() * 4), sugarIntake: Math.floor(Math.random() * 6), sodiumIntake: Math.floor(Math.random() * 6), sleepDebt: Math.floor(Math.random() * 3 - (isWeekend ? 2 : 0)), perceivedStress: Math.floor(3 + Math.random() * 5 + (pollutionLevel === 'high' ? 2 : 0)) }; }) }; // Current day data const todayData = mockData.days[mockData.days.length - 1]; // Utility functions function getScoreColor(score) { if (score >= 80) return '#10b981'; // Green if (score >= 60) return '#f59e0b'; // Yellow return '#ef4444'; // Red } function getScoreText(score) { if (score >= 80) return { text: 'พร้อมรบ', color: 'text-green-500' }; if (score >= 60) return { text: 'ปานกลาง', color: 'text-yellow-500' }; return { text: 'ต้องพัก', color: 'text-red-500' }; } function formatDateThai(dateString) { const date = new Date(dateString); const options = { year: 'numeric', month: 'long', day: 'numeric', locale: 'th-TH' }; return date.toLocaleDateString('th-TH', options); } function calculateTrend(values) { const recent = values.slice(-7); const previous = values.slice(-14, -7); const recentAvg = recent.reduce((a, b) => a + b, 0) / recent.length; const prevAvg = previous.reduce((a, b) => a + b, 0) / previous.length; return recentAvg - prevAvg; } // Initialize app document.addEventListener('DOMContentLoaded', function() { // Set last update time document.getElementById('lastUpdate').textContent = formatDateThai(new Date().toISOString()); // Load environmental warnings loadEnvironmentalWarnings(); // Load daily suggestions loadDailySuggestions(); // Initialize HRV chart initHRVChart(); // Load sleep data loadSleepData(); // Load nutrition matrix loadNutritionMatrix(); // Load seasonal report loadSeasonalReport(); // Initialize journal form data initJournalForm(); }); // Tab navigation function showSection(sectionName) { // Hide all sections document.querySelectorAll('.content-section').forEach(section => { section.classList.add('hidden'); }); // Show selected section document.getElementById(`${sectionName}-section`).classList.remove('hidden'); // Update tab buttons document.querySelectorAll('.tab-btn').forEach(btn => { btn.classList.remove('active', 'bg-secondary'); btn.classList.add('bg-cardBg'); }); event.target.closest('.tab-btn').classList.add('active', 'bg-secondary'); event.target.closest('.tab-btn').classList.remove('bg-cardBg'); // Trigger chart resize if needed if (sectionName === 'trends' && window.trendsChartInstance) { setTimeout(() => window.trendsChartInstance.resize(), 100); } } // Environmental warnings function loadEnvironmentalWarnings() { const warningsContainer = document.getElementById('environmental-warnings'); const warnings = []; if (todayData.aqi_pm25 > 100) { warnings.push(`🌫️ ค่า PM 2.5 สูง (${todayData.aqi_pm25} μg/m³) อาจลด HRV ของคุณได้`); } if (todayData.ambientTemp > 35) { warnings.push(`🌡️ อุณหภูมิสูง (${todayData.ambientTemp}°C) เพิ่มความเครียดในการออกกำลังกาย`); } if (todayData.trafficIndex > 7) { warnings.push(`🚗 รถติดหนัก (ระดับ ${todayData.trafficIndex}/10) เพิ่มความเครียดทางอารมณ์`); } warningsContainer.innerHTML = warnings.length > 0 ? warnings.map(w => `
•${w}
`).join('') : '
✅ สภาพแวดล้อมอยู่ในเกณฑ์ดี
'; } // Daily suggestions function loadDailySuggestions() { const suggestionsContainer = document.getElementById('daily-suggestions'); const suggestions = []; if (todayData.recoveryScore < 60) { suggestions.push(`⚠️ ควรลดความตึงเครียดวันนี้ไม่เกิน 12.5 จุด`); suggestions.push(`💤 แนะนำให้นอนกลางวัน 20-30 นาที`); } else if (todayData.recoveryScore < 80) { suggestions.push(`💪 สามารถฝึกกลางได้ตามปกติ แต่ควรหลีกเลี่ยงช่วงเที่ยง`); suggestions.push(`🥤 เพิ่มการดื่มน้ำ 2 เท่า จากภาวะอากาศร้อน`); } else { suggestions.push(`🔥 พร้อมสำหรับการฝึกซ้อมหนักวันนี้!`); suggestions.push(`🏃‍♂️ เหมาะสำหรับการวิ่งระยะไกล`); } if (todayData.spicyIntake > 2) { suggestions.push(`🌶️ ระวังอาหารเผ็ดอาจทำให้ RHR สูงขึ้นตอนนอน`); } suggestionsContainer.innerHTML = suggestions.map(s => `
•${s}
` ).join(''); } // HRV Chart function initHRVChart() { const ctx = document.getElementById('hrvChart').getContext('2d'); const last7Days = mockData.days.slice(-7); new Chart(ctx, { type: 'line', data: { labels: last7Days.map(d => formatDateThai(d.date).split(' ')[0]), datasets: [{ label: 'HRV (ms)', data: last7Days.map(d => d.hrv), borderColor: '#14b8a6', backgroundColor: 'rgba(20, 184, 166, 0.1)', tension: 0.4, yAxisID: 'y' }, { label: 'ความเครียด', data: last7Days.map(d => d.perceivedStress), borderColor: '#f97316', backgroundColor: 'rgba(249, 115, 22, 0.1)', tension: 0.4, yAxisID: 'y1' }] }, options: { responsive: true, maintainAspectRatio: false, interaction: { mode: 'index', intersect: false }, plugins: { legend: { labels: { color: '#9ca3af' } } }, scales: { y: { type: 'linear', display: true, position: 'left', title: { display: true, text: 'HRV (ms)', color: '#9ca3af' }, grid: { color: 'rgba(156, 163, 175, 0.1)' }, ticks: { color: '#9ca3af' } }, y1: { type: 'linear', display: true, position: 'right', title: { display: true, text: 'ระดับความเครียด (1-10)', color: '#9ca3af' }, grid: { drawOnChartArea: false }, ticks: { color: '#9ca3af' } }, x: { ticks: { color: '#9ca3af' }, grid: { color: 'rgba(156, 163, 175, 0.1)' } } } } }); } // Sleep data function loadSleepData() { // Respiratory status const respiratoryContainer = document.getElementById('respiratory-status'); const baselineRR = 16; const currentRR = todayData.respiratoryRate; const diff = currentRR - baselineRR; let status = 'good'; let message = 'อัตราการหายใจปกติ'; if (diff > 3) { status = 'danger'; message = '⚠️ อัตราการหายใจสูงผิดปกติ อาจมีอาการป่วยเริ่มต้น'; } else if (diff > 1) { status = 'warning'; message = 'อัตราการหายใจสูงกว่าปกติเล็กน้อย'; } respiratoryContainer.innerHTML = `
ปัจจุบัน ${currentRR}
Baseline ${baselineRR}
${message}
`; // Food impact on sleep const foodContainer = document.getElementById('food-impact-sleep'); const foodImpacts = []; if (todayData.spicyIntake > 2) { foodImpacts.push(`🌶️ อาหารเผ็ดมาก ทำให้ RHR สูงขึ้น ${Math.floor(Math.random() * 5 + 3)} bpm ตอนเริ่มนอน`); } if (todayData.sodiumIntake > 3) { foodImpacts.push(`🧂 โซเดียมสูง อาจทำให้คุณภาพการนอนลดลง 15%`); } if (todayData.sugarIntake > 4) { foodImpacts.push(`🍬 น้ำตาลสูง ทำให้ Sleep Latency เพิ่มขึ้น 20 นาที`); } foodContainer.innerHTML = foodImpacts.length > 0 ? foodImpacts.map(i => `
${i}
`).join('') : '
✅ อาหารวันนี้ไม่มีผลกระทบต่อการนอน
'; } // Nutrition matrix function loadNutritionMatrix() { const container = document.getElementById('nutrition-matrix'); // Calculate average RHR on high sodium days vs normal days const highSodiumDays = mockData.days.filter(d => d.sodiumIntake >= 4); const normalSodiumDays = mockData.days.filter(d => d.sodiumIntake < 3); const avgRHR_highSodium = highSodiumDays.length > 0 ? highSodiumDays.reduce((sum, d) => sum + d.rhr, 0) / highSodiumDays.length : 0; const avgRHR_normal = normalSodiumDays.length > 0 ? normalSodiumDays.reduce((sum, d) => sum + d.rhr, 0) / normalSodiumDays.length : 0; const diff = Math.abs(avgRHR_highSodium - avgRHR_normal).toFixed(1); container.innerHTML = `
วันที่กินเค็มมาก ${avgRHR_highSodium.toFixed(1)} bpm
วันที่กินปกติ ${avgRHR_normal.toFixed(1)} bpm
🔍 วันที่มีโซเดียมสูงเฉลี่ย RHR สูงกว่า ${diff} bpm
`; } // Seasonal report function loadSeasonalReport() { const container = document.getElementById('seasonal-report'); const hotSeasonData = mockData.days.filter(d => { const month = new Date(d.date).getMonth(); return month >= 2 && month <= 5; // March-May }); const avgRecoveryHotSeason = hotSeasonData.length > 0 ? hotSeasonData.reduce((sum, d) => sum + d.recoveryScore, 0) / hotSeasonData.length : 70; container.innerHTML = `

📊 ช่วงเดือนมีนาคมถึงพฤษภาคม เป็นฤดูร้อนที่เครียดที่สุด

⚠️ ค่าเฉลี่ยพลังกายพร้อมรบในฤดูร้อน: ${avgRecoveryHotSeason.toFixed(1)}

💡 แนะนำ: เน้นการฟื้นตัวแบบความเย็น ลดการออกกำลังกายกลางแจ้งในช่วง 10:00-16:00

🧊 เพิ่มการดื่มน้ำเกลือแร่ อาบน้ำเย็น และใช้ห้องแอร์ 24-26°C

`; } // Initialize journal form data function initJournalForm() { const journalForm = document.querySelector('journal-form'); if (journalForm) { journalForm.setTodayData(todayData); } }