// 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 = 'กำลังวิเคราะห์...'; setTimeout(() => { this.disabled = false; this.innerHTML = 'วิเคราะห์ใหม่'; 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 = `
${message}
`; 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'); });