vitaltrack-pro / index.html
CSNET's picture
อัปเดตเว็บแอป HTML5 (มือถือเป็นหลัก) เดิมให้:
324566d verified
Raw History Blame Contribute Delete
119 kB
<!DOCTYPE html> <html lang="th"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <title>VitalTrack Pro</title> <script src="https://cdn.tailwindcss.com"></script> <script src="https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js"></script> <script src="https://unpkg.com/feather-icons"></script> <style> :root { --primary: #10b981; --primary-dark: #059669; --secondary: #06b6d4; --secondary-dark: #0891b2; --bg-dark: #0f172a; --bg-light: #f8fafc; --card-dark: #1e293b; --card-light: #ffffff; --text-dark: #f1f5f9; --text-light: #0f172a; --border-dark: #334155; --border-light: #e2e8f0; --success: #22c55e; --warning: #f59e0b; --danger: #ef4444; } * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'SF Pro Display', 'Prompt', sans-serif; background: var(--bg-dark); color: var(--text-dark); min-height: 100vh; overflow-x: hidden; } body.light-mode { background: var(--bg-light); color: var(--text-light); } .card { background: var(--card-dark); border-radius: 16px; padding: 16px; box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1); border: 1px solid var(--border-dark); } body.light-mode .card { background: var(--card-light); border-color: var(--border-light); } .tab-content { display: none; animation: fadeIn 0.3s ease-in-out; } .tab-content.active { display: block; } @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } } .bottom-nav { position: fixed; bottom: 0; left: 0; right: 0; background: var(--card-dark); border-top: 1px solid var(--border-dark); padding: 8px 0; z-index: 100; } body.light-mode .bottom-nav { background: var(--card-light); } .nav-item { flex: 1; display: flex; flex-direction: column; align-items: center; padding: 8px; cursor: pointer; transition: all 0.2s; } .nav-item.active { color: var(--primary); } .modal { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.5); z-index: 200; padding: 20px; overflow-y: auto; } .modal.active { display: flex; align-items: center; justify-content: center; } .modal-content { background: var(--card-dark); border-radius: 20px; width: 100%; max-width: 390px; max-height: 90vh; overflow-y: auto; } body.light-mode .modal-content { background: var(--card-light); } .donut-chart { width: 120px; height: 120px; position: relative; } .progress-ring { transform: rotate(-90deg); } .progress-ring-bg { stroke: var(--border-dark); } .progress-ring-fill { transition: stroke-dashoffset 0.5s ease; } .skeleton { background: linear-gradient(90deg, var(--border-dark) 25%, var(--card-dark) 50%, var(--border-dark) 75%); background-size: 200% 100%; animation: loading 1.5s infinite; } @keyframes loading { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } } .sparkline { stroke: var(--primary); fill: none; stroke-width: 2; } .chart-container { position: relative; height: 200px; width: 100%; } .pulse { animation: pulse 2s infinite; } @keyframes pulse { 0% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.05); opacity: 0.8; } 100% { transform: scale(1); opacity: 1; } } .slide-up { animation: slideUp 0.3s ease-out; } @keyframes slideUp { from { transform: translateY(100%); opacity: 0; } to { transform: translateY(0); opacity: 1; } } @media (max-width: 390px) { body { font-size: 14px; } } </style> </head> <body> <!-- Header --> <header class="sticky top-0 z-50 card rounded-b-3xl mb-4"> <div class="flex justify-between items-center p-4"> <div class="flex items-center gap-2"> <i data-feather="activity" class="w-5 h-5 text-primary"></i> <span class="font-semibold text-lg" data-translate="app-title">VitalTrack Pro</span> </div> <div class="flex gap-3"> <button onclick="toggleLanguage()" class="p-2 rounded-lg hover:bg-gray-700 transition"> <span id="lang-toggle" class="text-sm font-medium">TH</span> </button> <button onclick="toggleTheme()" class="p-2 rounded-lg hover:bg-gray-700 transition"> <i data-feather="moon" class="w-5 h-5"></i> </button> </div> </div> </header> <!-- Main Content --> <main class="pb-20 px-4 max-w-md mx-auto"> <!-- Today Tab --> <div id="tab-today" class="tab-content active"> <div class="mb-4"> <h2 class="text-2xl font-bold mb-1" data-translate="today">วันนี้</h2> <p class="text-sm opacity-75" id="current-date">11 พฤศจิกายน 2025</p> </div> <!-- Daily Overview Card --> <div class="card mb-4"> <h3 class="font-semibold mb-3" data-translate="daily-overview">ภาพรวมประจำวัน</h3> <div class="grid grid-cols-2 gap-3"> <div class="text-center p-3 rounded-lg bg-gradient-to-br from-red-500/20 to-red-600/20"> <div class="text-2xl font-bold text-red-400" id="strain-value">13.2</div> <div class="text-xs opacity-75" data-translate="strain">ความเหนื่อย</div> </div> <div class="text-center p-3 rounded-lg bg-gradient-to-br from-green-500/20 to-green-600/20"> <div class="text-2xl font-bold text-green-400" id="recovery-value">74%</div> <div class="text-xs opacity-75" data-translate="recovery">การฟื้นตัว</div> </div> <div class="text-center p-3 rounded-lg bg-gradient-to-br from-blue-500/20 to-blue-600/20"> <div class="text-2xl font-bold text-blue-400" id="sleep-value">82%</div> <div class="text-xs opacity-75" data-translate="sleep">การนอนหลับ</div> </div> <div class="text-center p-3 rounded-lg bg-gradient-to-br from-purple-500/20 to-purple-600/20"> <div class="text-2xl font-bold text-purple-400" id="hrv-value">85</div> <div class="text-xs opacity-75">HRV (ms)</div> </div> </div> </div> <!-- Donut Charts --> <div class="grid grid-cols-3 gap-3 mb-4"> <div class="card text-center"> <div class="donut-chart mx-auto mb-2"> <svg width="120" height="120"> <circle cx="60" cy="60" r="50" fill="none" stroke-width="8" class="progress-ring-bg"/> <circle id="strain-ring" cx="60" cy="60" r="50" fill="none" stroke-width="8" stroke="#ef4444" stroke-dasharray="314" stroke-dashoffset="250" class="progress-ring progress-ring-fill"/> </svg> <div class="absolute inset-0 flex items-center justify-center"> <span class="text-xl font-bold">13.2</span> </div> </div> <div class="text-xs" data-translate="strain">ความเหนื่อย</div> </div> <div class="card text-center"> <div class="donut-chart mx-auto mb-2"> <svg width="120" height="120"> <circle cx="60" cy="60" r="50" fill="none" stroke-width="8" class="progress-ring-bg"/> <circle id="recovery-ring" cx="60" cy="60" r="50" fill="none" stroke-width="8" stroke="#22c55e" stroke-dasharray="314" stroke-dashoffset="82" class="progress-ring progress-ring-fill"/> </svg> <div class="absolute inset-0 flex items-center justify-center"> <span class="text-xl font-bold">74%</span> </div> </div> <div class="text-xs" data-translate="recovery">การฟื้นตัว</div> </div> <div class="card text-center"> <div class="donut-chart mx-auto mb-2"> <svg width="120" height="120"> <circle cx="60" cy="60" r="50" fill="none" stroke-width="8" class="progress-ring-bg"/> <circle id="sleep-ring" cx="60" cy="60" r="50" fill="none" stroke-width="8" stroke="#3b82f6" stroke-dasharray="314" stroke-dashoffset="57" class="progress-ring progress-ring-fill"/> </svg> <div class="absolute inset-0 flex items-center justify-center"> <span class="text-xl font-bold">82%</span> </div> </div> <div class="text-xs" data-translate="sleep">การนอนหลับ</div> </div> </div> <!-- Real-time HR --> <div class="card mb-4"> <h3 class="font-semibold mb-3 flex items-center gap-2"> <i data-feather="heart" class="w-4 h-4 text-red-500 pulse"></i> <span data-translate="current-hr">อัตราการเต้นหัวใจปัจจุบัน</span> </h3> <div class="text-3xl font-bold text-red-400 mb-2"> <span id="current-hr">64</span> <span class="text-sm font-normal">bpm</span> </div> <canvas id="hr-chart" height="80"></canvas> </div> <!-- Timeline --> <div class="card mb-4"> <h3 class="font-semibold mb-3" data-translate="timeline">ไทม์ไลน์กิจกรรม</h3> <div id="timeline" class="space-y-2"> <div class="flex items-center gap-3 p-2 rounded-lg hover:bg-gray-800/50 transition"> <i data-feather="activity" class="w-4 h-4 text-blue-400"></i> <div class="flex-1"> <div class="font-medium text-sm">Morning Run</div> <div class="text-xs opacity-75">07:00 - 07:30 • 245 kcal • Avg HR 145</div> </div> </div> <div class="flex items-center gap-3 p-2 rounded-lg hover:bg-gray-800/50 transition"> <i data-feather="shopping-bag" class="w-4 h-4 text-green-400"></i> <div class="flex-1"> <div class="font-medium text-sm">Walking</div> <div class="text-xs opacity-75">12:30 - 13:00 • 85 kcal • Avg HR 95</div> </div> </div> <div class="flex items-center gap-3 p-2 rounded-lg hover:bg-gray-800/50 transition"> <i data-feather="zap" class="w-4 h-4 text-purple-400"></i> <div class="flex-1"> <div class="font-medium text-sm">Gym Session</div> <div class="text-xs opacity-75">18:00 - 19:00 • 420 kcal • Avg HR 130</div> </div> </div> </div> </div> <!-- Log Journal Button --> <button onclick="openJournalModal()" class="w-full card bg-gradient-to-r from-primary to-primary-dark text-white font-semibold py-3 flex items-center justify-center gap-2 hover:opacity-90 transition"> <i data-feather="edit-3" class="w-4 h-4"></i> <span data-translate="log-journal">บันทึก Journal</span> </button> </div> <!-- Recovery Tab --> <div id="tab-recovery" class="tab-content"> <div class="mb-4"> <h2 class="text-2xl font-bold mb-1" data-translate="recovery">การฟื้นตัว</h2> <p class="text-sm opacity-75" data-translate="recovery-subtitle">ติดตามสถานะการฟื้นตัวของคุณ</p> </div> <!-- Recovery Score Card --> <div class="card mb-4"> <div class="text-center py-4"> <div class="text-5xl font-bold text-green-400 mb-2">74</div> <div class="text-lg font-medium mb-3" data-translate="recovery-score">คะแนนการฟื้นตัว</div> <div class="w-full bg-gray-700 rounded-full h-4 mb-2"> <div class="bg-gradient-to-r from-green-500 to-green-400 h-4 rounded-full" style="width: 74%"></div> </div> <div class="flex justify-between text-xs opacity-75"> <span data-translate="poor">แย่</span> <span data-translate="fair">ปานกลาง</span> <span data-translate="good">ดี</span> <span data-translate="excellent">ยอดเยี่ยม</span> </div> </div> </div> <!-- HRV Chart --> <div class="card mb-4"> <h3 class="font-semibold mb-3">HRV (7 วัน)</h3> <canvas id="hrv-chart" height="150"></canvas> </div> <!-- Resting HR Chart --> <div class="card mb-4"> <h3 class="font-semibold mb-3" data-translate="resting-hr">อัตราการเต้นหัวใจขณะพัก</h3> <canvas id="rhr-chart" height="150"></canvas> </div> <!-- Factors --> <div class="card"> <h3 class="font-semibold mb-3" data-translate="factors">ปัจจัยที่ส่งผล</h3> <div class="space-y-3"> <div class="flex justify-between items-center"> <span data-translate="sleep-performance">ประสิทธิภาพการนอน</span> <span class="font-medium text-green-400">82%</span> </div> <div class="flex justify-between items-center"> <span data-translate="yesterday-strain">ความเหนื่อยเมื่อวาน</span> <span class="font-medium text-yellow-400">11.8</span> </div> <div class="flex justify-between items-center"> <span data-translate="respiration-rate">อัตราการหายใจ</span> <span class="font-medium">14.2 breaths/min</span> </div> <div class="flex justify-between items-center"> <span data-translate="skin-temp">อุณหภูมิผิวหนัง</span> <span class="font-medium">+0.1°C</span> </div> </div> </div> </div> <!-- Sleep Tab --> <div id="tab-sleep" class="tab-content"> <div class="mb-4"> <h2 class="text-2xl font-bold mb-1" data-translate="sleep">การนอนหลับ</h2> <p class="text-sm opacity-75" data-translate="sleep-subtitle">วิเคราะห์คุณภาพการนอนหลับของคุณ</p> </div> <!-- Sleep Coach Card --> <div class="card mb-4"> <h3 class="font-semibold mb-3 flex items-center gap-2"> <i data-feather="moon" class="w-4 h-4 text-blue-400"></i> <span data-translate="sleep-coach">Sleep Coach</span> </h3> <div class="grid grid-cols-2 gap-3"> <div class="text-center p-3 rounded-lg bg-blue-500/20"> <i data-feather="log-in" class="w-5 h-5 mx-auto mb-1 text-blue-400"></i> <div class="text-xs opacity-75 mb-1" data-translate="bedtime">เวลาเข้านอน</div> <div class="font-semibold">22:45</div> </div> <div class="text-center p-3 rounded-lg bg-yellow-500/20"> <i data-feather="log-out" class="w-5 h-5 mx-auto mb-1 text-yellow-400"></i> <div class="text-xs opacity-75 mb-1" data-translate="wake-time">ตื่นนอน</div> <div class="font-semibold">06:30</div> </div> </div> <div class="mt-3 p-3 rounded-lg bg-green-500/20"> <div class="flex items-center gap-2 text-green-400"> <i data-feather="target" class="w-4 h-4"></i> <span class="text-sm" data-translate="sleep-goal">เป้าหมาย: 7.5 ชั่วโมงตามความเหนื่อยวันนี้</span> </div> </div> </div> <!-- Sleep Stages --> <div class="card mb-4"> <h3 class="font-semibold mb-3" data-translate="sleep-stages">ระยะการนอนหลับ</h3> <canvas id="sleep-stages-chart" height="150"></canvas> <div class="grid grid-cols-4 gap-2 mt-3 text-xs"> <div class="flex items-center gap-1"> <div class="w-3 h-3 bg-purple-500 rounded"></div> <span>Awake</span> </div> <div class="flex items-center gap-1"> <div class="w-3 h-3 bg-blue-400 rounded"></div> <span>Light</span> </div> <div class="flex items-center gap-1"> <div class="w-3 h-3 bg-blue-600 rounded"></div> <span>Deep</span> </div> <div class="flex items-center gap-1"> <div class="w-3 h-3 bg-cyan-400 rounded"></div> <span>REM</span> </div> </div> </div> <!-- Sleep Performance History --> <div class="card"> <h3 class="font-semibold mb-3" data-translate="sleep-history">ประวัติการนอนหลับ (14 วัน)</h3> <canvas id="sleep-history-chart" height="150"></canvas> </div> </div> <!-- Training Tab --> <div id="tab-training" class="tab-content"> <div class="mb-4"> <h2 class="text-2xl font-bold mb-1" data-translate="training">การฝึก</h2> <p class="text-sm opacity-75" data-translate="training-subtitle">บันทึกและติดตามการออกกำลังกาย</p> </div> <!-- Start Workout Button --> <button onclick="startWorkout()" class="w-full card bg-gradient-to-r from-red-500 to-orange-500 text-white font-semibold py-4 flex items-center justify-center gap-2 hover:opacity-90 transition mb-4"> <i data-feather="play-circle" class="w-6 h-6"></i> <span data-translate="start-workout">เริ่ม Live Workout</span> </button> <!-- Sport Selection --> <div class="card mb-4"> <h3 class="font-semibold mb-3" data-translate="select-sport">เลือกชนิดกีฬา</h3> <div class="grid grid-cols-4 gap-2"> <button class="p-3 rounded-lg bg-blue-500/20 hover:bg-blue-500/30 transition flex flex-col items-center gap-1"> <i data-feather="activity" class="w-5 h-5 text-blue-400"></i> <span class="text-xs">Run</span> </button> <button class="p-3 rounded-lg bg-green-500/20 hover:bg-green-500/30 transition flex flex-col items-center gap-1"> <i data-feather="navigation" class="w-5 h-5 text-green-400"></i> <span class="text-xs">Bike</span> </button> <button class="p-3 rounded-lg bg-purple-500/20 hover:bg-purple-500/30 transition flex flex-col items-center gap-1"> <i data-feather="zap" class="w-5 h-5 text-purple-400"></i> <span class="text-xs">Gym</span> </button> <button class="p-3 rounded-lg bg-cyan-500/20 hover:bg-cyan-500/30 transition flex flex-col items-center gap-1"> <i data-feather="droplet" class="w-5 h-5 text-cyan-400"></i> <span class="text-xs">Swim</span> </button> <button class="p-3 rounded-lg bg-orange-500/20 hover:bg-orange-500/30 transition flex flex-col items-center gap-1"> <i data-feather="trending-up" class="w-5 h-5 text-orange-400"></i> <span class="text-xs">HIIT</span> </button> <button class="p-3 rounded-lg bg-pink-500/20 hover:bg-pink-500/30 transition flex flex-col items-center gap-1"> <i data-feather="heart" class="w-5 h-5 text-pink-400"></i> <span class="text-xs">Yoga</span> </button> <button class="p-3 rounded-lg bg-indigo-500/20 hover:bg-indigo-500/30 transition flex flex-col items-center gap-1"> <i data-feather="compass" class="w-5 h-5 text-indigo-400"></i> <span class="text-xs">Hike</span> </button> <button class="p-3 rounded-lg bg-gray-500/20 hover:bg-gray-500/30 transition flex flex-col items-center gap-1"> <i data-feather="more-horizontal" class="w-5 h-5 text-gray-400"></i> <span class="text-xs">Other</span> </button> </div> </div> <!-- Live Workout Display (Hidden by default) --> <div id="live-workout" class="hidden card mb-4 bg-gradient-to-br from-red-500/10 to-orange-500/10"> <h3 class="font-semibold mb-3 text-red-400">Live Workout</h3> <div class="grid grid-cols-2 gap-3 mb-3"> <div class="text-center p-3 rounded-lg bg-black/30"> <div class="text-2xl font-bold text-red-400 pulse" id="live-hr">145</div> <div class="text-xs opacity-75">Current HR</div> </div> <div class="text-center p-3 rounded-lg bg-black/30"> <div class="text-2xl font-bold text-orange-400" id="live-time">00:00</div> <div class="text-xs opacity-75">Duration</div> </div> <div class="text-center p-3 rounded-lg bg-black/30"> <div class="text-2xl font-bold text-yellow-400" id="live-kcal">0</div> <div class="text-xs opacity-75">Calories</div> </div> <div class="text-center p-3 rounded-lg bg-black/30"> <div class="text-2xl font-bold text-green-400" id="live-strain">0.0</div> <div class="text-xs opacity-75">Strain</div> </div> </div> <canvas id="live-hr-chart" height="100"></canvas> <button onclick="endWorkout()" class="w-full mt-3 bg-red-500 text-white font-semibold py-2 rounded-lg hover:bg-red-600 transition"> End Workout </button> </div> <!-- Recent Workouts --> <div class="card"> <h3 class="font-semibold mb-3" data-translate="recent-workouts">การฝึกล่าสุด</h3> <div id="workout-list" class="space-y-2"> <!-- Workouts will be populated here --> </div> </div> </div> <!-- Trends Tab --> <div id="tab-trends" class="tab-content"> <div class="mb-4"> <h2 class="text-2xl font-bold mb-1" data-translate="trends">แนวโน้ม</h2> <p class="text-sm opacity-75" data-translate="trends-subtitle">วิเคราะห์ข้อมูลระยะยาว</p> </div> <!-- Time Period Selector --> <div class="card mb-4"> <div class="flex gap-2"> <button onclick="setTrendPeriod('7D')" class="flex-1 py-2 px-4 rounded-lg bg-primary/20 text-primary font-medium">7D</button> <button onclick="setTrendPeriod('30D')" class="flex-1 py-2 px-4 rounded-lg hover:bg-gray-700/30 transition font-medium">30D</button> <button onclick="setTrendPeriod('90D')" class="flex-1 py-2 px-4 rounded-lg hover:bg-gray-700/30 transition font-medium">90D</button> </div> </div> <!-- Combined Metrics Chart --> <div class="card mb-4"> <h3 class="font-semibold mb-3">Strain, Recovery & Sleep</h3> <canvas id="combined-chart" height="200"></canvas> </div> <!-- HRV vs RHR Chart --> <div class="card mb-4"> <h3 class="font-semibold mb-3">HRV vs Resting HR</h3> <canvas id="hrv-rhr-chart" height="200"></canvas> </div> <!-- Weekly Summary --> <div class="card"> <h3 class="font-semibold mb-3" data-translate="weekly-report">สรุปประจำสัปดาห์</h3> <div class="grid grid-cols-2 gap-3"> <div class="text-center p-3 rounded-lg bg-primary/20"> <div class="text-xl font-bold text-primary">8.5</div> <div class="text-xs opacity-75">Avg Strain</div> </div> <div class="text-center p-3 rounded-lg bg-green-500/20"> <div class="text-xl font-bold text-green-400">72%</div> <div class="text-xs opacity-75">Avg Recovery</div> </div> <div class="text-center p-3 rounded-lg bg-blue-500/20"> <div class="text-xl font-bold text-blue-400">84%</div> <div class="text-xs opacity-75">Avg Sleep</div> </div> <div class="text-center p-3 rounded-lg bg-purple-500/20"> <div class="text-xl font-bold text-purple-400">2,850</div> <div class="text-xs opacity-75">Total Calories</div> </div> </div> </div> </div> </main> <!-- Bottom Navigation --> <nav class="bottom-nav"> <div class="flex justify-around items-center max-w-md mx-auto"> <div class="nav-item active" onclick="switchTab('today')"> <i data-feather="home" class="w-5 h-5"></i> <span class="text-xs mt-1" data-translate="nav-today">วันนี้</span> </div> <div class="nav-item" onclick="switchTab('recovery')"> <i data-feather="heart" class="w-5 h-5"></i> <span class="text-xs mt-1" data-translate="nav-recovery">ฟื้นตัว</span> </div> <div class="nav-item" onclick="switchTab('sleep')"> <i data-feather="moon" class="w-5 h-5"></i> <span class="text-xs mt-1" data-translate="nav-sleep">นอน</span> </div> <div class="nav-item" onclick="switchTab('training')"> <i data-feather="activity" class="w-5 h-5"></i> <span class="text-xs mt-1" data-translate="nav-training">ฝึก</span> </div> <div class="nav-item" onclick="switchTab('trends')"> <i data-feather="trending-up" class="w-5 h-5"></i> <span class="text-xs mt-1" data-translate="nav-trends">แนวโน้ม</span> </div> <div class="nav-item" onclick="switchTab('advance-lab')"> <i data-feather="cpu" class="w-5 h-5"></i> <span class="text-xs mt-1">Lab</span> </div> </div> </nav> <!-- Advance Lab Tab --> <div id="tab-advance-lab" class="tab-content"> <div class="mb-4"> <h2 class="text-2xl font-bold mb-1">Advance Lab</h2> <p class="text-sm opacity-75 mb-2">เพื่อการศึกษา ไม่ใช่คำวินิจฉัยทางการแพทย์</p> <div class="card bg-yellow-500/10 border-yellow-500/30"> <div class="flex items-center gap-2 text-yellow-400"> <i data-feather="alert-triangle" class="w-4 h-4"></i> <span class="text-xs">Last test: 2025-11-01 • 3 abnormal markers detected</span> </div> </div> </div> <!-- Lab Sub-Navigation --> <div class="card mb-4"> <div class="flex gap-1 overflow-x-auto pb-2"> <button onclick="switchLabSubTab('overview')" class="lab-sub-tab px-3 py-2 rounded-lg bg-primary/20 text-primary text-sm font-medium whitespace-nowrap">Overview</button> <button onclick="switchLabSubTab('panels')" class="lab-sub-tab px-3 py-2 rounded-lg hover:bg-gray-700/30 text-sm font-medium whitespace-nowrap">Panels</button> <button onclick="switchLabSubTab('derived')" class="lab-sub-tab px-3 py-2 rounded-lg hover:bg-gray-700/30 text-sm font-medium whitespace-nowrap">Derived & Ratios</button> <button onclick="switchLabSubTab('trends')" class="lab-sub-tab px-3 py-2 rounded-lg hover:bg-gray-700/30 text-sm font-medium whitespace-nowrap">Trends & Heatmap</button> <button onclick="switchLabSubTab('correlations')" class="lab-sub-tab px-3 py-2 rounded-lg hover:bg-gray-700/30 text-sm font-medium whitespace-nowrap">Correlations</button> <button onclick="switchLabSubTab('import')" class="lab-sub-tab px-3 py-2 rounded-lg hover:bg-gray-700/30 text-sm font-medium whitespace-nowrap">Import/Export</button> <button onclick="switchLabSubTab('settings')" class="lab-sub-tab px-3 py-2 rounded-lg hover:bg-gray-700/30 text-sm font-medium whitespace-nowrap">Lab Settings</button> </div> </div> <!-- Overview Section --> <div id="lab-overview" class="lab-sub-content"> <div class="card mb-4"> <h3 class="font-semibold mb-3">Lab Wellness Index</h3> <div class="text-center py-4"> <div class="text-5xl font-bold text-green-400 mb-2">78</div> <div class="w-full bg-gray-700 rounded-full h-4 mb-2"> <div class="bg-gradient-to-r from-green-500 to-green-400 h-4 rounded-full" style="width: 78%"></div> </div> <div class="flex justify-between text-xs opacity-75"> <span>Poor</span> <span>Fair</span> <span>Good</span> <span>Excellent</span> </div> </div> </div> <div class="card mb-4"> <h3 class="font-semibold mb-3">Panel Radar</h3> <canvas id="lab-radar-chart" height="200"></canvas> </div> <div class="card"> <h3 class="font-semibold mb-3">Top 5 Abnormal Markers</h3> <div class="space-y-2"> <div class="flex justify-between items-center p-2 rounded-lg bg-red-500/10 border border-red-500/30"> <span class="text-sm">HOMA-IR</span> <span class="text-sm font-bold text-red-400">3.2 ↑</span> </div> <div class="flex justify-between items-center p-2 rounded-lg bg-yellow-500/10 border border-yellow-500/30"> <span class="text-sm">AIP</span> <span class="text-sm font-bold text-yellow-400">0.5 ↑</span> </div> <div class="flex justify-between items-center p-2 rounded-lg bg-yellow-500/10 border border-yellow-500/30"> <span class="text-sm">hs-CRP</span> <span class="text-sm font-bold text-yellow-400">3.1 mg/L ↑</span> </div> <div class="flex justify-between items-center p-2 rounded-lg bg-blue-500/10 border border-blue-500/30"> <span class="text-sm">Ferritin</span> <span class="text-sm font-bold text-blue-400">18 ng/mL ↓</span> </div> <div class="flex justify-between items-center p-2 rounded-lg bg-yellow-500/10 border border-yellow-500/30"> <span class="text-sm">Vitamin D</span> <span class="text-sm font-bold text-yellow-400">22 ng/mL ↓</span> </div> </div> </div> </div> <!-- Panels Section --> <div id="lab-panels" class="lab-sub-content hidden"> <div class="space-y-3" id="lab-panels-container"> <!-- Panels will be dynamically generated --> </div> </div> <!-- Derived & Ratios Section --> <div id="lab-derived" class="lab-sub-content hidden"> <div class="card mb-4"> <h3 class="font-semibold mb-3">Derived Calculations</h3> <div class="space-y-2"> <div class="grid grid-cols-2 gap-3"> <div class="p-3 rounded-lg bg-gray-700/30"> <div class="text-xs opacity-75 mb-1">HOMA-IR</div> <div class="text-lg font-bold text-red-400">3.2</div> <div class="text-xs text-red-400">Insulin Resistance</div> </div> <div class="p-3 rounded-lg bg-gray-700/30"> <div class="text-xs opacity-75 mb-1">AIP</div> <div class="text-lg font-bold text-yellow-400">0.5</div> <div class="text-xs text-yellow-400">Atherogenic Risk</div> </div> <div class="p-3 rounded-lg bg-gray-700/30"> <div class="text-xs opacity-75 mb-1">LDL-C (calc)</div> <div class="text-lg font-bold">128 mg/dL</div> <div class="text-xs">Borderline</div> </div> <div class="p-3 rounded-lg bg-gray-700/30"> <div class="text-xs opacity-75 mb-1">eGFR</div> <div class="text-lg font-bold">92 mL/min</div> <div class="text-xs">Normal</div> </div> <div class="p-3 rounded-lg bg-gray-700/30"> <div class="text-xs opacity-75 mb-1">UACR</div> <div class="text-lg font-bold">12 mg/g</div> <div class="text-xs">A1 Normal</div> </div> <div class="p-3 rounded-lg bg-gray-700/30"> <div class="text-xs opacity-75 mb-1">Free Testosterone</div> <div class="text-lg font-bold">9.2 ng/dL</div> <div class="text-xs">Normal</div> </div> </div> </div> </div> <div class="card"> <h3 class="font-semibold mb-3">Ratios</h3> <div class="space-y-2"> <div class="flex justify-between items-center p-2 rounded-lg bg-gray-700/30"> <span class="text-sm">TG/HDL Ratio</span> <span class="text-sm font-bold">2.8</span> </div> <div class="flex justify-between items-center p-2 rounded-lg bg-gray-700/30"> <span class="text-sm">A/G Ratio</span> <span class="text-sm font-bold">1.5</span> </div> <div class="flex justify-between items-center p-2 rounded-lg bg-gray-700/30"> <span class="text-sm">Transferrin Saturation</span> <span class="text-sm font-bold">22%</span> </div> </div> </div> </div> <!-- Trends & Heatmap Section --> <div id="lab-trends" class="lab-sub-content hidden"> <div class="card mb-4"> <h3 class="font-semibold mb-3">Z-Score Heatmap (12 months)</h3> <canvas id="lab-heatmap" height="300"></canvas> </div> <div class="card"> <h3 class="font-semibold mb-3">Multi-Marker Trends</h3> <canvas id="lab-trends-chart" height="200"></canvas> </div> </div> <!-- Correlations Section --> <div id="lab-correlations" class="lab-sub-content hidden"> <div class="card mb-4"> <h3 class="font-semibold mb-3">Correlation Matrix</h3> <canvas id="lab-correlation-matrix" height="250"></canvas> </div> <div class="card"> <h3 class="font-semibold mb-3">Scatter Plot</h3> <div class="mb-3"> <select class="w-full p-2 rounded-lg bg-gray-700/50 border border-gray-600" id="scatter-x"> <option value="homa_ir">HOMA-IR</option> <option value="aip">AIP</option> <option value="hs_crp">hs-CRP</option> </select> </div> <div class="mb-3"> <select class="w-full p-2 rounded-lg bg-gray-700/50 border border-gray-600" id="scatter-y"> <option value="recovery">Recovery Score</option> <option value="hrv">HRV</option> <option value="sleep">Sleep Score</option> </select> </div> <canvas id="lab-scatter" height="200"></canvas> </div> </div> <!-- Import/Export Section --> <div id="lab-import" class="lab-sub-content hidden"> <div class="card mb-4"> <h3 class="font-semibold mb-3">Import Data</h3> <div class="border-2 border-dashed border-gray-600 rounded-lg p-6 text-center"> <i data-feather="upload-cloud" class="w-8 h-8 mx-auto mb-2 opacity-50"></i> <p class="text-sm opacity-75 mb-2">Drag CSV/JSON file here or click to browse</p> <input type="file" id="lab-file-input" accept=".csv,.json" class="hidden"> <button onclick="document.getElementById('lab-file-input').click()" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-dark transition"> Select File </button> </div> </div> <div class="card mb-4"> <h3 class="font-semibold mb-3">Download Template</h3> <button onclick="downloadLabTemplate()" class="w-full p-3 rounded-lg bg-gray-700/50 border border-gray-600 text-left hover:bg-gray-700/70 transition"> <i data-feather="download" class="inline w-4 h-4 mr-2"></i> Download CSV Template </button> </div> <div class="card"> <h3 class="font-semibold mb-3">Export Data</h3> <button onclick="exportLabData()" class="w-full p-3 rounded-lg bg-gray-700/50 border border-gray-600 text-left hover:bg-gray-700/70 transition"> <i data-feather="download" class="inline w-4 h-4 mr-2"></i> Export Lab Data (JSON) </button> </div> </div> <!-- Lab Settings Section --> <div id="lab-settings" class="lab-sub-content hidden"> <div class="card mb-4"> <h3 class="font-semibold mb-3">Personal Information</h3> <div class="space-y-3"> <div> <label class="block text-sm mb-1">Sex</label> <select class="w-full p-2 rounded-lg bg-gray-700/50 border border-gray-600" id="lab-sex"> <option value="male">Male</option> <option value="female">Female</option> </select> </div> <div> <label class="block text-sm mb-1">Age</label> <input type="number" class="w-full p-2 rounded-lg bg-gray-700/50 border border-gray-600" id="lab-age" value="32"> </div> <div> <label class="block text-sm mb-1">Units</label> <select class="w-full p-2 rounded-lg bg-gray-700/50 border border-gray-600" id="lab-units"> <option value="si">SI (mmol/L)</option> <option value="us">US (mg/dL)</option> </select> </div> </div> </div> <div class="card mb-4"> <h3 class="font-semibold mb-3">Reference Set</h3> <select class="w-full p-2 rounded-lg bg-gray-700/50 border border-gray-600"> <option value="general">General Population</option> <option value="athlete">Athlete</option> <option value="elderly">Elderly (60+)</option> </select> </div> <div class="card mb-4"> <h3 class="font-semibold mb-3">Risk Thresholds</h3> <div class="space-y-2"> <div class="flex justify-between items-center"> <span class="text-sm">Normal Range</span> <div class="w-20 h-2 bg-green-500 rounded"></div> </div> <div class="flex justify-between items-center"> <span class="text-sm">Borderline</span> <div class="w-20 h-2 bg-yellow-500 rounded"></div> </div> <div class="flex justify-between items-center"> <span class="text-sm">High Risk</span> <div class="w-20 h-2 bg-red-500 rounded"></div> </div> </div> </div> <div class="card"> <button onclick="recalculateLabData()" class="w-full bg-primary text-white font-semibold py-3 rounded-lg hover:bg-primary-dark transition mb-2"> Recalculate All </button> <button onclick="resetLabData()" class="w-full bg-red-500/20 text-red-400 font-semibold py-3 rounded-lg hover:bg-red-500/30 transition"> Reset Lab Data </button> </div> </div> </div> <!-- Journal Modal --> <div id="journal-modal" class="modal"> <div class="modal-content slide-up"> <div class="p-6"> <div class="flex justify-between items-center mb-4"> <h3 class="text-xl font-bold" data-translate="log-journal">บันทึก Journal</h3> <button onclick="closeJournalModal()" class="p-2 hover:bg-gray-700/50 rounded-lg transition"> <i data-feather="x" class="w-5 h-5"></i> </button> </div> <div class="space-y-4"> <!-- Categories --> <div> <h4 class="font-semibold mb-2" data-translate="nutrition">โภชนาการ</h4> <div class="grid grid-cols-2 gap-2"> <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer"> <input type="checkbox" class="form-checkbox text-primary"> <span class="text-sm">Caffeine</span> </label> <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer"> <input type="checkbox" class="form-checkbox text-primary"> <span class="text-sm">Alcohol</span> </label> <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer"> <input type="checkbox" class="form-checkbox text-primary"> <span class="text-sm">Late meal</span> </label> <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer"> <input type="checkbox" class="form-checkbox text-primary"> <span class="text-sm">Supplements</span> </label> </div> </div> <div> <h4 class="font-semibold mb-2" data-translate="lifestyle">ไลฟ์สไตล์</h4> <div class="grid grid-cols-2 gap-2"> <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer"> <input type="checkbox" class="form-checkbox text-primary"> <span class="text-sm">Travel</span> </label> <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer"> <input type="checkbox" class="form-checkbox text-primary"> <span class="text-sm">Sick</span> </label> <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer"> <input type="checkbox" class="form-checkbox text-primary"> <span class="text-sm">Stress</span> </label> <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer"> <input type="checkbox" class="form-checkbox text-primary"> <span class="text-sm">Meditation</span> </label> </div> </div> <div> <h4 class="font-semibold mb-2" data-translate="recovery-tools">เครื่องมือฟื้นตัว</h4> <div class="grid grid-cols-2 gap-2"> <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer"> <input type="checkbox" class="form-checkbox text-primary"> <span class="text-sm">Sauna</span> </label> <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer"> <input type="checkbox" class="form-checkbox text-primary"> <span class="text-sm">Cold plunge</span> </label> <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer"> <input type="checkbox" class="form-checkbox text-primary"> <span class="text-sm">Massage</span> </label> <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer"> <input type="checkbox" class="form-checkbox text-primary"> <span class="text-sm">Stretching</span> </label> </div> </div> <div> <label class="block"> <span class="font-semibold mb-2 block" data-translate="mood">อารมณ์</span> <select class="w-full p-2 rounded-lg bg-gray-700/50 border border-gray-600"> <option value="excellent" data-translate="excellent">ยอดเยี่ยม</option> <option value="good" data-translate="good">ดี</option> <option value="fair" data-translate="fair">ปานกลาง</option> <option value="poor" data-translate="poor">แย่</option> </select> </label> </div> <button onclick="saveJournal()" class="w-full bg-primary text-white font-semibold py-3 rounded-lg hover:bg-primary-dark transition"> <span data-translate="save">บันทึก</span> </button> </div> </div> </div> </div> <!-- Settings Modal --> <div id="settings-modal" class="modal"> <div class="modal-content slide-up"> <div class="p-6"> <div class="flex justify-between items-center mb-4"> <h3 class="text-xl font-bold" data-translate="settings">การตั้งค่า</h3> <button onclick="closeSettingsModal()" class="p-2 hover:bg-gray-700/50 rounded-lg transition"> <i data-feather="x" class="w-5 h-5"></i> </button> </div> <div class="space-y-4"> <div> <label class="block font-semibold mb-2" data-translate="units">หน่วย</label> <select class="w-full p-2 rounded-lg bg-gray-700/50 border border-gray-600"> <option value="metric">Metric (km, kg)</option> <option value="imperial">Imperial (mi, lbs)</option> </select> </div> <div> <label class="block font-semibold mb-2" data-translate="export-data">ส่งออกข้อมูล</label> <button onclick="exportData()" class="w-full p-2 rounded-lg bg-gray-700/50 border border-gray-600 text-left hover:bg-gray-700/70 transition"> <i data-feather="download" class="inline w-4 h-4 mr-2"></i> Download CSV </button> </div> <div> <button onclick="resetData()" class="w-full p-2 rounded-lg bg-red-500/20 border border-red-500 text-red-400 hover:bg-red-500/30 transition"> <i data-feather="trash-2" class="inline w-4 h-4 mr-2"></i> <span data-translate="reset-data">รีเซ็ตข้อมูลจำลอง</span> </button> </div> </div> </div> </div> </div> <script> // Lab Catalog - Complete biomarker definitions const labCatalog = { // Metabolic & Glycemia glucose: { id: 'glucose', label_th: 'น้ำตาล', panel: 'Metabolic', unit_SI: 'mmol/L', unit_US: 'mg/dL', toSI: (v) => v/18, toUS: (v) => v*18, ref_range: {male: {18_39: {low: 3.9, high: 5.6}, 40_59: {low: 4.1, high: 5.8}, 60_: {low: 4.4, high: 6.1}}, female: {18_39: {low: 3.9, high: 5.2}, 40_59: {low: 4.2, high: 5.9}, 60_: {low: 4.5, high: 6.2}}}, direction: 'high_worse', weight: 1.0, color_thresholds: {normal: {low: 3.9, high: 5.6}, borderline: {low: 5.6, high: 6.9}, high_risk: {low: 6.9, high: 999}} }, insulin: { id: 'insulin', label_th: 'อินซูลิน', panel: 'Metabolic', unit_SI: 'pmol/L', unit_US: 'µU/mL', toSI: (v) => v*6.945, toUS: (v) => v/6.945, ref_range: {male: {18_39: {low: 18, high: 180}, 40_59: {low: 18, high: 180}, 60_: {low: 18, high: 180}}, female: {18_39: {low: 18, high: 180}, 40_59: {low: 18, high: 180}, 60_: {low: 18, high: 180}}}, direction: 'high_worse', weight: 1.0 }, hba1c: { id: 'hba1c', label_th: 'HbA1c', panel: 'Metabolic', unit_SI: 'mmol/mol', unit_US: '%', toSI: (v) => (v*10.93)-23.5, toUS: (v) => (v+23.5)/10.93, ref_range: {male: {18_39: {low: 20, high: 42}, 40_59: {low: 20, high: 42}, 60_: {low: 20, high: 42}}, female: {18_39: {low: 20, high: 42}, 40_59: {low: 20, high: 42}, 60_: {low: 20, high: 42}}}, direction: 'high_worse', weight: 1.2 }, // Lipids total_chol: { id: 'total_chol', label_th: 'คอเลสเตอรอลรวม', panel: 'Lipids', unit_SI: 'mmol/L', unit_US: 'mg/dL', toSI: (v) => v/38.67, toUS: (v) => v*38.67, ref_range: {male: {18_39: {low: 3.1, high: 5.2}, 40_59: {low: 3.7, high: 6.2}, 60_: {low: 4.1, high: 6.8}}, female: {18_39: {low: 3.1, high: 5.2}, 40_59: {low: 3.9, high: 6.4}, 60_: {low: 4.4, high: 7.2}}}, direction: 'high_worse', weight: 0.8 }, ldl_c: { id: 'ldl_c', label_th: 'LDL-C', panel: 'Lipids', unit_SI: 'mmol/L', unit_US: 'mg/dL', toSI: (v) => v/38.67, toUS: (v) => v*38.67, ref_range: {male: {18_39: {low: 0, high: 3.0}, 40_59: {low: 0, high: 3.4}, 60_: {low: 0, high: 3.6}}, female: {18_39: {low: 0, high: 2.9}, 40_59: {low: 0, high: 3.3}, 60_: {low: 0, high: 3.8}}}, direction: 'high_worse', weight: 1.2 }, hdl_c: { id: 'hdl_c', label_th: 'HDL-C', panel: 'Lipids', unit_SI: 'mmol/L', unit_US: 'mg/dL', toSI: (v) => v/38.67, toUS: (v) => v*38.67, ref_range: {male: {18_39: {low: 1.0, high: 999}, 40_59: {low: 0.9, high: 999}, 60_: {low: 0.9, high: 999}}, female: {18_39: {low: 1.2, high: 999}, 40_59: {low: 1.1, high: 999}, 60_: {low: 1.0, high: 999}}}, direction: 'low_worse', weight: 1.0 }, triglycerides: { id: 'triglycerides', label_th: 'ไตรกลีเซอไรด์', panel: 'Lipids', unit_SI: 'mmol/L', unit_US: 'mg/dL', toSI: (v) => v/88.54, toUS: (v) => v*88.54, ref_range: {male: {18_39: {low: 0, high: 1.7}, 40_59: {low: 0, high: 2.0}, 60_: {low: 0, high: 2.3}}, female: {18_39: {low: 0, high: 1.5}, 40_59: {low: 0, high: 1.8}, 60_: {low: 0, high: 2.1}}}, direction: 'high_worse', weight: 0.9 }, // Liver ast: { id: 'ast', label_th: 'AST (GOT)', panel: 'Liver', unit_SI: 'U/L', unit_US: 'U/L', toSI: (v) => v, toUS: (v) => v, ref_range: {male: {18_39: {low: 0, high: 40}, 40_59: {low: 0, high: 40}, 60_: {low: 0, high: 40}}, female: {18_39: {low: 0, high: 32}, 40_59: {low: 0, high: 32}, 60_: {low: 0, high: 32}}}, direction: 'high_worse', weight: 0.8 }, alt: { id: 'alt', label_th: 'ALT (GPT)', panel: 'Liver', unit_SI: 'U/L', unit_US: 'U/L', toSI: (v) => v, toUS: (v) => v, ref_range: {male: {18_39: {low: 0, high: 45}, 40_59: {low: 0, high: 45}, 60_: {low: 0, high: 45}}, female: {18_39: {low: 0, high: 34}, 40_59: {low: 0, high: 34}, 60_: {low: 0, high: 34}}}, direction: 'high_worse', weight: 0.9 }, // Renal creatinine: { id: 'creatinine', label_th: 'ครีอะตินีน', panel: 'Renal', unit_SI: 'µmol/L', unit_US: 'mg/dL', toSI: (v) => v*88.4, toUS: (v) => v/88.4, ref_range: {male: {18_39: {low: 62, high: 106}, 40_59: {low: 66, high: 112}, 60_: {low: 72, high: 124}}, female: {18_39: {low: 44, high: 80}, 40_59: {low: 48, high: 86}, 60_: {low: 54, high: 94}}}, direction: 'high_worse', weight: 1.0 }, // Thyroid tsh: { id: 'tsh', label_th: 'TSH', panel: 'Thyroid', unit_SI: 'mIU/L', unit_US: 'µIU/mL', toSI: (v) => v, toUS: (v) => v, ref_range: {male: {18_39: {low: 0.4, high: 4.0}, 40_59: {low: 0.4, high: 4.0}, 60_: {low: 0.5, high: 4.5}}, female: {18_39: {low: 0.4, high: 4.0}, 40_59: {low: 0.4, high: 4.2}, 60_: {low: 0.5, high: 5.0}}}, direction: 'u_shaped', weight: 0.9 }, // Inflammation hs_crp: { id: 'hs_crp', label_th: 'hs-CRP', panel: 'Inflammation', unit_SI: 'mg/L', unit_US: 'mg/L', toSI: (v) => v, toUS: (v) => v, ref_range: {male: {18_39: {low: 0, high: 3.0}, 40_59: {low: 0, high: 3.0}, 60_: {low: 0, high: 4.0}}, female: {18_39: {low: 0, high: 3.0}, 40_59: {low: 0, high: 3.5}, 60_: {low: 0, high: 4.5}}}, direction: 'high_worse', weight: 0.8 }, // Nutrition vitamin_d: { id: 'vitamin_d', label_th: 'วิตามิน D', panel: 'Nutrition', unit_SI: 'nmol/L', unit_US: 'ng/mL', toSI: (v) => v*2.5, toUS: (v) => v/2.5, ref_range: {male: {18_39: {low: 50, high: 999}, 40_59: {low: 50, high: 999}, 60_: {low: 50, high: 999}}, female: {18_39: {low: 50, high: 999}, 40_59: {low: 50, high: 999}, 60_: {low: 50, high: 999}}}, direction: 'low_worse', weight: 0.7 }, ferritin: { id: 'ferritin', label_th: 'เฟอร์ริติน', panel: 'Nutrition', unit_SI: 'µg/L', unit_US: 'ng/mL', toSI: (v) => v, toUS: (v) => v, ref_range: {male: {18_39: {low: 30, high: 300}, 40_59: {low: 30, high: 300}, 60_: {low: 20, high: 300}}, female: {18_39: {low: 15, high: 150}, 40_59: {low: 15, high: 150}, 60_: {low: 10, high: 150}}}, direction: 'u_shaped', weight: 0.8 }, // Hormones testosterone: { id: 'testosterone', label_th: 'เทสโทสเตอโรนรวม', panel: 'Hormones', unit_SI: 'nmol/L', unit_US: 'ng/dL', toSI: (v) => v*0.0347, toUS: (v) => v/0.0347, ref_range: {male: {18_39: {low: 9.9, high: 27.8}, 40_59: {low: 8.6, high: 25.5}, 60_: {low: 6.6, high: 20.9}}, female: {18_39: {low: 0.3, high: 1.7}, 40_59: {low: 0.2, high: 1.4}, 60_: {low: 0.1, high: 1.2}}}, direction: 'u_shaped', weight: 0.6 }, // Hematology hemoglobin: { id: 'hemoglobin', label_th: 'ฮีโมโกลบิน', panel: 'Hematology', unit_SI: 'g/L', unit_US: 'g/dL', toSI: (v) => v*10, toUS: (v) => v/10, ref_range: {male: {18_39: {low: 130, high: 175}, 40_59: {low: 130, high: 175}, 60_: {low: 125, high: 170}}, female: {18_39: {low: 115, high: 155}, 40_59: {low: 115, high: 155}, 60_: {low: 115, high: 155}}}, direction: 'u_shaped', weight: 0.7 } }; // Derived calculation functions const labDerived = { homa_ir: (glucose, insulin, unit_system = 'us') => { const g = unit_system === 'us' ? glucose : labCatalog.glucose.toUS(glucose); const i = unit_system === 'us' ? insulin : labCatalog.insulin.toUS(insulin); return (g * i) / 405; }, ldl_calc: (total_chol, hdl_c, triglycerides, unit_system = 'us') => { const tc = unit_system === 'us' ? total_chol : labCatalog.total_chol.toUS(total_chol); const hdl = unit_system === 'us' ? hdl_c : labCatalog.hdl_c.toUS(hdl_c); const tg = unit_system === 'us' ? triglycerides : labCatalog.triglycerides.toUS(triglycerides); return tg < 400 ? tc - hdl - (tg / 5) : null; }, aip: (triglycerides, hdl_c, unit_system = 'us') => { const tg = unit_system === 'us' ? triglycerides : labCatalog.triglycerides.toUS(triglycerides); const hdl = unit_system === 'us' ? hdl_c : labCatalog.hdl_c.toUS(hdl_c); return Math.log10(tg / hdl); }, tg_hdl_ratio: (triglycerides, hdl_c, unit_system = 'us') => { const tg = unit_system === 'us' ? triglycerides : labCatalog.triglycerides.toUS(triglycerides); const hdl = unit_system === 'us' ? hdl_c : labCatalog.hdl_c.toUS(hdl_c); return tg / hdl; }, egfr: (creatinine, age, sex, unit_system = 'us') => { const scr = unit_system === 'us' ? creatinine : labCatalog.creatinine.toUS(creatinine); const kappa = sex === 'female' ? 0.7 : 0.9; const alpha = sex === 'female' ? -0.241 : -0.302; const female_factor = sex === 'female' ? 1.012 : 1.0; return 142 * Math.min(scr/kappa, 1)**alpha * Math.max(scr/kappa, 1)**(-1.200) * 0.9938**age * female_factor; }, free_testosterone: (testosterone, shbg, albumin, sex, unit_system = 'us') => { const t = unit_system === 'us' ? testosterone : labCatalog.testosterone.toUS(testosterone); const shbg_val = shbg || 40; // Default SHBG const albumin_val = albumin || 4.3; // Default albumin // Vermeulen approximation (simplified) const c1 = 0.0167; // Association constants const c2 = 1.0e-9; const c3 = 1.0e-12; const ft = t / (1 + c1*shbg_val + c2*albumin_val + c3*shbg_val*albumin_val); return ft; }, z_score: (value, mean, sd) => { const z = (value - mean) / sd; return Math.max(-3.5, Math.min(3.5, z)); }, percentile: (z_score) => { // Normal CDF approximation const t = 1 / (1 + 0.2316419 * Math.abs(z_score)); const d = 0.3989423 * Math.exp(-z_score * z_score / 2); const prob = d * t * (0.319381530 + t * (-0.356563782 + t * (1.781477937 + t * (-1.821255978 + t * 1.330274429)))); return z_score > 0 ? 1 - prob : prob; } }; // Lab data generation and management const labData = { currentValues: {}, historicalData: {}, derivedValues: {}, generateMockData: function(months = 24) { const now = new Date(); this.historicalData = {}; for (let i = 0; i < months; i++) { const date = new Date(now); date.setMonth(date.getMonth() - i); const dateKey = date.toISOString().split('T')[0]; this.historicalData[dateKey] = {}; // Generate values for all biomarkers with realistic trends Object.keys(labCatalog).forEach(biomarkerId => { const biomarker = labCatalog[biomarkerId]; const baseValue = this.getBaseValue(biomarkerId); // Add realistic variation and trends let value = baseValue + (Math.random() - 0.5) * baseValue * 0.2; // Add trends based on age/time progression if (i > 6) { // After 6 months if (biomarkerId === 'glucose' || biomarkerId === 'triglycerides') { value *= 1.02; // Gradual increase } else if (biomarkerId === 'hdl_c') { value *= 0.98; // Gradual decrease } } this.historicalData[dateKey][biomarkerId] = value; }); // Set latest values as current if (i === 0) { this.currentValues = {...this.historicalData[dateKey]}; } } this.calculateDerivedValues(); this.saveToStorage(); }, getBaseValue: function(biomarkerId) { // Return baseline values within normal ranges const baseValues = { glucose: 5.2, insulin: 12, hba1c: 35, total_chol: 4.8, ldl_c: 3.0, hdl_c: 1.4, triglycerides: 1.2, ast: 25, alt: 28, creatinine: 85, tsh: 2.5, hs_crp: 2.0, vitamin_d: 60, ferritin: 80, testosterone: 15, hemoglobin: 145 }; return baseValues[biomarkerId] || 50; }, calculateDerivedValues: function() { const current = this.currentValues; const unitSystem = 'us'; // Default to US units for calculations this.derivedValues = { homa_ir: labDerived.homa_ir(current.glucose, current.insulin, unitSystem), ldl_calc: labDerived.ldl_calc(current.total_chol, current.hdl_c, current.triglycerides, unitSystem), aip: labDerived.aip(current.triglycerides, current.hdl_c, unitSystem), tg_hdl_ratio: labDerived.tg_hdl_ratio(current.triglycerides, current.hdl_c, unitSystem), egfr: labDerived.egfr(current.creatinine, 32, 'male', unitSystem), free_testosterone: labDerived.free_testosterone(current.testosterone, null, null, 'male', unitSystem) }; }, getLabWellnessIndex: function() { let totalScore = 0; let totalWeight = 0; // Include both current and derived values const allValues = {...this.currentValues, ...this.derivedValues}; Object.keys(allValues).forEach(key => { let biomarker = labCatalog[key]; if (!biomarker) { // Handle derived values if (key === 'homa_ir') biomarker = {id: 'homa_ir', weight: 1.2, direction: 'high_worse', color_thresholds: {normal: {low: 0, high: 2.5}, borderline: {low: 2.5, high: 3.5}, high_risk: {low: 3.5, high: 999}}}; else if (key === 'aip') biomarker = {id: 'aip', weight: 1.0, direction: 'high_worse', color_thresholds: {normal: {low: -999, high: 0.1}, borderline: {low: 0.1, high: 0.24}, high_risk: {low: 0.24, high: 999}}}; else if (key === 'tg_hdl_ratio') biomarker = {id: 'tg_hdl_ratio', weight: 0.8, direction: 'high_worse', color_thresholds: {normal: {low: 0, high: 2.0}, borderline: {low: 2.0, high: 3.0}, high_risk: {low: 3.0, high: 999}}}; else biomarker = {id: key, weight: 0.5, direction: 'high_worse', color_thresholds: {normal: {low: 0, high: 100}, borderline: {low: 100, high: 200}, high_risk: {low: 200, high: 999}}}; } const value = allValues[key]; const thresholds = biomarker.color_thresholds || {normal: {low: 0, high: 100}, borderline: {low: 100, high: 200}, high_risk: {low: 200, high: 999}}; let score = 100; if (biomarker.direction === 'high_worse') { if (value >= thresholds.high_risk.low) score = 30; else if (value >= thresholds.borderline.low) score = 60; } else if (biomarker.direction === 'low_worse') { if (value <= thresholds.normal.low * 0.5) score = 30; else if (value <= thresholds.normal.low * 0.8) score = 60; } else if (biomarker.direction === 'u_shaped') { if (value < thresholds.normal.low || value > thresholds.normal.high) score = 30; } totalScore += score * (biomarker.weight || 1.0); totalWeight += (biomarker.weight || 1.0); }); return Math.round(totalScore / totalWeight); }, saveToStorage: function() { localStorage.setItem('labData', JSON.stringify({ current: this.currentValues, historical: this.historicalData, derived: this.derivedValues })); }, loadFromStorage: function() { const stored = localStorage.getItem('labData'); if (stored) { const data = JSON.parse(stored); this.currentValues = data.current || {}; this.historicalData = data.historical || {}; this.derivedValues = data.derived || {}; } else { this.generateMockData(); } } }; // Lab rendering functions const labRenderer = { renderPanels: function() { const container = document.getElementById('lab-panels-container'); if (!container) return; container.innerHTML = ''; const panels = {}; // Group biomarkers by panel Object.keys(labCatalog).forEach(id => { const biomarker = labCatalog[id]; if (!panels[biomarker.panel]) { panels[biomarker.panel] = []; } panels[biomarker.panel].push(biomarker); }); // Render each panel Object.keys(panels).forEach(panelName => { const panelCard = document.createElement('div'); panelCard.className = 'card'; let panelHTML = ` <h3 class="font-semibold mb-3 cursor-pointer flex items-center justify-between" onclick="togglePanelExpand('${panelName}')"> ${panelName} <i data-feather="chevron-down" class="w-4 h-4"></i> </h3> <div id="panel-${panelName}" class="space-y-2"> `; panels[panelName].forEach(biomarker => { const value = labData.currentValues[biomarker.id]; if (value !== undefined) { const status = this.getBiomarkerStatus(value, biomarker); panelHTML += ` <div class="flex justify-between items-center p-2 rounded-lg bg-gray-700/30"> <span class="text-sm">${biomarker.label_th}</span> <span class="text-sm font-bold ${status.color}">${value.toFixed(1)} ${biomarker.unit_US} ${status.icon}</span> </div> `; } }); panelHTML += '</div>'; panelCard.innerHTML = panelHTML; container.appendChild(panelCard); }); feather.replace(); }, getBiomarkerStatus: function(value, biomarker) { const thresholds = biomarker.color_thresholds; if (!thresholds) return {color: 'text-gray-400', icon: ''}; let status = {color: 'text-green-400', icon: '✓'}; if (biomarker.direction === 'high_worse') { if (value >= thresholds.high_risk?.low) { status = {color: 'text-red-400', icon: '↑'}; } else if (value >= thresholds.borderline?.low) { status = {color: 'text-yellow-400', icon: '↑'}; } } else if (biomarker.direction === 'low_worse') { if (value <= thresholds.normal?.low * 0.5) { status = {color: 'text-red-400', icon: '↓'}; } else if (value <= thresholds.normal?.low * 0.8) { status = {color: 'text-blue-400', icon: '↓'}; } } else if (biomarker.direction === 'u_shaped') { if (value < thresholds.normal?.low || value > thresholds.normal?.high) { status = {color: 'text-yellow-400', icon: '⚠'}; } } return status; }, renderRadarChart: function() { const canvas = document.getElementById('lab-radar-chart'); if (!canvas) return; const ctx = canvas.getContext('2d'); canvas.width = canvas.offsetWidth; canvas.height = 200; const panels = ['Metabolic', 'Lipids', 'Liver', 'Renal', 'Thyroid', 'Inflammation', 'Nutrition', 'Hematology', 'Hormones']; const panelScores = panels.map(panel => { let totalScore = 0; let count = 0; Object.keys(labCatalog).forEach(id => { if (labCatalog[id].panel === panel) { const value = labData.currentValues[id]; if (value !== undefined) { const status = this.getBiomarkerStatus(value, labCatalog[id]); totalScore += status.color === 'text-green-400' ? 100 : status.color === 'text-yellow-400' ? 60 : status.color === 'text-blue-400' ? 60 : 30; count++; } } }); return count > 0 ? totalScore / count : 50; }); // Draw radar chart const centerX = canvas.width / 2; const centerY = canvas.height / 2; const radius = Math.min(centerX, centerY) - 20; const angleStep = (Math.PI * 2) / panels.length; ctx.strokeStyle = '#10b981'; ctx.lineWidth = 2; ctx.fillStyle = 'rgba(16, 185, 129, 0.2)'; ctx.beginPath(); panelScores.forEach((score, index) => { const angle = angleStep * index - Math.PI / 2; const x = centerX + Math.cos(angle) * radius * (score / 100); const y = centerY + Math.sin(angle) * radius * (score / 100); if (index === 0) { ctx.moveTo(x, y); } else { ctx.lineTo(x, y); } }); ctx.closePath(); ctx.fill(); ctx.stroke(); // Draw labels ctx.fillStyle = '#f1f5f9'; ctx.font = '11px sans-serif'; panels.forEach((panel, index) => { const angle = angleStep * index - Math.PI / 2; const x = centerX + Math.cos(angle) * (radius + 15); const y = centerY + Math.sin(angle) * (radius + 15); ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(panel.substring(0, 8), x, y); }); }, renderHeatmap: function() { const canvas = document.getElementById('lab-heatmap'); if (!canvas) return; const ctx = canvas.getContext('2d'); canvas.width = canvas.offsetWidth; canvas.height = 300; const biomarkers = Object.keys(labCatalog).slice(0, 15); // Limit to 15 for visibility const months = 12; const cellWidth = canvas.width / months; const cellHeight = canvas.height / biomarkers.length; // Draw heatmap biomarkers.forEach((biomarkerId, row) => { for (let col = 0; col < months; col++) { const date = new Date(); date.setMonth(date.getMonth() - (months - col - 1)); const dateKey = date.toISOString().split('T')[0]; const value = labData.historicalData[dateKey]?.[biomarkerId]; if (value !== undefined) { const biomarker = labCatalog[biomarkerId]; const status = this.getBiomarkerStatus(value, biomarker); ctx.fillStyle = status.color === 'text-green-400' ? '#22c55e' : status.color === 'text-yellow-400' ? '#f59e0b' : status.color === 'text-blue-400' ? '#3b82f6' : status.color === 'text-red-400' ? '#ef4444' : '#6b7280'; ctx.fillRect(col * cellWidth, row * cellHeight, cellWidth - 1, cellHeight - 1); } } }); // Draw labels ctx.fillStyle = '#f1f5f9'; ctx.font = '10px sans-serif'; // Month labels const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; monthNames.forEach((month, col) => { ctx.textAlign = 'center'; ctx.fillText(month, col * cellWidth + cellWidth/2, canvas.height - 5); }); // Biomarker labels biomarkers.forEach((biomarkerId, row) => { ctx.textAlign = 'right'; ctx.fillText(labCatalog[biomarkerId].label_th.substring(0, 10), cellWidth - 5, row * cellHeight + cellHeight/2); }); } }; // Lab sub-tab switching function switchLabSubTab(tabName) { // Hide all sub-tabs document.querySelectorAll('.lab-sub-content').forEach(tab => { tab.classList.add('hidden'); }); // Show selected sub-tab document.getElementById(`lab-${tabName}`).classList.remove('hidden'); // Update tab styles document.querySelectorAll('.lab-sub-tab').forEach(tab => { tab.classList.remove('bg-primary/20', 'text-primary'); tab.classList.add('hover:bg-gray-700/30'); }); event.currentTarget.classList.add('bg-primary/20', 'text-primary'); event.currentTarget.classList.remove('hover:bg-gray-700/30'); // Render content based on tab if (tabName === 'overview') { setTimeout(() => labRenderer.renderRadarChart(), 100); } else if (tabName === 'panels') { labRenderer.renderPanels(); } else if (tabName === 'trends') { setTimeout(() => labRenderer.renderHeatmap(), 100); } feather.replace(); } // Lab utility functions function togglePanelExpand(panelName) { const panel = document.getElementById(`panel-${panelName}`); if (panel) { panel.classList.toggle('hidden'); } } function downloadLabTemplate() { const csvContent = "date,biomarker_id,value,unit\n2025-11-01,glucose,95,mg/dL\n2025-11-01,insulin,12,µU/mL\n2025-11-01,total_chol,185,mg/dL\n2025-11-01,hdl_c,45,mg/dL\n2025-11-01,triglycerides,120,mg/dL"; const blob = new Blob([csvContent], { type: 'text/csv' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'lab_template.csv'; a.click(); URL.revokeObjectURL(url); showToast('Template downloaded!'); } function exportLabData() { const data = { current: labData.currentValues, historical: labData.historicalData, derived: labData.derivedValues, catalog: labCatalog }; const jsonContent = JSON.stringify(data, null, 2); const blob = new Blob([jsonContent], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'lab_data.json'; a.click(); URL.revokeObjectURL(url); showToast('Lab data exported!'); } function importLabData(file) { const reader = new FileReader(); reader.onload = function(e) { try { if (file.name.endsWith('.json')) { const data = JSON.parse(e.target.result); labData.currentValues = data.current || {}; labData.historicalData = data.historical || {}; labData.derivedValues = data.derived || {}; } else if (file.name.endsWith('.csv')) { // Parse CSV const lines = e.target.result.split('\n'); const headers = lines[0].split(','); for (let i = 1; i < lines.length; i++) { if (lines[i].trim()) { const values = lines[i].split(','); const date = values[0]; const biomarkerId = values[1]; const value = parseFloat(values[2]); if (!labData.historicalData[date]) { labData.historicalData[date] = {}; } labData.historicalData[date][biomarkerId] = value; if (i === 1) { // First row as current labData.currentValues[biomarkerId] = value; } } } } labData.calculateDerivedValues(); labData.saveToStorage(); showToast('Data imported successfully!'); // Refresh UI if (document.getElementById('tab-advance-lab').classList.contains('active')) { const activeSubTab = document.querySelector('.lab-sub-content:not(.hidden)'); if (activeSubTab) { const tabName = activeSubTab.id.replace('lab-', ''); if (tabName === 'panels') labRenderer.renderPanels(); else if (tabName === 'overview') labRenderer.renderRadarChart(); } } } catch (error) { showToast('Import failed: ' + error.message); } }; reader.readAsText(file); } function recalculateLabData() { labData.calculateDerivedValues(); labData.saveToStorage(); showToast('Lab data recalculated!'); // Refresh UI if (document.getElementById('tab-advance-lab').classList.contains('active')) { const activeSubTab = document.querySelector('.lab-sub-content:not(.hidden)'); if (activeSubTab) { const tabName = activeSubTab.id.replace('lab-', ''); if (tabName === 'panels') labRenderer.renderPanels(); else if (tabName === 'overview') labRenderer.renderRadarChart(); } } } function resetLabData() { if (confirm('Are you sure you want to reset all lab data? This cannot be undone.')) { labData.generateMockData(); showToast('Lab data reset!'); // Refresh UI if (document.getElementById('tab-advance-lab').classList.contains('active')) { const activeSubTab = document.querySelector('.lab-sub-content:not(.hidden)'); if (activeSubTab) { const tabName = activeSubTab.id.replace('lab-', ''); if (tabName === 'panels') labRenderer.renderPanels(); else if (tabName === 'overview') labRenderer.renderRadarChart(); } } } } // File input handler document.addEventListener('DOMContentLoaded', function() { const fileInput = document.getElementById('lab-file-input'); if (fileInput) { fileInput.addEventListener('change', function(e) { const file = e.target.files[0]; if (file) { importLabData(file); } }); } // Initialize lab data labData.loadFromStorage(); }); // Mock Data const mockData = { profile: { name: "Demo User", age: 32, gender: "unspecified" }, today: { date: "2025-11-11", strain: 13.2, recovery: 74, sleep_score: 82, hr_current: 64, hrv_ms: 85, rhr_bpm: 52, resp_rate: 14.2, skin_temp_delta: 0.1 }, sleep: { coach_recommended_bedtime: "22:45", coach_recommended_waketime: "06:30", stages: [ {t: "22:50", stage: "Light", duration: 50}, {t: "23:40", stage: "Deep", duration: 90}, {t: "01:10", stage: "REM", duration: 50}, {t: "02:00", stage: "Light", duration: 80}, {t: "03:20", stage: "Deep", duration: 140}, {t: "05:40", stage: "REM", duration: 50}, {t: "06:30", stage: "Awake", duration: 0} ], history: generateSleepHistory(14) }, recovery_history: generateRecoveryHistory(30), strain_history: generateStrainHistory(30), workouts: generateWorkouts(10), journal_logs: [], hrv_data: generateHRVData(14), rhr_data: generateRHRData(14) }; // Language data const translations = { th: { "app-title": "VitalTrack Pro", "today": "วันนี้", "recovery": "การฟื้นตัว", "sleep": "การนอนหลับ", "training": "การฝึก", "trends": "แนวโน้ม", "nav-today": "วันนี้", "nav-recovery": "ฟื้นตัว", "nav-sleep": "นอน", "nav-training": "ฝึก", "nav-trends": "แนวโน้ม", "daily-overview": "ภาพรวมประจำวัน", "strain": "ความเหนื่อย", "current-hr": "อัตราการเต้นหัวใจปัจจุบัน", "timeline": "ไทม์ไลน์กิจกรรม", "log-journal": "บันทึก Journal", "recovery-score": "คะแนนการฟื้นตัว", "poor": "แย่", "fair": "ปานกลาง", "good": "ดี", "excellent": "ยอดเยี่ยม", "resting-hr": "อัตราการเต้นหัวใจขณะพัก", "factors": "ปัจจัยที่ส่งผล", "sleep-performance": "ประสิทธิภาพการนอน", "yesterday-strain": "ความเหนื่อยเมื่อวาน", "respiration-rate": "อัตราการหายใจ", "skin-temp": "อุณหภูมิผิวหนัง", "sleep-coach": "Sleep Coach", "bedtime": "เวลาเข้านอน", "wake-time": "ตื่นนอน", "sleep-goal": "เป้าหมาย: 7.5 ชั่วโมงตามความเหนื่อยวันนี้", "sleep-stages": "ระยะการนอนหลับ", "sleep-history": "ประวัติการนอนหลับ (14 วัน)", "start-workout": "เริ่ม Live Workout", "select-sport": "เลือกชนิดกีฬา", "recent-workouts": "การฝึกล่าสุด", "weekly-report": "สรุปประจำสัปดาห์", "nutrition": "โภชนาการ", "lifestyle": "ไลฟ์สไตล์", "recovery-tools": "เครื่องมือฟื้นตัว", "mood": "อารมณ์", "save": "บันทึก", "settings": "การตั้งค่า", "units": "หน่วย", "export-data": "ส่งออกข้อมูล", "reset-data": "รีเซ็ตข้อมูลจำลอง" }, en: { "app-title": "VitalTrack Pro", "today": "Today", "recovery": "Recovery", "sleep": "Sleep", "training": "Training", "trends": "Trends", "nav-today": "Today", "nav-recovery": "Recovery", "nav-sleep": "Sleep", "nav-training": "Training", "nav-trends": "Trends", "daily-overview": "Daily Overview", "strain": "Strain", "current-hr": "Current Heart Rate", "timeline": "Activity Timeline", "log-journal": "Log Journal", "recovery-score": "Recovery Score", "poor": "Poor", "fair": "Fair", "good": "Good", "excellent": "Excellent", "resting-hr": "Resting Heart Rate", "factors": "Factors", "sleep-performance": "Sleep Performance", "yesterday-strain": "Yesterday's Strain", "respiration-rate": "Respiration Rate", "skin-temp": "Skin Temperature", "sleep-coach": "Sleep Coach", "bedtime": "Bedtime", "wake-time": "Wake Time", "sleep-goal": "Goal: 7.5 hours based on today's strain", "sleep-stages": "Sleep Stages", "sleep-history": "Sleep History (14 days)", "start-workout": "Start Live Workout", "select-sport": "Select Sport", "recent-workouts": "Recent Workouts", "weekly-report": "Weekly Summary", "nutrition": "Nutrition", "lifestyle": "Lifestyle", "recovery-tools": "Recovery Tools", "mood": "Mood", "save": "Save", "settings": "Settings", "units": "Units", "export-data": "Export Data", "reset-data": "Reset Mock Data" } }; // Global state let currentLang = 'th'; let isDarkMode = true; let workoutInterval = null; let workoutStartTime = null; let liveHRData = []; let hrChartInstance = null; // Generate mock data functions function generateSleepHistory(days) { const history = []; for (let i = days - 1; i >= 0; i--) { const date = new Date(); date.setDate(date.getDate() - i); history.push({ date: date.toISOString().split('T')[0], duration: 7 + Math.random() * 2, efficiency: 75 + Math.random() * 20, deep: Math.random() * 2, rem: Math.random() * 2, light: 4 + Math.random() * 2 }); } return history; } function generateRecoveryHistory(days) { const history = []; for (let i = days - 1; i >= 0; i--) { const date = new Date(); date.setDate(date.getDate() - i); history.push({ date: date.toISOString().split('T')[0], recovery: 60 + Math.random() * 30, rhr: 45 + Math.random() * 20, hrv: 60 + Math.random() * 60 }); } return history; } function generateStrainHistory(days) { const history = []; for (let i = days - 1; i >= 0; i--) { const date = new Date(); date.setDate(date.getDate() - i); history.push({ date: date.toISOString().split('T')[0], strain: 5 + Math.random() * 15 }); } return history; } function generateWorkouts(count) { const workouts = []; const sports = ['Run', 'Bike', 'Gym', 'Swim', 'HIIT', 'Yoga']; for (let i = 0; i < count; i++) { const date = new Date(); date.setDate(date.getDate() - i); workouts.push({ date: date.toISOString().split('T')[0], sport: sports[Math.floor(Math.random() * sports.length)], duration_min: 30 + Math.random() * 60, kcal: 200 + Math.random() * 400, avg_hr: 100 + Math.random() * 60, max_hr: 150 + Math.random() * 30, strain: 5 + Math.random() * 10 }); } return workouts; } function generateHRVData(days) { const data = []; for (let i = days - 1; i >= 0; i--) { data.push(60 + Math.random() * 60); } return data; } function generateRHRData(days) { const data = []; for (let i = days - 1; i >= 0; i--) { data.push(45 + Math.random() * 20); } return data; } // Initialize app function initApp() { feather.replace(); initializeCharts(); updateDateTime(); setInterval(updateDateTime, 60000); setInterval(updateLiveHR, 1000); renderWorkoutList(); } // Update date/time function updateDateTime() { const now = new Date(); const options = { year: 'numeric', month: 'long', day: 'numeric' }; const dateStr = now.toLocaleDateString(currentLang === 'th' ? 'th-TH' : 'en-US', options); document.getElementById('current-date').textContent = dateStr; } // Tab switching function switchTab(tabName) { // Hide all tabs document.querySelectorAll('.tab-content').forEach(tab => { tab.classList.remove('active'); }); // Show selected tab document.getElementById(`tab-${tabName}`).classList.add('active'); // Update nav document.querySelectorAll('.nav-item').forEach(item => { item.classList.remove('active'); }); event.currentTarget.classList.add('active'); // Reinitialize charts if needed if (tabName === 'recovery') { drawRecoveryCharts(); } else if (tabName === 'sleep') { drawSleepCharts(); } else if (tabName === 'trends') { drawTrendsCharts(); } else if (tabName === 'advance-lab') { // Initialize lab tab with overview setTimeout(() => { // Set default sub-tab document.querySelectorAll('.lab-sub-tab').forEach(tab => { tab.classList.remove('bg-primary/20', 'text-primary'); tab.classList.add('hover:bg-gray-700/30'); }); document.querySelector('.lab-sub-tab').classList.add('bg-primary/20', 'text-primary'); document.querySelector('.lab-sub-tab').classList.remove('hover:bg-gray-700/30'); // Show overview, hide others document.querySelectorAll('.lab-sub-content').forEach(tab => { tab.classList.add('hidden'); }); document.getElementById('lab-overview').classList.remove('hidden'); // Render overview labRenderer.renderRadarChart(); }, 100); } feather.replace(); } // Theme toggle function toggleTheme() { isDarkMode = !isDarkMode; document.body.classList.toggle('light-mode'); localStorage.setItem('theme', isDarkMode ? 'dark' : 'light'); // Update icon const icon = document.querySelector('button[onclick="toggleTheme()"] i'); icon.setAttribute('data-feather', isDarkMode ? 'moon' : 'sun'); feather.replace(); } // Language toggle function toggleLanguage() { currentLang = currentLang === 'th' ? 'en' : 'th'; localStorage.setItem('language', currentLang); document.getElementById('lang-toggle').textContent = currentLang.toUpperCase(); // Update all translatable elements document.querySelectorAll('[data-translate]').forEach(element => { const key = element.getAttribute('data-translate'); if (translations[currentLang][key]) { element.textContent = translations[currentLang][key]; } }); } // Modal functions function openJournalModal() { document.getElementById('journal-modal').classList.add('active'); } function closeJournalModal() { document.getElementById('journal-modal').classList.remove('active'); } function openSettingsModal() { document.getElementById('settings-modal').classList.add('active'); } function closeSettingsModal() { document.getElementById('settings-modal').classList.remove('active'); } // Save journal function saveJournal() { const journalEntry = { date: new Date().toISOString(), mood: document.querySelector('select').value, entries: [] }; document.querySelectorAll('#journal-modal input[type="checkbox"]:checked').forEach(checkbox => { journalEntry.entries.push(checkbox.nextElementSibling.textContent); }); mockData.journal_logs.push(journalEntry); closeJournalModal(); // Show success message showToast('Journal saved successfully!'); } // Workout functions function startWorkout() { document.getElementById('live-workout').classList.remove('hidden'); workoutStartTime = Date.now(); liveHRData = []; workoutInterval = setInterval(() => { updateLiveWorkout(); }, 1000); } function endWorkout() { if (workoutInterval) { clearInterval(workoutInterval); workoutInterval = null; } // Save workout const workout = { date: new Date().toISOString().split('T')[0], sport: 'Workout', duration_min: Math.floor((Date.now() - workoutStartTime) / 60000), kcal: parseInt(document.getElementById('live-kcal').textContent), avg_hr: Math.floor(liveHRData.reduce((a, b) => a + b, 0) / liveHRData.length), max_hr: Math.max(...liveHRData), strain: parseFloat(document.getElementById('live-strain').textContent) }; mockData.workouts.unshift(workout); renderWorkoutList(); document.getElementById('live-workout').classList.add('hidden'); showToast('Workout completed!'); } function updateLiveWorkout() { const elapsed = Math.floor((Date.now() - workoutStartTime) / 1000); const minutes = Math.floor(elapsed / 60); const seconds = elapsed % 60; document.getElementById('live-time').textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; // Update calories (rough estimate) const calories = Math.floor(elapsed * 0.15); document.getElementById('live-kcal').textContent = calories; // Update strain const strain = (elapsed / 60000) * 2; document.getElementById('live-strain').textContent = strain.toFixed(1); // Update HR with simulation const hr = 120 + Math.floor(Math.random() * 40); document.getElementById('live-hr').textContent = hr; liveHRData.push(hr); // Update live HR chart drawLiveHRChart(); } // Render workout list function renderWorkoutList() { const workoutList = document.getElementById('workout-list'); workoutList.innerHTML = ''; mockData.workouts.slice(0, 5).forEach(workout => { const div = document.createElement('div'); div.className = 'flex items-center gap-3 p-3 rounded-lg hover:bg-gray-800/50 transition'; div.innerHTML = ` <i data-feather="activity" class="w-4 h-4 text-blue-400"></i> <div class="flex-1"> <div class="font-medium text-sm">${workout.sport}</div> <div class="text-xs opacity-75">${workout.duration_min} min • ${workout.kcal} kcal • Avg HR ${workout.avg_hr}</div> </div> <div class="text-sm font-semibold text-purple-400">${workout.strain.toFixed(1)}</div> `; workoutList.appendChild(div); }); feather.replace(); } // Chart functions function initializeCharts() { // HR Chart drawHRChart(); } function drawHRChart() { const canvas = document.getElementById('hr-chart'); if (!canvas) return; const ctx = canvas.getContext('2d'); canvas.width = canvas.offsetWidth; canvas.height = 80; // Generate random HR data const data = []; for (let i = 0; i < 50; i++) { data.push(60 + Math.random() * 20); } // Draw line chart ctx.strokeStyle = '#ef4444'; ctx.lineWidth = 2; ctx.beginPath(); const step = canvas.width / (data.length - 1); data.forEach((value, index) => { const x = index * step; const y = canvas.height - (value - 60) * 3; if (index === 0) { ctx.moveTo(x, y); } else { ctx.lineTo(x, y); } }); ctx.stroke(); } function drawLiveHRChart() { const canvas = document.getElementById('live-hr-chart'); if (!canvas) return; const ctx = canvas.getContext('2d'); canvas.width = canvas.offsetWidth; canvas.height = 100; ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw line chart ctx.strokeStyle = '#ef4444'; ctx.lineWidth = 2; ctx.beginPath(); const step = canvas.width / (liveHRData.length - 1); liveHRData.forEach((value, index) => { const x = index * step; const y = canvas.height - (value - 100) * 1.5; if (index === 0) { ctx.moveTo(x, y); } else { ctx.lineTo(x, y); } }); ctx.stroke(); } function drawRecoveryCharts() { drawHRVChart(); drawRHRChart(); } function drawHRVChart() { const canvas = document.getElementById('hrv-chart'); if (!canvas) return; const ctx = canvas.getContext('2d'); canvas.width = canvas.offsetWidth; canvas.height = 150; ctx.strokeStyle = '#10b981'; ctx.lineWidth = 2; ctx.beginPath(); const step = canvas.width / (mockData.hrv_data.length - 1); mockData.hrv_data.forEach((value, index) => { const x = index * step; const y = canvas.height - (value - 60); if (index === 0) { ctx.moveTo(x, y); } else { ctx.lineTo(x, y); } }); ctx.stroke(); } function drawRHRChart() { const canvas = document.getElementById('rhr-chart'); if (!canvas) return; const ctx = canvas.getContext('2d'); canvas.width = canvas.offsetWidth; canvas.height = 150; const barWidth = canvas.width / mockData.rhr_data.length - 2; mockData.rhr_data.forEach((value, index) => { const x = index * (barWidth + 2); const height = value * 2; const y = canvas.height - height; ctx.fillStyle = '#f59e0b'; ctx.fillRect(x, y, barWidth, height); }); } function drawSleepCharts() { drawSleepStagesChart(); drawSleepHistoryChart(); } function drawSleepStagesChart() { const canvas = document.getElementById('sleep-stages-chart'); if (!canvas) return; const ctx = canvas.getContext('2d'); canvas.width = canvas.offsetWidth; canvas.height = 150; const stages = mockData.sleep.stages; let currentX = 0; const colors = { 'Awake': '#a855f7', 'Light': '#60a5fa', 'Deep': '#2563eb', 'REM': '#06b6d4' }; stages.forEach(stage => { const width = (stage.duration / 360) * canvas.width; ctx.fillStyle = colors[stage.stage]; ctx.fillRect(currentX, 0, width, canvas.height); currentX += width; }); } function drawSleepHistoryChart() { const canvas = document.getElementById('sleep-history-chart'); if (!canvas) return; const ctx = canvas.getContext('2d'); canvas.width = canvas.offsetWidth; canvas.height = 150; const data = mockData.sleep.history; const barWidth = canvas.width / data.length - 2; data.forEach((day, index) => { const x = index * (barWidth + 2); const height = day.efficiency; const y = canvas.height - height; ctx.fillStyle = '#3b82f6'; ctx.fillRect(x, y, barWidth, height); }); } function drawTrendsCharts() { drawCombinedChart(); drawHRVRHRChart(); } function drawCombinedChart() { const canvas = document.getElementById('combined-chart'); if (!canvas) return; const ctx = canvas.getContext('2d'); canvas.width = canvas.offsetWidth; canvas.height = 200; // Draw strain line ctx.strokeStyle = '#ef4444'; ctx.lineWidth = 2; ctx.beginPath(); const step = canvas.width / (mockData.strain_history.length - 1); mockData.strain_history.forEach((day, index) => { const x = index * step; const y = canvas.height - day.strain * 10; if (index === 0) { ctx.moveTo(x, y); } else { ctx.lineTo(x, y); } }); ctx.stroke(); // Draw recovery line ctx.strokeStyle = '#22c55e'; ctx.lineWidth = 2; ctx.beginPath(); mockData.recovery_history.slice(0, 30).forEach((day, index) => { const x = index * step; const y = canvas.height - day.recovery * 1.5; if (index === 0) { ctx.moveTo(x, y); } else { ctx.lineTo(x, y); } }); ctx.stroke(); } function drawHRVRHRChart() { const canvas = document.getElementById('hrv-rhr-chart'); if (!canvas) return; const ctx = canvas.getContext('2d'); canvas.width = canvas.offsetWidth; canvas.height = 200; // Draw scatter plot correlation mockData.recovery_history.forEach((day, index) => { const x = (day.hrv / 120) * canvas.width; const y = canvas.height - (day.rhr / 65) * canvas.height; ctx.fillStyle = 'rgba(16, 185, 129, 0.6)'; ctx.beginPath(); ctx.arc(x, y, 4, 0, Math.PI * 2); ctx.fill(); }); } function setTrendPeriod(period) { // Update button styles document.querySelectorAll('.flex.gap-2 button').forEach(btn => { btn.classList.remove('bg-primary/20', 'text-primary'); btn.classList.add('hover:bg-gray-700/30'); }); event.target.classList.add('bg-primary/20', 'text-primary'); event.target.classList.remove('hover:bg-gray-700/30'); // Redraw charts with new period drawTrendsCharts(); } // Update live HR function updateLiveHR() { const hr = 55 + Math.floor(Math.random() * 20); document.getElementById('current-hr').textContent = hr; document.getElementById('hr_current') && (document.getElementById('hr_current').textContent = hr); } // Export data function exportData() { const dataStr = JSON.stringify(mockData, null, 2); const dataBlob = new Blob([dataStr], {type: 'application/json'}); const url = URL.createObjectURL(dataBlob); const link = document.createElement('a'); link.href = url; link.download = 'vitaltrack-data.json'; link.click(); showToast('Data exported successfully!'); } // Reset data function resetData() { if (confirm('Are you sure you want to reset all mock data?')) { location.reload(); } } // Toast notification function showToast(message) { const toast = document.createElement('div'); toast.className = 'fixed top-20 left-1/2 transform -translate-x-1/2 bg-green-500 text-white px-4 py-2 rounded-lg shadow-lg z-50'; toast.textContent = message; document.body.appendChild(toast); setTimeout(() => { toast.remove(); }, 3000); } // Load saved preferences function loadPreferences() { const savedTheme = localStorage.getItem('theme'); if (savedTheme === 'light') { toggleTheme(); } const savedLang = localStorage.getItem('language'); if (savedLang) { currentLang = savedLang; document.getElementById('lang-toggle').textContent = currentLang.toUpperCase(); toggleLanguage(); } } // Initialize on load document.addEventListener('DOMContentLoaded', () => { loadPreferences(); initApp(); }); // Handle resize window.addEventListener('resize', () => { drawHRChart(); if (document.getElementById('tab-recovery').classList.contains('active')) { drawRecoveryCharts(); } else if (document.getElementById('tab-sleep').classList.contains('active')) { drawSleepCharts(); } else if (document.getElementById('tab-trends').classList.contains('active')) { drawTrendsCharts(); } }); </script> <script src="https://huggingface.co/deepsite/deepsite-badge.js"></script> </body> </html>
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>VitalTrack Pro</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js"></script>
<script src="https://unpkg.com/feather-icons"></script>
<style>
:root {
--primary: #10b981;
--primary-dark: #059669;
--secondary: #06b6d4;
--secondary-dark: #0891b2;
--bg-dark: #0f172a;
--bg-light: #f8fafc;
--card-dark: #1e293b;
--card-light: #ffffff;
--text-dark: #f1f5f9;
--text-light: #0f172a;
--border-dark: #334155;
--border-light: #e2e8f0;
--success: #22c55e;
--warning: #f59e0b;
--danger: #ef4444;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'SF Pro Display', 'Prompt', sans-serif;
background: var(--bg-dark);
color: var(--text-dark);
min-height: 100vh;
overflow-x: hidden;
}
body.light-mode {
background: var(--bg-light);
color: var(--text-light);
}
.card {
background: var(--card-dark);
border-radius: 16px;
padding: 16px;
box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
border: 1px solid var(--border-dark);
}
body.light-mode .card {
background: var(--card-light);
border-color: var(--border-light);
}
.tab-content {
display: none;
animation: fadeIn 0.3s ease-in-out;
}
.tab-content.active {
display: block;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
.bottom-nav {
position: fixed;
bottom: 0;
left: 0;
right: 0;
background: var(--card-dark);
border-top: 1px solid var(--border-dark);
padding: 8px 0;
z-index: 100;
}
body.light-mode .bottom-nav {
background: var(--card-light);
}
.nav-item {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
padding: 8px;
cursor: pointer;
transition: all 0.2s;
}