HTMLify
script.js
Views: 44 | Author: karbonsites
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 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 | // --- Mock Data Store --- const MOCK_USER_DATA = { id: 'U1001', name: 'Jane Doe', email: 'jane.doe@example.com', age: 30, height: '165 cm', weight: '68 kg', occupation: 'Software Engineer', moodLogs: [ { date: '2024-07-20', mood: 'Energetic', notes: 'Great workout.' }, { date: '2024-07-21', mood: 'Neutral', notes: 'Long meeting.' }, { date: '2024-07-22', mood: 'Stressed', notes: 'Deadline approaching.' }, { date: '2024-07-23', mood: 'Energetic', notes: 'Feeling positive.' }, { date: '2024-07-24', mood: 'Tired', notes: 'Slept poorly.' }, ], recommendations: [ { id: 'R001', title: 'Mindful Breathing Session', source: 'AI Mental Health' }, { id: 'R002', title: 'Low-Impact Cardio Plan', source: 'AI Physical Health' } ] }; const MOCK_PRODUCTS = [ { id: 'P001', name: 'ErgoFlow Office Chair', price: 15000, desc: 'Supports posture for long working hours.', img: 'https://via.placeholder.com/150/A0C4FF/FFFFFF?text=Ergonomic+Chair' }, { id: 'P002', name: 'Serenity Herbal Tea', price: 850, desc: 'Natural blend to aid relaxation before sleep.', img: 'https://via.placeholder.com/150/FFC3A0/FFFFFF?text=Calm+Tea' } ]; // --- Utility Functions --- function getActivePage() { const path = window.location.pathname; if (path.includes('index.html') || path === '/' || path.endsWith('/')) return 'index'; if (path.includes('profile.html')) return 'profile'; if (path.includes('tips.html')) return 'tips'; if (path.includes('admin.html')) return 'admin'; return 'index'; } function showMessage(elementId, message, isError = false) { const el = document.getElementById(elementId); if (el) { el.textContent = message; el.style.backgroundColor = isError ? 'rgba(220, 53, 69, 0.2)' : 'rgba(40, 167, 69, 0.2)'; el.style.color = isError ? 'var(--color-error)' : 'var(--color-success)'; el.style.display = 'block'; setTimeout(() => { el.style.display = 'none'; }, 5000); } } // --- Core Initialization --- document.addEventListener('DOMContentLoaded', () => { const page = getActivePage(); if (page === 'index') { initializeDashboard(); } else if (page === 'profile') { initializeProfile(); } else if (page === 'tips') { initializeTipsPage(); } else if (page === 'admin') { initializeAdminPanel(); } }); // --- Dashboard Logic --- function initializeDashboard() { renderRecommendationsDashboard(); setupCheckinListeners(); updateHealthSnapshot(); } function setupCheckinListeners() { const moodButtons = document.querySelectorAll('.mood-btn'); const submitButton = document.getElementById('submitCheckin'); let selectedMood = null; moodButtons.forEach(button => { button.addEventListener('click', function() { moodButtons.forEach(btn => btn.classList.remove('selected')); this.classList.add('selected'); selectedMood = this.dataset.mood; }); }); submitButton.addEventListener('click', () => { const notes = document.getElementById('dailyNotes').value.trim(); const messageEl = document.getElementById('checkinMessage'); if (!selectedMood) { messageEl.textContent = 'Please select how you are feeling today.'; messageEl.style.backgroundColor = 'rgba(220, 53, 69, 0.2)'; messageEl.style.color = 'var(--color-error)'; return; } // Mock logging const today = new Date().toISOString().slice(0, 10); MOCK_USER_DATA.moodLogs.push({ date: today, mood: selectedMood, notes: notes || '(No notes provided)' }); messageEl.textContent = `Success! Logged mood: ${selectedMood}. Thank you for checking in.`; messageEl.style.backgroundColor = 'rgba(40, 167, 69, 0.2)'; messageEl.style.color = 'var(--color-success)'; document.getElementById('dailyNotes').value = ''; moodButtons.forEach(btn => btn.classList.remove('selected')); selectedMood = null; updateHealthSnapshot(); }); } function updateHealthSnapshot() { const logs = MOCK_USER_DATA.moodLogs; // Compliance (Example: 5/7 days logged in the last 7 entries) const compliance = Math.min(100, (logs.length / 7) * 100); document.getElementById('complianceRate').textContent = `${Math.round(compliance)}%`; // Last Mood Log if (logs.length > 0) { const lastMood = logs[logs.length - 1].mood; document.getElementById('lastMood').textContent = lastMood; } else { document.getElementById('lastMood').textContent = 'N/A'; } } function renderRecommendationsDashboard() { const recList = document.getElementById('recList'); if (!recList) return; // Showing top 2 recommendations from the general list for the dashboard const displayRecs = MOCK_USER_DATA.recommendations.slice(0, 2); recList.innerHTML = displayRecs.map(rec => ` <article class="tip-card"> <h4>${rec.title}</h4> <p>A personalized suggestion based on your recent activity.</p> <span class="tip-source">${rec.source}</span> </article> `).join(''); if (displayRecs.length === 0) { recList.innerHTML = '<p style="color: var(--color-text-muted);">No personalized recommendations available right now.</p>'; } } // --- Profile Logic --- function initializeProfile() { populateProfileData(); renderMoodChart(); } function populateProfileData() { document.getElementById('profUserId').textContent = MOCK_USER_DATA.id; document.getElementById('profName').textContent = MOCK_USER_DATA.name; document.getElementById('profEmail').textContent = MOCK_USER_DATA.email; document.getElementById('profAge').textContent = MOCK_USER_DATA.age; document.getElementById('profHeight').textContent = MOCK_USER_DATA.height; document.getElementById('profWeight').textContent = MOCK_USER_DATA.weight; document.getElementById('profOccupation').textContent = MOCK_USER_DATA.occupation; } function renderMoodChart() { const ctx = document.getElementById('moodChart').getContext('2d'); // Prepare data for the last 7 days const recentLogs = MOCK_USER_DATA.moodLogs.slice(-7); const labels = recentLogs.map(log => log.date.substring(5)); // MM-DD // Map moods to numerical values for simple charting (for visualization purposes) const moodMap = { 'Energetic': 4, 'Neutral': 3, 'Tired': 2, 'Stressed': 1 }; const dataValues = recentLogs.map(log => moodMap[log.mood] || 0); new Chart(ctx, { type: 'line', data: { labels: labels, datasets: [{ label: 'Mental State Score (1=Low, 4=High)', data: dataValues, backgroundColor: 'rgba(0, 123, 255, 0.5)', borderColor: 'rgba(0, 123, 255, 1)', borderWidth: 2, tension: 0.3, fill: true }] }, options: { responsive: true, maintainAspectRatio: false, scales: { y: { beginAtZero: true, max: 4.5, ticks: { color: 'var(--color-text-muted)' } }, x: { ticks: { color: 'var(--color-text-muted)' } } }, plugins: { legend: { display: false }, title: { display: false } } } }); } // --- Tips & Products Logic --- function initializeTipsPage() { renderTips(); renderProductList(); setupMpesaModal(); } function renderTips() { const tipContainer = document.getElementById('tipContainer'); if (!tipContainer) return; // Clear default tip and render all AI tips tipContainer.innerHTML = MOCK_USER_DATA.recommendations.map(rec => ` <article class="tip-card"> <h4>${rec.title}</h4> <p>This tip is generated based on your profile data indicating a need for ${rec.source.includes('Mental') ? 'mental balance' : 'physical activity/rest'}. Focus on incorporating this today.</p> <span class="tip-source">${rec.source}</span> </article> `).join(''); if (MOCK_USER_DATA.recommendations.length === 0) { tipContainer.innerHTML = '<p style="color: var(--color-text-muted);">No new AI tips available. Check back later!</p>'; } } function renderProductList() { const productList = document.getElementById('productList'); if (!productList) return; productList.innerHTML = MOCK_PRODUCTS.map(product => ` <div class="product-card" data-id="${product.id}"> <img src="${product.img}" alt="${product.name}"> <h4>${product.name}</h4> <p class="price">KSh ${product.price.toLocaleString()}</p> <p class="description">${product.desc}</p> <button class="buy-button" data-product-id="${product.id}" data-product-name="${product.name}" data-product-price="${product.price}">Purchase via Mpesa</button> </div> `).join(''); } function setupMpesaModal() { const modal = document.getElementById('mpesaModal'); const closeBtn = document.querySelector('.close-button'); const buyButtons = document.querySelectorAll('.buy-button'); const confirmBtn = document.getElementById('confirmMpesaPayment'); const phoneInput = document.getElementById('mpesaPhone'); const statusEl = document.getElementById('paymentStatus'); let currentProductId = null; // Open Modal buyButtons.forEach(button => { button.addEventListener('click', function() { currentProductId = this.dataset.productId; const name = this.dataset.productName; const price = this.dataset.productPrice; document.getElementById('modalProductName').textContent = name; document.getElementById('modalPrice').textContent = `KSh ${parseInt(price).toLocaleString()}`; phoneInput.value = ''; statusEl.textContent = ''; modal.style.display = 'block'; }); }); // Close Modal closeBtn.onclick = () => modal.style.display = 'none'; window.onclick = (event) => { if (event.target === modal) { modal.style.display = 'none'; } }; // Handle Payment confirmBtn.addEventListener('click', () => { const phone = phoneInput.value.trim(); if (!/^0[71][0-9]{8}$/.test(phone)) { // Basic Kenyan mobile number check statusEl.textContent = 'Please enter a valid 10-digit Mpesa phone number starting with 07 or 01.'; statusEl.style.backgroundColor = 'rgba(220, 53, 69, 0.2)'; statusEl.style.color = 'var(--color-error)'; return; } statusEl.textContent = 'Sending payment request via Mpesa API...'; statusEl.style.backgroundColor = 'rgba(255, 140, 0, 0.2)'; statusEl.style.color = '#ff8c00'; // --- Mock API Call --- setTimeout(() => { // Success Simulation const productName = document.getElementById('modalProductName').textContent; statusEl.textContent = `Successfully initiated Mpesa payment for ${productName}. Check your phone for confirmation.`; statusEl.style.backgroundColor = 'rgba(40, 167, 69, 0.2)'; statusEl.style.color = 'var(--color-success)'; phoneInput.value = ''; // Close after success message display setTimeout(() => { modal.style.display = 'none'; }, 3000); }, 2000); }); } // --- Admin Logic --- function initializeAdminPanel() { // Mock population for admin view populateAdminUserList(); // Setup form listeners document.getElementById('broadcastForm').addEventListener('submit', handleBroadcastSubmit); document.getElementById('productForm').addEventListener('submit', handleProductSubmit); } function populateAdminUserList() { const userListEl = document.getElementById('userList'); if (!userListEl) return; // Mock users (simulating data retrieved from a DB) const mockAdmins = [ { name: 'John Smith', email: 'john@mail.com', status: 'Active' }, { name: 'Alice Johnson', email: 'alice@mail.com', status: 'Inactive' }, { name: 'Robert Brown', email: 'rob@mail.com', status: 'Active' }, { name: 'Emily Davis', email: 'emily@mail.com', status: 'Active' } ]; userListEl.innerHTML = mockAdmins.map(user => ` <li class="user-item"> <span>${user.name} (${user.email})</span> <span class="user-status ${user.status.toLowerCase()}">${user.status}</span> </li> `).join(''); } function handleBroadcastSubmit(e) { e.preventDefault(); const type = document.getElementById('broadcastType').value; const title = document.getElementById('broadcastTitle').value; const content = document.getElementById('broadcastContent').value; // Simulate sending to backend/notification service console.log(`Admin Broadcast: Type=${type}, Title=${title}, Content=${content}`); showMessage('broadcastMessage', `Successfully queued ${type} broadcast: "${title}"`, false); document.getElementById('broadcastForm').reset(); } function handleProductSubmit(e) { e.preventDefault(); const name = document.getElementById('productName').value; const price = parseInt(document.getElementById('productPrice').value); const desc = document.getElementById('productDesc').value; const image = document.getElementById('productImage').value; // Mock adding new product const newProduct = { id: 'P' + (1000 + MOCK_PRODUCTS.length), name: name, price: price, desc: desc, img: image }; MOCK_PRODUCTS.push(newProduct); console.log('New Product Added:', newProduct); showMessage('productMessage', `Product "${name}" added successfully! It is now available for recommendation.`, false); document.getElementById('productForm').reset(); // If navigated to tips page, re-render product list (Though this is complex without routing, we log it) if (getActivePage() === 'tips') { renderProductList(); } } // --- APK Compilation Instructions --- // The request asks for APK instructions, which cannot be executed in a web environment. // Providing instructions as a console log/comment is the best simulation. console.log("\n--- MOCK APK Compilation Instructions for Android Project ---\n"); console.log("NOTE: This code structure represents the frontend (HTML/CSS/JS) mock-up. A real Android application requires a native framework (like React Native, Flutter, or native Android/Java/Kotlin) to handle push notifications, Mpesa integration, and true APK compilation.\n"); console.log("If this were a standard Android Studio project (Java/Kotlin):"); console.log("1. Ensure Android SDK and NDK are installed in Android Studio."); console.log("2. Open the project in Android Studio."); console.log("3. Go to Build > Generate Signed Bundle / APK."); console.log("4. Select APK and follow the wizard to create a Keystore if you don't have one."); console.log("5. Choose 'release' build variant."); console.log("6. Click Finish. The signed APK will be generated in the 'app/release' directory."); |