File size: 13,667 Bytes
9539581
4a7cb62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9539581
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a7cb62
 
9539581
 
 
 
 
 
4a7cb62
9539581
 
 
 
 
 
 
 
4a7cb62
9539581
 
 
 
4a7cb62
 
9539581
 
 
 
4a7cb62
 
 
9539581
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a7cb62
 
 
9539581
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a7cb62
9539581
 
 
4a7cb62
 
 
9539581
 
 
 
 
 
4a7cb62
9539581
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a7cb62
 
9539581
 
 
 
 
 
 
 
 
 
 
4a7cb62
9539581
 
 
4a7cb62
 
 
9539581
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a7cb62
 
 
 
9539581
 
 
 
 
 
 
 
 
 
 
 
 
 
4a7cb62
 
 
 
9539581
 
4a7cb62
9539581
 
 
4a7cb62
9539581
 
 
 
 
 
 
 
4a7cb62
 
9539581
 
 
 
4a7cb62
 
9539581
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a7cb62
 
9539581
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a7cb62
 
9539581
 
 
 
 
 
4a7cb62
 
 
 
9539581
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a7cb62
 
 
9539581
 
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

// Global App State
const AppState = {
    currentUser: {
        name: 'พิมพ์',
        recovery: 78,
        strain: 12.5,
        sleep: 82,
        heartRate: 68
    },
    
    // Mock data for chart
    heartRateData: {
        labels: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00', '24:00'],
        datasets: [{
            label: 'Heart Rate',
            data: [58, 62, 75, 82, 78, 70, 62],
            borderColor: '#34d399',
            backgroundColor: 'rgba(52, 211, 153, 0.1)',
            tension: 0.4,
            fill: true,
            pointRadius: 0,
            pointHoverRadius: 6
        }]
    }
};
// Initialize Heart Rate Chart
function initHeartRateChart() {
    try {
        const ctx = document.getElementById('hrChart');
        if (!ctx) return;
        
        new Chart(ctx, {
            type: 'line',
            data: AppState.heartRateData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: 'rgba(17, 24, 39, 0.9)',
                        titleColor: '#34d399',
                        bodyColor: '#e5e7eb',
                        borderColor: '#34d399',
                        borderWidth: 1,
                        callbacks: {
                            label: function(context) {
                                return `${context.parsed.y} bpm`;
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        grid: { display: false },
                        ticks: { 
                            color: '#9ca3af'
                        }
                    },
                    y: {
                        grid: { 
                            color: 'rgba(75, 85, 99, 0.3)',
                            borderDash: [5, 5]
                        },
                        ticks: { 
                            color: '#9ca3af'
                        }
                    }
                },
                interaction: {
                    intersect: false,
                    mode: 'index'
                }
            }
        });
    } catch (error) {
        console.error('Chart initialization error:', error);
    }
}
// Simulate Real-time Heart Rate Updates
function simulateRealtimeHR() {
    try {
        const hrElement = document.querySelector('.text-sm.font-medium');
        if (!hrElement || !hrElement.textContent.includes('bpm')) return;
        
        setInterval(() => {
            try {
                const variation = Math.floor(Math.random() * 10) - 5;
                const newHR = Math.max(55, Math.min(85, AppState.currentUser.heartRate + variation));
                hrElement.textContent = `${newHR} bpm`;
            } catch (e) {
                console.warn('HR update error:', e);
            }
        }, 3000);
    } catch (error) {
        console.error('Realtime HR simulation error:', error);
    }
}
// Quick Log Button Actions
function setupQuickLogButtons() {
    try {
        const buttons = document.querySelectorAll('.quick-log-btn');
        
        buttons.forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                try {
                    // Add ripple effect
                    const ripple = document.createElement('div');
                    ripple.className = 'absolute inset-0 bg-white/20 rounded-xl animate-ping';
                    this.appendChild(ripple);
                    
                    setTimeout(() => ripple.remove(), 600);
                    
                    // Show Thai notification
                    const text = this.textContent.trim();
                    showNotification(`กำลังบันทึก: ${text}...`, 'success');
                } catch (innerError) {
                    console.error('Quick log button error:', innerError);
                }
            });
        });
    } catch (error) {
        console.error('Setup quick log buttons error:', error);
    }
}
// Notification System
function showNotification(message, type = 'info') {
    try {
        // Remove existing notification
        const existing = document.querySelector('.notification-toast');
        if (existing) {
            existing.remove();
        }

        const notification = document.createElement('div');
        notification.className = `notification-toast fixed top-4 left-4 right-4 z-50 p-4 rounded-xl shadow-lg transform translate-y-[-100px] opacity-0 transition-all duration-300 ${
            type === 'success' ? 'bg-green-500' : 
            type === 'error' ? 'bg-red-500' : 
            type === 'warning' ? 'bg-yellow-500' : 'bg-blue-500'
        }`;
        notification.textContent = message;
        
        document.body.appendChild(notification);
        
        // Animate in
        setTimeout(() => {
            notification.style.transform = 'translateY(0)';
            notification.style.opacity = '1';
        }, 100);
        
        // Remove after 3 seconds
        setTimeout(() => {
            notification.style.transform = 'translateY(-100px)';
            notification.style.opacity = '0';
            setTimeout(() => notification.remove(), 300);
        }, 3000);
    } catch (error) {
        console.error('Notification error:', error);
        // Fallback to alert
        if (message) alert(message);
    }
}
// Animate elements on scroll
function setupScrollAnimations() {
    try {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('animate-fadeInUp');
                }
            });
        }, { threshold: 0.1 });
        
        document.querySelectorAll('.glass-card').forEach(card => {
            observer.observe(card);
        });
    } catch (error) {
        console.error('Scroll animation setup error:', error);
    }
}
// AI Coach Dynamic Messages
function updateAICoachMessage() {
    try {
        const messages = [
            "วันนี้คุณฟื้นตัวเต็มที่! เหมาะสำหรับการออกกำลังกายระดับกลาง-หนัก อย่าลืมทานอาหารให้ครบ 5 หมู่นะคะ",
            "ค่า HRV ของคุณดีขึ้น 15% จากสัปดาห์ที่แล้ว! แสดงว่าร่างกายกำลังฟื้นตัวได้ดีมากเลยค่ะ",
            "พบว่าคืนที่คุณดื่มกาแฟหลัง 3 ทุ่ม คุณภาพการนอนจะลดลง 30% ลองเลี่ยงดื่มกาแฟในช่วงบ่ายดูนะคะ",
            "วันนี้ความเครียดสะสมอยู่ในระดับปานกลาง แนะนำให้นั่งสมาธิ 10 นาทีก่อนนอนเพื่อลดระดับคอร์ติซอลค่ะ"
        ];
        
        const coachCard = document.querySelector('ai-coach-card');
        if (coachCard && Math.random() > 0.7 && typeof coachCard.updateMessage === 'function') {
            const randomMessage = messages[Math.floor(Math.random() * messages.length)];
            coachCard.updateMessage(randomMessage);
        }
    } catch (error) {
        console.error('AI Coach update error:', error);
    }
}
// Hardware Pairing Simulation
function simulateHardwareConnection() {
    try {
        const devices = [
            { name: 'Apple Watch Series 9', connected: true },
            { name: 'Oura Ring Gen 3', connected: false },
            { name: 'Polar H10', connected: false }
        ];
        
        // Check if hardware is connected
        const connectedDevice = devices.find(d => d.connected);
        if (connectedDevice) {
            console.log(`เชื่อมต่อกับ ${connectedDevice.name} เรียบร้อยแล้ว`);
        }
    } catch (error) {
        console.error('Hardware simulation error:', error);
    }
}
// Office Syndrome Alert
function setupSedentaryAlert() {
    try {
        let sittingTime = 0;
        
        setInterval(() => {
            // Simulate sedentary behavior (in real app, use accelerometer data)
            const isSitting = Math.random() > 0.3;
            
            if (isSitting) {
                sittingTime += 1;
                
                if (sittingTime >= 60) { // 1 hour
                    showOfficeSyndromeAlert();
                    sittingTime = 0;
                }
            } else {
                sittingTime = 0;
            }
        }, 60000); // Check every minute
    } catch (error) {
        console.error('Sedentary alert setup error:', error);
    }
}
function showOfficeSyndromeAlert() {
    try {
        // Remove existing alert
        const existing = document.querySelector('.office-alert');
        if (existing) existing.remove();

        const alert = document.createElement('div');
        alert.className = 'office-alert fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4';
        alert.innerHTML = `
            <div class="glass-card rounded-2xl p-6 max-w-sm w-full border border-gray-700/50">
                <div class="text-center">
                    <div class="w-16 h-16 bg-red-500 rounded-full mx-auto mb-4 flex items-center justify-center pulse-animation">
                        <i data-feather="alert-circle" class="w-8 h-8 text-white"></i>
                    </div>
                    <h3 class="text-xl font-bold mb-2">เตือนภัย Office Syndrome!</h3>
                    <p class="text-gray-400 mb-4">คุณนั่งนิ่งนานเกิน 1 ชั่วโมงแล้ว ลุกขึ้นมายืดเส้นยืดสายกันดีกว่าค่ะ</p>
                    <div class="flex gap-3">
                        <button onclick="this.closest('.office-alert').remove()" class="flex-1 bg-gray-700 hover:bg-gray-600 py-3 rounded-xl font-medium transition-colors">
                            เลื่อนไปก่อน
                        </button>
                        <button onclick="startMicroWorkout(); this.closest('.office-alert').remove()" class="flex-1 bg-gradient-to-r from-green-500 to-emerald-600 py-3 rounded-xl font-medium transition-all hover:scale-[1.02]">
                            เริ่มเลย!
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        document.body.appendChild(alert);
        
        if (typeof feather !== 'undefined') {
            feather.replace({ root: alert });
        }
        
        // Auto close after 30 seconds
        setTimeout(() => {
            if (document.body.contains(alert)) {
                alert.remove();
            }
        }, 30000);
    } catch (error) {
        console.error('Office syndrome alert error:', error);
    }
}
function startMicroWorkout() {
    try {
        showNotification('กำลังเปิดวิดีโอท่ายืดเหยียด...', 'success');
        // In real app, would open video player
    } catch (error) {
        console.error('Micro workout start error:', error);
    }
}

// Initialize App
document.addEventListener('DOMContentLoaded', function() {
    try {
        console.log('Initializing ชีพจร app...');
        
        // Set initial animations
        document.querySelectorAll('section').forEach((section, index) => {
            section.style.animationDelay = `${index * 0.1}s`;
            section.classList.add('animate-fadeInUp');
        });
        
        // Initialize components with delays to avoid conflicts
        setTimeout(() => {
            initHeartRateChart();
        }, 100);
        
        setTimeout(() => {
            simulateRealtimeHR();
        }, 200);
        
        setTimeout(() => {
            setupQuickLogButtons();
        }, 300);
        
        setTimeout(() => {
            setupScrollAnimations();
        }, 400);
        
        setTimeout(() => {
            simulateHardwareConnection();
        }, 500);
        
        // Simulate periodic updates
        setInterval(() => {
            updateAICoachMessage();
        }, 10000);
        
        setTimeout(() => {
            setupSedentaryAlert();
        }, 5000); // Start checking after 5 seconds
        
        // Request permissions (in real app)
        console.log('กำลังขอสิทธิ์เข้าถึงข้อมูลสุขภาพ...');
        
        // Show welcome notification
        setTimeout(() => {
            showNotification('ยินดีต้อนรับสู่ ชีพจร! AI กำลังวิเคราะห์ข้อมูลของคุณ...', 'success');
        }, 1000);
        
        console.log('App initialization complete');
    } catch (error) {
        console.error('App initialization error:', error);
    }
});
// Export for other modules
window.AppState = AppState;
window.showNotification = showNotification;
window.initHeartRateChart = initHeartRateChart;