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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
// WP WELLNET Longevity Platform JavaScript

// Initialize the app
document.addEventListener('DOMContentLoaded', function() {
    initializeCharts();
    initializeNavigation();
    initializeInteractions();
    initializeNotifications();
    loadUserData();
});

// Chart initialization
function initializeCharts() {
    // Simple chart visualization for Fat percentage
    const fatCanvas = document.getElementById('fatChart');
    if (fatCanvas) {
        const ctx = fatCanvas.getContext('2d');
        drawSimpleLineChart(ctx, [19.2, 19.0, 18.9, 18.8, 18.7, 18.6, 18.5]);
    }
}

function drawSimpleLineChart(ctx, data) {
    const width = ctx.canvas.width;
    const height = ctx.canvas.height;
    const padding = 10;
    
    // Clear canvas
    ctx.clearRect(0, 0, width, height);
    
    // Set styles
    ctx.strokeStyle = '#A5D6A7';
    ctx.lineWidth = 2;
    ctx.fillStyle = '#A5D6A7';
    
    // Calculate points
    const maxValue = Math.max(...data);
    const minValue = Math.min(...data);
    const range = maxValue - minValue;
    const xStep = (width - padding * 2) / (data.length - 1);
    const yScale = (height - padding * 2) / range;
    
    // Draw line
    ctx.beginPath();
    data.forEach((value, index) => {
        const x = padding + index * xStep;
        const y = height - padding - (value - minValue) * yScale;
        
        if (index === 0) {
            ctx.moveTo(x, y);
        } else {
            ctx.lineTo(x, y);
        }
    });
    ctx.stroke();
    
    // Draw points
    data.forEach((value, index) => {
        const x = padding + index * xStep;
        const y = height - padding - (value - minValue) * yScale;
        
        ctx.beginPath();
        ctx.arc(x, y, 3, 0, Math.PI * 2);
        ctx.fill();
    });
}

// Navigation handling
function initializeNavigation() {
    const navButtons = document.querySelectorAll('nav button');
    navButtons.forEach(button => {
        button.addEventListener('click', function() {
            // Remove active state from all buttons
            navButtons.forEach(btn => {
                btn.classList.remove('text-primary');
                btn.classList.add('text-gray-500');
            });
            
            // Add active state to clicked button
            this.classList.remove('text-gray-500');
            this.classList.add('text-primary');
            
            // Handle navigation (scroll to section)
            const buttonText = this.querySelector('span').textContent;
            navigateToSection(buttonText);
        });
    });
}

function navigateToSection(section) {
    const sectionMap = {
        'หน้าหลัก': 'dashboard',
        'วิเคราะห์': 'ai-analysis',
        'แผน': 'longevity-plan',
        'สินค้า': 'products',
        'รางวัล': 'rewards'
    };
    
    const targetSection = document.getElementById(sectionMap[section]);
    if (targetSection) {
        targetSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
}

// Interactive elements
function initializeInteractions() {
    // Analyze button
    const analyzeBtn = document.querySelector('button:has(.refresh-cw)');
    if (analyzeBtn) {
        analyzeBtn.addEventListener('click', function() {
            this.disabled = true;
            this.innerHTML = '<i data-feather="loader" class="inline w-4 h-4 mr-2 animate-spin"></i>กำลังวิเคราะห์...';
            
            setTimeout(() => {
                this.disabled = false;
                this.innerHTML = '<i data-feather="refresh-cw" class="inline w-4 h-4 mr-2"></i>วิเคราะห์ใหม่';
                feather.replace();
                showNotification('วิเคราะห์ข้อมูลเสร็จสิ้น!', 'success');
            }, 2000);
        });
    }
    
    // Mission completion buttons
    const missionButtons = document.querySelectorAll('.bg-green-100, .bg-gray-200');
    missionButtons.forEach(button => {
        if (button.textContent.includes('สำเร็จ')) {
            button.addEventListener('click', function() {
                toggleMissionStatus(this);
            });
        }
    });
    
    // Product purchase buttons
    const purchaseButtons = document.querySelectorAll('button:contains("สั่งซื้อ")');
    purchaseButtons.forEach(button => {
        button.addEventListener('click', function() {
            handlePurchase(this);
        });
    });
    
    // Reorder buttons
    const reorderButtons = document.querySelectorAll('button:contains("ซื้อซ้ำ")');
    reorderButtons.forEach(button => {
        button.addEventListener('click', function() {
            handleReorder(this);
        });
    });
}

// Mission status toggle
function toggleMissionStatus(button) {
    if (button.textContent.includes('สำเร็จ')) {
        button.classList.remove('bg-green-100', 'text-green-600');
        button.classList.add('bg-gray-200', 'text-gray-600');
        button.textContent = 'ยังไม่สำเร็จ';
    } else {
        button.classList.remove('bg-gray-200', 'text-gray-600');
        button.classList.add('bg-green-100', 'text-green-600');
        button.textContent = 'สำเร็จ';
        button.classList.add('success-animation');
        
        // Update points
        updatePoints(20);
        showNotification('ภารกิจสำเร็จ! +20 แต้ม', 'success');
    }
}

// Purchase handling
function handlePurchase(button) {
    button.disabled = true;
    button.textContent = 'กำลังดำเนินการ...';
    
    setTimeout(() => {
        button.disabled = false;
        button.textContent = 'สั่งซื้อทันที';
        showNotification('เพิ่มสินค้าลงตะกร้าแล้ว', 'success');
        
        // Update cart count
        updateCartCount();
    }, 1500);
}

// Reorder handling
function handleReorder(button) {
    button.disabled = true;
    button.textContent = 'กำลังสั่งซื้อ...';
    
    setTimeout(() => {
        button.disabled = false;
        button.textContent = 'ซื้อซ้ำ 1 คลิก';
        showNotification('สั่งซื้อสำเร็จ! จัดส่งใน 1-2 วัน', 'success');
    }, 2000);
}

// Points system
let currentPoints = 750;

function updatePoints(points) {
    currentPoints += points;
    const pointsDisplay = document.querySelector('.text-2xl.font-bold');
    if (pointsDisplay && pointsDisplay.textContent.includes('แต้ม')) {
        pointsDisplay.textContent = currentPoints;
        pointsDisplay.classList.add('success-animation');
        setTimeout(() => {
            pointsDisplay.classList.remove('success-animation');
        }, 600);
    }
}

// Cart system
let cartCount = 0;

function updateCartCount() {
    cartCount++;
    // Add cart badge to navigation if not exists
    const cartButton = document.querySelector('button:has(.shopping-cart)');
    if (cartButton && cartCount > 0) {
        let badge = cartButton.querySelector('.cart-badge');
        if (!badge) {
            badge = document.createElement('span');
            badge.className = 'cart-badge absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full w-5 h-5 flex items-center justify-center';
            cartButton.appendChild(badge);
        }
        badge.textContent = cartCount;
        badge.classList.add('badge-pulse');
    }
}

// Notification system
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `fixed top-20 left-4 right-4 z-50 p-4 rounded-lg shadow-lg transform transition-all duration-300 ${
        type === 'success' ? 'bg-green-500 text-white' : 
        type === 'error' ? 'bg-red-500 text-white' : 
        'bg-blue-500 text-white'
    }`;
    notification.innerHTML = `
        <div class="flex items-center justify-between">
            <span>${message}</span>
            <button onclick="this.parentElement.parentElement.remove()" class="ml-4">
                <i data-feather="x" class="w-4 h-4"></i>
            </button>
        </div>
    `;
    
    document.body.appendChild(notification);
    feather.replace();
    
    // Animate in
    setTimeout(() => {
        notification.style.transform = 'translateY(0)';
    }, 10);
    
    // Auto remove
    setTimeout(() => {
        notification.style.transform = 'translateY(-100%)';
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, 3000);
}

// Initialize notifications
function initializeNotifications() {
    // Check for new notifications
    setInterval(checkNewNotifications, 30000);
}

function checkNewNotifications() {
    // Simulate notification check
    const hasNewNotification = Math.random() > 0.8;
    if (hasNewNotification) {
        const bellButton = document.querySelector('button:has(.bell)');
        if (bellButton) {
            const dot = bellButton.querySelector('.bg-red-500');
            if (!dot) {
                const newDot = document.createElement('span');
                newDot.className = 'absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full badge-pulse';
                bellButton.appendChild(newDot);
            }
        }
    }
}

// Load user data
function loadUserData() {
    // Simulate loading user data from API
    const userData = {
        biologicalAge: 34,
        realAge: 38,
        progress: 65,
        hrv: 75,
        stress: 45,
        sleep: 85,
        muscle: 70,
        points: 750,
        currentDay: 15
    };
    
    // Update UI with user data
    updateDashboard(userData);
}

function updateDashboard(data) {
    // Update biological age display
    const bioAgeElements = document.querySelectorAll('.text-4xl.font-bold');
    bioAgeElements.forEach(el => {
        if (parseInt(el.textContent) > 30) {
            el.textContent = data.biologicalAge;
        }
    });
    
    // Update progress bars
    const progressBars = document.querySelectorAll('.bg-white.rounded-full');
    progressBars.forEach(bar => {
        if (bar.parentElement.classList.contains('opacity-90')) {
            bar.style.width = `${data.progress}%`;
        }
    });
    
    // Update health metrics
    updateHealthMetric('HRV', data.hrv);
    updateHealthMetric('ความเครียด', data.stress);
    updateHealthMetric('การนอนหลับ', data.sleep);
    updateHealthMetric('กล้ามเนื้อ', data.muscle);
}

function updateHealthMetric(metric, value) {
    const cards = document.querySelectorAll('.grid .bg-white');
    cards.forEach(card => {
        const label = card.querySelector('.text-xs.text-gray-600');
        if (label && label.textContent === metric) {
            const progressBar = card.querySelector('.bg-gray-200 .rounded-full');
            if (progressBar) {
                progressBar.style.width = `${value}%`;
            }
        }
    });
}

// BioCoach communication
document.querySelectorAll('button:has(.message-circle), button:has(.video), button:has(.file-text)').forEach(button => {
    button.addEventListener('click', function() {
        const icon = this.querySelector('svg').getAttribute('data-feather');
        
        if (icon === 'message-circle') {
            openChat();
        } else if (icon === 'video') {
            openVideoCall();
        } else if (icon === 'file-text') {
            openQuestionForm();
        }
    });
});

function openChat() {
    showNotification('กำลังเปิดแชทกับ BioCoach...', 'info');
    // Implement chat interface
}

function openVideoCall() {
    showNotification('กำลังเชื่อมต่อวิดีโอคอล...', 'info');
    // Implement video call interface
}

function openQuestionForm() {
    showNotification('กำลังเปิดฟอร์มถาม-ตอบ...', 'info');
    // Implement question form
}

// Special event logging
document.querySelector('button:contains("บันทึกเหตุการณ์พิเศษ")')?.addEventListener('click', function() {
    const eventTypes = ['ป่วย', 'งดอาหาร', 'ออกกำลังกายหนัก', 'ท่องเที่ยว', 'สตรีสสูง'];
    const eventType = prompt('เลือกประเภทเหตุการณ์:\n' + eventTypes.map((e, i) => `${i+1}. ${e}`).join('\n'));
    
    if (eventType && eventTypes[parseInt(eventType) - 1]) {
        showNotification(`บันทึกเหตุการณ์: ${eventTypes[parseInt(eventType) - 1]}`, 'success');
        // Log to backend
    }
});

// Periodic data sync
setInterval(() => {
    syncData();
}, 60000); // Sync every minute

function syncData() {
    // Simulate data synchronization
    console.log('Syncing data with server...');
    // Implement actual sync logic
}

// Handle app lifecycle
document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        // App is hidden, pause background tasks
        console.log('App paused');
    } else {
        // App is visible, resume tasks
        console.log('App resumed');
        checkNewNotifications();
    }
});

// Handle online/offline status
window.addEventListener('online', function() {
    showNotification('เชื่อมต่ออินเทอร์เน็ตแล้ว', 'success');
});

window.addEventListener('offline', function() {
    showNotification('การเชื่อมต่ออินเทอร์เน็ตขาดหาย', 'error');
});