Spaces:
Running
Running
File size: 29,562 Bytes
df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a 6365de3 df62a7a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 | // 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 = `
<div class="flex items-center">
<span class="toast-icon mr-2">${icons[type] || icons.info}</span>
<span class="toast-message">${message}</span>
</div>
`;
// 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 => `
<div class="activity-item flex items-center justify-between p-3 bg-gray-50 rounded-lg mb-2">
<div class="flex items-center">
<div class="w-10 h-10 bg-${getActivityColor(activity.type)}-100 rounded-full flex items-center justify-center mr-3">
<i data-feather="${getActivityIcon(activity.type)}" class="w-5 h-5 text-${getActivityColor(activity.type)}-600"></i>
</div>
<div>
<div class="font-semibold">${activity.name}</div>
<div class="text-sm text-gray-500">${activity.time}</div>
</div>
</div>
<div class="text-right">
<div class="font-bold text-${getActivityColor(activity.type)}-600">${activity.strain}</div>
<div class="text-sm text-gray-500">${activity.calories} kcal</div>
</div>
</div>
`).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 => `
<div class="text-center">
<div class="text-sm text-gray-500">${hour.time}</div>
<div class="text-lg font-semibold">${hour.temp}°</div>
<div class="text-xs text-orange-500">PM2.5: ${hour.pm25}</div>
</div>
`).join('');
}
}
function updateTrafficAlternatives(alternatives) {
const alternativesContainer = document.querySelector('.traffic-alternatives');
if (alternativesContainer && alternatives) {
alternativesContainer.innerHTML = alternatives.map(route => `
<div class="flex items-center justify-between p-2 bg-gray-50 rounded-lg mb-2">
<div>
<div class="font-semibold text-sm">${route.route}</div>
<div class="text-xs text-gray-500">${route.distance} กม.</div>
</div>
<div class="text-right">
<div class="font-bold text-${route.time < 40 ? 'green' : 'orange'}-600">${route.time} นาที</div>
</div>
</div>
`).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 => `
<div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg mb-2">
<div class="flex items-center">
<div class="w-10 h-10 bg-indigo-600 rounded-full flex items-center justify-center text-white font-bold mr-3">
${team.avatar}
</div>
<div>
<div class="font-semibold">${team.name}</div>
<div class="text-sm text-gray-500">${team.members} สมาชิก</div>
</div>
</div>
<div class="text-right">
<div class="font-bold text-indigo-600">${team.points} pts</div>
<div class="text-sm text-gray-500">อันดับ ${team.rank}</div>
</div>
</div>
`).join('');
}
}
// Update challenges
if (communityData && communityData.challenges) {
const challengesContainer = document.querySelector('.challenges-list');
if (challengesContainer) {
challengesContainer.innerHTML = communityData.challenges.map(challenge => `
<div class="border rounded-lg p-4 mb-3">
<div class="flex items-center justify-between mb-2">
<h3 class="font-bold">${challenge.name}</h3>
<span class="bg-${challenge.status === 'active' ? 'green' : 'gray'}-100 text-${challenge.status === 'active' ? 'green' : 'gray'}-800 px-2 py-1 rounded text-sm">
${challenge.status === 'active' ? 'กำลังทำ' : 'สิ้นสุด'}
</span>
</div>
<div class="text-sm text-gray-600 mb-2">
วันที่ ${challenge.progress}/${challenge.total} • ${challenge.reward}
</div>
<div class="w-full bg-gray-200 rounded-full h-2">
<div class="bg-${(challenge.progress/challenge.total) > 0.5 ? 'green' : 'blue'}-500 h-2 rounded-full transition-all"
style="width: ${(challenge.progress/challenge.total) * 100}%"></div>
</div>
</div>
`).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);
});
});
} |