// Theme Management const themeManager = { init() { const savedTheme = localStorage.getItem('theme') || 'light'; document.documentElement.classList.toggle('dark', savedTheme === 'dark'); this.updateComponentThemes(); }, toggle() { const isDark = document.documentElement.classList.toggle('dark'); localStorage.setItem('theme', isDark ? 'dark' : 'light'); this.updateComponentThemes(); }, updateComponentThemes() { const isDark = document.documentElement.classList.contains('dark'); document.querySelectorAll('custom-navbar, custom-footer').forEach(el => { el.classList.toggle('dark', isDark); }); } }; // Role-Based Authentication System const authManager = { users: [ { id: 'admin1', email: 'admin@lifeline.com', password: 'admin123', role: 'admin', name: 'Command Center', permissions: ['full_access', 'map_control', 'team_dispatch', 'analytics'] }, { id: 'responder1', email: 'responder@lifeline.com', password: 'respond123', role: 'responder', name: 'Field Responder', permissions: ['map_view', 'case_update', 'gps_share'] }, { id: 'victim1', email: 'victim@lifeline.com', password: 'help123', role: 'victim', name: 'Emergency User', permissions: ['report_emergency', 'view_status', 'voice_call'] } ], init() { const currentUser = this.getCurrentUser(); if (currentUser) { this.updateUIForRole(currentUser); } }, login(email, password, role) { const user = this.users.find(u => u.email === email && u.password === password && u.role === role); if (user) { const session = { ...user, loginTime: Date.now(), sessionId: this.generateSessionId() }; localStorage.setItem('currentUser', JSON.stringify(session)); this.updateUIForRole(session); return { success: true, user: session }; } return { success: false, error: 'Invalid credentials or role' }; }, loginAs(role) { // Quick login for demo purposes const user = this.users.find(u => u.role === role); if (user) { const session = { ...user, loginTime: Date.now(), sessionId: this.generateSessionId() }; localStorage.setItem('currentUser', JSON.stringify(session)); return { success: true, user: session }; } return { success: false }; }, logout() { localStorage.removeItem('currentUser'); window.location.href = 'index.html'; }, getCurrentUser() { return JSON.parse(localStorage.getItem('currentUser') || 'null'); }, hasPermission(permission) { const user = this.getCurrentUser(); return user && user.permissions.includes(permission); }, generateSessionId() { return 'sess_' + Math.random().toString(36).substr(2, 9); }, updateUIForRole(user) { // Update navbar const navbar = document.querySelector('custom-navbar'); if (navbar) { navbar.updateUserDisplay && navbar.updateUserDisplay(); } // Apply role-based restrictions document.body.setAttribute('data-role', user.role); // Hide/show elements based on permissions document.querySelectorAll('[data-permission]').forEach(el => { const required = el.dataset.permission.split(','); const hasAccess = required.some(p => user.permissions.includes(p)); el.style.display = hasAccess ? '' : 'none'; }); }, requireAuth(requiredRole, redirectTo = 'index.html') { const user = this.getCurrentUser(); if (!user || (requiredRole && user.role !== requiredRole)) { window.location.href = redirectTo; return false; } return true; } }; // Global logout function function logout() { authManager.logout(); } // IVR System Simulation const ivrSystem = { isActive: false, currentStep: 0, collectedData: {}, steps: [ { message: "Welcome to Lifeline Nexus Emergency Response. Please select your emergency type.", options: [ { key: '1', label: 'Medical Emergency', value: 'medical' }, { key: '2', label: 'Fire / Explosion', value: 'fire' }, { key: '3', label: 'Flood / Natural Disaster', value: 'flood' }, { key: '4', label: 'Trapped / Structural', value: 'trapped' } ] }, { message: "How many people need assistance?", options: [ { key: '1', label: 'Just myself', value: 1 }, { key: '2', label: '2-3 people', value: 3 }, { key: '3', label: '4-10 people', value: 10 }, { key: '4', label: 'More than 10', value: 20 } ] }, { message: "Are you in immediate danger?", options: [ { key: '1', label: 'Yes, life threatening', value: 'critical' }, { key: '2', label: 'Yes, but stable', value: 'high' }, { key: '3', label: 'No immediate danger', value: 'medium' }, { key: '4', label: 'Reporting for others', value: 'low' } ] }, { message: "Please state your location after the beep, or press 1 to use GPS.", options: [ { key: '1', label: 'Use GPS Location', value: 'gps' } ] } ], start() { this.isActive = true; this.currentStep = 0; this.collectedData = {}; this.speak(this.steps[0].message); this.updateUI(); }, speak(text) { if ('speechSynthesis' in window) { const utterance = new SpeechSynthesisUtterance(text); utterance.rate = 0.9; utterance.pitch = 1; speechSynthesis.speak(utterance); } }, handleInput(input) { const step = this.steps[this.currentStep]; const option = step.options.find(opt => opt.key === input); if (option) { this.collectedData[`step${this.currentStep}`] = option.value; this.currentStep++; if (this.currentStep < this.steps.length) { this.speak(this.steps[this.currentStep].message); this.updateUI(); } else { this.complete(); } } }, updateUI() { const statusEl = document.getElementById('ivr-status'); const optionsEl = document.getElementById('ivr-options'); if (statusEl && optionsEl && this.currentStep < this.steps.length) { const step = this.steps[this.currentStep]; statusEl.textContent = step.message; optionsEl.innerHTML = step.options.map(opt => ` `).join(''); } }, complete() { const statusEl = document.getElementById('ivr-status'); const optionsEl = document.getElementById('ivr-options'); if (statusEl && optionsEl) { statusEl.textContent = "Thank you. Help is on the way. Your case ID is " + this.generateCaseId(); optionsEl.innerHTML = `

Emergency Reported Successfully

Response team dispatched

`; feather.replace(); // Store in localStorage for demo this.saveEmergencyReport(); } }, generateCaseId() { return 'LN-' + Date.now().toString(36).toUpperCase(); }, saveEmergencyReport() { const reports = JSON.parse(localStorage.getItem('emergencyReports') || '[]'); reports.push({ id: this.generateCaseId(), data: this.collectedData, timestamp: new Date().toISOString(), status: 'dispatched' }); localStorage.setItem('emergencyReports', JSON.stringify(reports)); } }; // Real-time Stats Animation const statsAnimator = { animate(elementId, targetValue, duration = 2000) { const element = document.getElementById(elementId); if (!element) return; const startTime = performance.now(); const startValue = 0; const isTime = typeof targetValue === 'string' && targetValue.includes('min'); const animate = (currentTime) => { const elapsed = currentTime - startTime; const progress = Math.min(elapsed / duration, 1); const easeProgress = 1 - Math.pow(1 - progress, 3); if (isTime) { const minutes = (4.2 * easeProgress).toFixed(1); element.textContent = minutes + ' min'; } else { const current = Math.floor(startValue + (parseInt(targetValue.replace(/,/g, '')) - startValue) * easeProgress); element.textContent = current.toLocaleString(); } if (progress < 1) { requestAnimationFrame(animate); } }; requestAnimationFrame(animate); } }; // Geolocation Helper const geoHelper = { getCurrentPosition() { return new Promise((resolve, reject) => { if (!navigator.geolocation) { reject(new Error('Geolocation not supported')); return; } navigator.geolocation.getCurrentPosition( (position) => resolve({ lat: position.coords.latitude, lng: position.coords.longitude, accuracy: position.coords.accuracy }), (error) => reject(error), { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 } ); }); }, async getAddressFromCoords(lat, lng) { // Simulated reverse geocoding return `Near ${lat.toFixed(4)}, ${lng.toFixed(4)}`; } }; // WebSocket Simulation for Real-time Updates class RealtimeUpdates { constructor() { this.subscribers = []; this.simulateUpdates(); } subscribe(callback) { this.subscribers.push(callback); return () => { const index = this.subscribers.indexOf(callback); if (index > -1) this.subscribers.splice(index, 1); }; } simulateUpdates() { setInterval(() => { const update = { type: 'emergency', data: { id: 'LN-' + Date.now().toString(36).toUpperCase(), type: ['medical', 'fire', 'flood', 'trapped'][Math.floor(Math.random() * 4)], location: { lat: 37.7749 + (Math.random() - 0.5) * 0.1, lng: -122.4194 + (Math.random() - 0.5) * 0.1 }, severity: ['critical', 'high', 'medium', 'low'][Math.floor(Math.random() * 4)], timestamp: new Date().toISOString() } }; this.subscribers.forEach(cb => cb(update)); }, 30000); // New emergency every 30 seconds } } const realtime = new RealtimeUpdates(); // Utility Functions const utils = { formatTimeAgo(dateString) { const date = new Date(dateString); const now = new Date(); const seconds = Math.floor((now - date) / 1000); if (seconds < 60) return 'Just now'; if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`; if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`; return `${Math.floor(seconds / 86400)}d ago`; }, debounce(func, wait) { let timeout; return function executedFunction(...args) { const later = () => { clearTimeout(timeout); func(...args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); }; }, generateId() { return 'id-' + Math.random().toString(36).substr(2, 9); } }; // Enhanced Map Management const mapManager = { map: null, markers: [], layers: {}, heatmapLayer: null, routingControl: null, init(containerId, options = {}) { if (this.map) return this.map; // Default to San Francisco if no center provided const center = options.center || [37.7749, -122.4194]; const zoom = options.zoom || 12; this.map = L.map(containerId, { zoomControl: false, attributionControl: false }).setView(center, zoom); // Add tile layers this.layers.street = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '© OpenStreetMap' }); this.layers.satellite = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', { maxZoom: 19, attribution: '© Esri' }); this.layers.dark = L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', { maxZoom: 19, attribution: '© CARTO' }); // Default to street view this.layers.street.addTo(this.map); // Add zoom control to bottom right L.control.zoom({ position: 'bottomright' }).addTo(this.map); // Add scale control L.control.scale({ position: 'bottomleft', imperial: false }).addTo(this.map); // Initialize heatmap layer this.initHeatmap(); // Add custom controls this.addCustomControls(); return this.map; }, initHeatmap() { // Simulated heatmap using canvas overlay const canvas = document.createElement('canvas'); canvas.style.position = 'absolute'; canvas.style.top = '0'; canvas.style.left = '0'; canvas.style.pointerEvents = 'none'; canvas.style.zIndex = '400'; this.heatmapCanvas = canvas; // Add to map pane this.map.createPane('heatmapPane'); this.map.getPane('heatmapPane').appendChild(canvas); this.updateHeatmap(); }, updateHeatmap() { // Generate random heat points based on emergency data const emergencies = JSON.parse(localStorage.getItem('emergencyReports') || '[]'); const points = emergencies.map(e => { // Generate random coordinates near center if not provided return [ 37.7749 + (Math.random() - 0.5) * 0.1, -122.4194 + (Math.random() - 0.5) * 0.1, e.severity === 'critical' ? 1 : e.severity === 'high' ? 0.7 : 0.4 ]; }); // Add some static heat points for demo points.push( [37.7849, -122.4094, 0.9], [37.7649, -122.4294, 0.6], [37.7749, -122.3994, 0.8] ); this.heatPoints = points; this.renderHeatmap(); }, renderHeatmap() { const canvas = this.heatmapCanvas; const size = this.map.getSize(); canvas.width = size.x; canvas.height = size.y; const ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); this.heatPoints.forEach(point => { const latLng = L.latLng(point[0], point[1]); const pixel = this.map.latLngToContainerPoint(latLng); const intensity = point[2]; const gradient = ctx.createRadialGradient(pixel.x, pixel.y, 0, pixel.x, pixel.y, 50); gradient.addColorStop(0, `rgba(239, 68, 68, ${intensity * 0.6})`); gradient.addColorStop(0.5, `rgba(249, 115, 22, ${intensity * 0.3})`); gradient.addColorStop(1, 'rgba(239, 68, 68, 0)'); ctx.fillStyle = gradient; ctx.beginPath(); ctx.arc(pixel.x, pixel.y, 50, 0, Math.PI * 2); ctx.fill(); }); }, addCustomControls() { // Layer control const layerControl = L.control({ position: 'topright' }); layerControl.onAdd = () => { const div = L.DomUtil.create('div', 'leaflet-bar leaflet-control'); div.innerHTML = `
`; return div; }; layerControl.addTo(this.map); // Update heatmap on move this.map.on('moveend zoomend', () => this.renderHeatmap()); }, setBaseLayer(type) { Object.values(this.layers).forEach(l => this.map.removeLayer(l)); this.layers[type].addTo(this.map); }, toggleHeatmap(show) { this.heatmapCanvas.style.display = show ? 'block' : 'none'; }, toggleMarkers(show) { this.markers.forEach(m => { if (show) m.addTo(this.map); else m.remove(); }); }, addEmergencyMarker(emergency, options = {}) { const colors = { critical: '#ef4444', high: '#f97316', medium: '#eab308', low: '#22c55e' }; const icons = { medical: 'activity', fire: 'flame', flood: 'cloud-rain', trapped: 'layers' }; const color = colors[emergency.severity] || '#6b7280'; const iconSvg = this.getIconSvg(icons[emergency.type] || 'alert-circle', color); const customIcon = L.divIcon({ html: `
${iconSvg}
`, className: 'custom-marker', iconSize: [40, 50], iconAnchor: [20, 50] }); const marker = L.marker([emergency.lat, emergency.lng], { icon: customIcon }).addTo(this.map); const popupContent = `
${emergency.severity} ${emergency.type}

${emergency.description || 'No description'}

${emergency.peopleCount || 1} people • ${utils.formatTimeAgo(emergency.timestamp)}
${options.showActions ? `
` : ''}
`; marker.bindPopup(popupContent); this.markers.push(marker); // Animate marker on add const el = marker.getElement(); if (el) { el.style.transform += ' scale(0)'; setTimeout(() => { el.style.transition = 'transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)'; el.style.transform = el.style.transform.replace(' scale(0)', ' scale(1)'); }, 10); } return marker; }, addResponderMarker(responder) { const icon = L.divIcon({ html: `
`, className: 'responder-marker', iconSize: [36, 36], iconAnchor: [18, 18] }); const marker = L.marker([responder.lat, responder.lng], { icon }).addTo(this.map); marker.bindPopup(`

${responder.name}

${responder.status}

${responder.eta || 'On standby'}

`); this.markers.push(marker); return marker; }, getIconSvg(name, color) { const icons = { activity: '', flame: '', 'cloud-rain': '', layers: '', 'alert-circle': '' }; return icons[name] || icons['alert-circle']; }, drawRoute(from, to, options = {}) { if (this.routingControl) { this.map.removeLayer(this.routingControl); } // Simple line for demo - in production use proper routing service const latlngs = [ [from.lat, from.lng], [to.lat, to.lng] ]; this.routingControl = L.polyline(latlngs, { color: options.color || '#3b82f6', weight: 4, opacity: 0.8, dashArray: options.dashed ? '10, 10' : null }).addTo(this.map); // Add distance label const midPoint = L.latLng( (from.lat + to.lat) / 2, (from.lng + to.lng) / 2 ); const distance = this.map.distance( L.latLng(from.lat, from.lng), L.latLng(to.lat, to.lng) ); const label = L.marker(midPoint, { icon: L.divIcon({ html: `
${(distance / 1000).toFixed(1)} km
`, className: 'distance-label', iconSize: [60, 20], iconAnchor: [30, 10] }) }).addTo(this.map); this.markers.push(label); return this.routingControl; }, fitToMarkers() { if (this.markers.length === 0) return; const group = new L.featureGroup(this.markers); this.map.fitBounds(group.getBounds().pad(0.1)); }, centerOnLocation(lat, lng, zoom = 15) { this.map.setView([lat, lng], zoom); }, clearMarkers() { this.markers.forEach(m => this.map.removeLayer(m)); this.markers = []; } }; // Initialize document.addEventListener('DOMContentLoaded', () => { themeManager.init(); authManager.init(); // Animate stats on homepage if (document.getElementById('stat-rescues')) { setTimeout(() => { statsAnimator.animate('stat-rescues', '12847'); statsAnimator.animate('stat-response', '4.2 min'); statsAnimator.animate('stat-active', '156'); statsAnimator.animate('stat-volunteers', '2341'); }, 500); } // Keyboard shortcuts document.addEventListener('keydown', (e) => { if ((e.ctrlKey || e.metaKey) && e.key === 'd') { e.preventDefault(); themeManager.toggle(); } if (e.key === 'Escape') { closeIVRDemo(); closeAllModals(); } }); // Update component themes themeManager.updateComponentThemes(); }); function closeAllModals() { document.querySelectorAll('[id$="-modal"]').forEach(modal => { modal.classList.add('hidden'); modal.classList.remove('flex'); }); } function dispatchTeam(emergencyId) { alert(`Dispatching team to emergency ${emergencyId}`); } function viewDetails(emergencyId) { alert(`Viewing details for ${emergencyId}`); } // Global functions for onclick handlers function startIVRDemo() { document.getElementById('ivr-modal').classList.remove('hidden'); document.getElementById('ivr-modal').classList.add('flex'); ivrSystem.start(); } function closeIVRDemo() { document.getElementById('ivr-modal').classList.add('hidden'); document.getElementById('ivr-modal').classList.remove('flex'); ivrSystem.isActive = false; if ('speechSynthesis' in window) { speechSynthesis.cancel(); } } function toggleTheme() { themeManager.toggle(); }