File size: 29,469 Bytes
517fb3f
1c4deee
 
 
 
 
517fb3f
1c4deee
 
 
 
 
517fb3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c4deee
 
 
517fb3f
 
 
 
1c4deee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
517fb3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c4deee
 
 
 
517fb3f
1c4deee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
517fb3f
1c4deee
 
517fb3f
 
 
1c4deee
 
517fb3f
 
 
 
 
 
 
 
 
 
 
 
 
 
1c4deee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764

// 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 => `
                <button onclick="ivrSystem.handleInput('${opt.key}')" 
                    class="w-full p-4 rounded-xl bg-gray-100 dark:bg-gray-700 hover:bg-primary-100 dark:hover:bg-primary-900/30 transition-colors text-left flex items-center gap-3">
                    <span class="w-8 h-8 rounded-full bg-primary-500 text-white flex items-center justify-center text-sm font-bold">${opt.key}</span>
                    <span class="text-gray-700 dark:text-gray-300">${opt.label}</span>
                </button>
            `).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 = `
                <div class="p-6 rounded-xl bg-green-100 dark:bg-green-900/30 text-center">
                    <i data-feather="check-circle" class="w-12 h-12 text-green-600 dark:text-green-400 mx-auto mb-2"></i>
                    <p class="text-green-800 dark:text-green-200 font-semibold">Emergency Reported Successfully</p>
                    <p class="text-sm text-green-600 dark:text-green-400 mt-1">Response team dispatched</p>
                </div>
            `;
            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 = `
                <div style="background:white;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,0.15);padding:8px;">
                    <button onclick="mapManager.setBaseLayer('street')" style="display:block;width:100%;padding:6px 12px;border:none;background:#f3f4f6;border-radius:4px;margin-bottom:4px;cursor:pointer;font-size:12px;">Street</button>
                    <button onclick="mapManager.setBaseLayer('satellite')" style="display:block;width:100%;padding:6px 12px;border:none;background:transparent;border-radius:4px;margin-bottom:4px;cursor:pointer;font-size:12px;">Satellite</button>
                    <button onclick="mapManager.setBaseLayer('dark')" style="display:block;width:100%;padding:6px 12px;border:none;background:transparent;border-radius:4px;cursor:pointer;font-size:12px;">Dark</button>
                    <div style="border-top:1px solid #e5e7eb;margin:8px 0;"></div>
                    <label style="display:flex;align-items:center;gap:6px;font-size:12px;cursor:pointer;">
                        <input type="checkbox" checked onchange="mapManager.toggleHeatmap(this.checked)" style="accent-color:#ef4444;">
                        Heatmap
                    </label>
                    <label style="display:flex;align-items:center;gap:6px;font-size:12px;cursor:pointer;margin-top:4px;">
                        <input type="checkbox" checked onchange="mapManager.toggleMarkers(this.checked)" style="accent-color:#ef4444;">
                        Markers
                    </label>
                </div>
            `;
            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: `
                <div style="position:relative;">
                    <div style="width:40px;height:40px;background:${color};border-radius:50%;display:flex;align-items:center;justify-content:center;box-shadow:0 4px 12px rgba(0,0,0,0.3);border:3px solid white;">
                        ${iconSvg}
                    </div>
                    <div style="position:absolute;bottom:-8px;left:50%;transform:translateX(-50%);width:0;height:0;border-left:8px solid transparent;border-right:8px solid transparent;border-top:10px solid ${color};"></div>
                </div>
            `,
            className: 'custom-marker',
            iconSize: [40, 50],
            iconAnchor: [20, 50]
        });
        
        const marker = L.marker([emergency.lat, emergency.lng], { icon: customIcon }).addTo(this.map);
        
        const popupContent = `
            <div style="min-width:200px;">
                <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
                    <span style="padding:4px 8px;background:${color};color:white;border-radius:4px;font-size:11px;font-weight:600;text-transform:uppercase;">${emergency.severity}</span>
                    <span style="font-size:11px;color:#6b7280;">${emergency.type}</span>
                </div>
                <p style="margin:0 0 8px;font-size:13px;color:#374151;">${emergency.description || 'No description'}</p>
                <div style="display:flex;align-items:center;gap:8px;font-size:12px;color:#6b7280;">
                    <span>${emergency.peopleCount || 1} people</span>
                    <span>•</span>
                    <span>${utils.formatTimeAgo(emergency.timestamp)}</span>
                </div>
                ${options.showActions ? `
                    <div style="display:flex;gap:8px;margin-top:12px;">
                        <button onclick="dispatchTeam('${emergency.id}')" style="flex:1;padding:8px;background:#ef4444;color:white;border:none;border-radius:6px;font-size:12px;cursor:pointer;">Dispatch</button>
                        <button onclick="viewDetails('${emergency.id}')" style="flex:1;padding:8px;background:#f3f4f6;color:#374151;border:none;border-radius:6px;font-size:12px;cursor:pointer;">Details</button>
                    </div>
                ` : ''}
            </div>
        `;
        
        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: `
                <div style="width:36px;height:36px;background:#3b82f6;border-radius:50%;display:flex;align-items:center;justify-content:center;box-shadow:0 4px 12px rgba(59,130,246,0.4);border:3px solid white;">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2">
                        <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
                    </svg>
                </div>
            `,
            className: 'responder-marker',
            iconSize: [36, 36],
            iconAnchor: [18, 18]
        });
        
        const marker = L.marker([responder.lat, responder.lng], { icon }).addTo(this.map);
        
        marker.bindPopup(`
            <div style="min-width:150px;">
                <p style="margin:0 0 4px;font-weight:600;color:#374151;">${responder.name}</p>
                <p style="margin:0;font-size:12px;color:#6b7280;">${responder.status}</p>
                <p style="margin:4px 0 0;font-size:11px;color:#3b82f6;">${responder.eta || 'On standby'}</p>
            </div>
        `);
        
        this.markers.push(marker);
        return marker;
    },
    
    getIconSvg(name, color) {
        const icons = {
            activity: '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>',
            flame: '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"/></svg>',
            'cloud-rain': '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><line x1="16" y1="13" x2="16" y2="21"/><line x1="8" y1="13" x2="8" y2="21"/><line x1="12" y1="15" x2="12" y2="23"/><path d="M20 16.58A5 5 0 0 0 18 7h-1.26A8 8 0 1 0 4 15.25"/></svg>',
            layers: '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg>',
            'alert-circle': '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>'
        };
        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: `<div style="background:#3b82f6;color:white;padding:4px 8px;border-radius:4px;font-size:11px;font-weight:600;white-space:nowrap;">${(distance / 1000).toFixed(1)} km</div>`,
                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();
}