// ThaiRice NDVI Visualizer - Main JavaScript // Initialize application document.addEventListener('DOMContentLoaded', function() { console.log('ThaiRice NDVI Visualizer initialized'); // Initialize components initNDVIInteractions(); initDateDisplay(); initHealthScoreAnimation(); initChartSimulation(); // Set up service worker for offline functionality if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js').catch(console.error); } }); // NDVI Map Interactions function initNDVIInteractions() { const mapControls = document.querySelectorAll('.map-control'); const ndviImage = document.querySelector('img[alt="Rice Field NDVI Map"]'); mapControls.forEach(control => { control.addEventListener('click', function(e) { e.preventDefault(); const action = this.querySelector('i').getAttribute('data-feather'); switch(action) { case 'zoom-in': simulateZoom(1.2); break; case 'zoom-out': simulateZoom(0.8); break; case 'maximize': toggleFullscreen(ndviImage); break; } // Add click feedback this.classList.add('scale-95'); setTimeout(() => this.classList.remove('scale-95'), 150); }); }); } // Simulate zoom effect function simulateZoom(factor) { const mapContainer = document.querySelector('.relative.h-96'); const img = mapContainer.querySelector('img'); // Store current transform const currentTransform = img.style.transform || 'scale(1)'; const currentScale = parseFloat(currentTransform.match(/scale\(([^)]+)\)/)?.[1] || 1); const newScale = currentScale * factor; // Limit zoom range if (newScale < 0.5 || newScale > 3) return; img.style.transform = `scale(${newScale})`; img.style.transition = 'transform 0.3s ease'; // Update controls state updateZoomControls(newScale); } function updateZoomControls(scale) { const zoomIn = document.querySelector('[data-feather="zoom-in"]').closest('button'); const zoomOut = document.querySelector('[data-feather="zoom-out"]').closest('button'); zoomIn.disabled = scale >= 3; zoomOut.disabled = scale <= 0.5; } function toggleFullscreen(element) { if (!document.fullscreenElement) { if (element.requestFullscreen) { element.requestFullscreen(); } else if (element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } else if (element.msRequestFullscreen) { element.msRequestFullscreen(); } } else { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } } } // Initialize date display function initDateDisplay() { const dateElements = document.querySelectorAll('[data-date-format]'); const now = new Date(); dateElements.forEach(element => { const format = element.getAttribute('data-date-format'); let formattedDate; switch(format) { case 'relative': formattedDate = getRelativeDate(now); break; case 'full': formattedDate = now.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }); break; default: formattedDate = now.toLocaleDateString(); } if (element.tagName === 'INPUT') { element.value = formattedDate; } else { element.textContent = formattedDate; } }); } function getRelativeDate(date) { const now = new Date(); const diffMs = now - date; const diffMins = Math.floor(diffMs / 60000); const diffHours = Math.floor(diffMins / 60); const diffDays = Math.floor(diffHours / 24); if (diffMins < 1) return 'Just now'; if (diffMins < 60) return `${diffMins} minutes ago`; if (diffHours < 24) return `${diffHours} hours ago`; if (diffDays === 1) return 'Yesterday'; if (diffDays < 7) return `${diffDays} days ago`; return date.toLocaleDateString(); } // Animate health score function initHealthScoreAnimation() { const healthScore = document.querySelector('.inline-flex.items-center.justify-center'); if (!healthScore) return; // Add animation class healthScore.classList.add('pulse-slow'); // Simulate real-time updates setInterval(() => { const randomChange = Math.random() * 0.02 - 0.01; // +/- 1% const currentScore = parseFloat(healthScore.querySelector('span').textContent); const newScore = Math.min(100, Math.max(0, currentScore + randomChange)); healthScore.querySelector('span').textContent = `${newScore.toFixed(1)}%`; // Update gradient based on score updateHealthGradient(newScore); }, 10000); // Update every 10 seconds } function updateHealthGradient(score) { const healthIndicator = document.querySelector('.health-indicator'); if (!healthIndicator) return; let color; if (score >= 80) color = '#10b981'; // Green else if (score >= 60) color = '#f59e0b'; // Amber else color = '#ef4444'; // Red healthIndicator.style.setProperty('--indicator-color', color); } // Simulate chart data updates function initChartSimulation() { const chartBars = document.querySelectorAll('.bg-gradient-to-t'); if (!chartBars.length) return; // Animate bars on load setTimeout(() => { chartBars.forEach((bar, index) => { bar.style.height = bar.style.height || getComputedStyle(bar).height; bar.style.height = '0'; setTimeout(() => { bar.style.transition = 'height 0.8s ease'; bar.style.height = bar.dataset.originalHeight || bar.style.height; }, index * 100); }); }, 500); // Simulate real-time updates setInterval(() => { const currentNDVI = document.querySelector('.text-2xl.font-bold.text-green-700'); if (!currentNDVI) return; const currentValue = parseFloat(currentNDVI.textContent); const randomChange = (Math.random() * 0.04 - 0.02); // +/- 0.02 const newValue = Math.min(0.9, Math.max(0.1, currentValue + randomChange)); // Animate the change animateValue(currentNDVI, currentValue, newValue, 1000); // Update trend indicator updateTrendIndicator(randomChange); }, 15000); // Update every 15 seconds } function animateValue(element, start, end, duration) { const startTime = performance.now(); function update(currentTime) { const elapsed = currentTime - startTime; const progress = Math.min(elapsed / duration, 1); const current = start + (end - start) * progress; element.textContent = current.toFixed(2); if (progress < 1) { requestAnimationFrame(update); } } requestAnimationFrame(update); } function updateTrendIndicator(change) { const trendElement = document.querySelector('.text-xs.text-green-600.mt-1'); if (!trendElement) return; const icon = trendElement.querySelector('i'); const text = trendElement.querySelector('span') || trendElement; if (change > 0) { icon.setAttribute('data-feather', 'trending-up'); text.textContent = `+${Math.abs(change).toFixed(2)} from last update`; trendElement.className = 'text-xs text-green-600 mt-1'; } else if (change < 0) { icon.setAttribute('data-feather', 'trending-down'); text.textContent = `-${Math.abs(change).toFixed(2)} from last update`; trendElement.className = 'text-xs text-red-600 mt-1'; } else { icon.setAttribute('data-feather', 'minus'); text.textContent = 'No change from last update'; trendElement.className = 'text-xs text-gray-600 mt-1'; } feather.replace(); } // Export functionality function exportNDVIReport() { const reportData = { fieldId: 'TH-RF-2023-042', location: 'Suphan Buri, Thailand', area: '15.3 hectares', ndviScore: document.querySelector('.text-4xl.font-bold.text-white')?.textContent || '82%', currentNDVI: document.querySelector('.text-2xl.font-bold.text-green-700')?.textContent || '0.62', lastUpdated: new Date().toISOString(), recommendations: Array.from(document.querySelectorAll('.bg-gradient-to-br')).map(card => ({ category: card.querySelector('h3')?.textContent, status: card.querySelector('p.text-sm')?.textContent, details: card.querySelector('p.text-gray-700')?.textContent })) }; // Create download link const dataStr = JSON.stringify(reportData, null, 2); const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr); const exportFileDefaultName = `ndvi-report-${reportData.fieldId}-${new Date().toISOString().split('T')[0]}.json`; const linkElement = document.createElement('a'); linkElement.setAttribute('href', dataUri); linkElement.setAttribute('download', exportFileDefaultName); linkElement.click(); // Show notification showNotification('Report exported successfully!', 'success'); } // Notification system function showNotification(message, type = 'info') { const notification = document.createElement('div'); notification.className = `fixed top-4 right-4 z-50 px-6 py-4 rounded-lg shadow-lg transform transition-transform duration-300 translate-x-full ${ type === 'success' ? 'bg-green-500 text-white' : type === 'error' ? 'bg-red-500 text-white' : 'bg-blue-500 text-white' }`; notification.textContent = message; document.body.appendChild(notification); // Animate in setTimeout(() => { notification.classList.remove('translate-x-full'); }, 10); // Auto remove after 5 seconds setTimeout(() => { notification.classList.add('translate-x-full'); setTimeout(() => notification.remove(), 300); }, 5000); } // Error handling window.addEventListener('error', function(e) { console.error('Application error:', e.error); showNotification('An error occurred. Please refresh the page.', 'error'); }); // Performance monitoring if ('performance' in window) { window.addEventListener('load', function() { const timing = performance.timing; const loadTime = timing.loadEventEnd - timing.navigationStart; console.log(`Page loaded in ${loadTime}ms`); if (loadTime > 3000) { console.warn('Page load time exceeds 3 seconds'); } }); }