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
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
// 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);
            });
    });
}