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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
{% extends "base.html" %}

{% block head %}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<style>
    .container-fluid {
        padding: 0;
        height: 100vh;
        display: flex;
    }
    
    #emergencyMap { 
        height: 100vh;
        width: 70%;
        position: relative;
    }
    
    .control-panel {
        width: 30%;
        height: 100vh;
        background: rgba(26, 26, 46, 0.95);
        padding: 20px;
        overflow-y: auto;
        display: flex;
        flex-direction: column;
        gap: 15px;
    }
    
    .control-section {
        background: rgba(255, 255, 255, 0.05);
        border-radius: var(--border-radius);
        padding: 15px;
        margin-bottom: 15px;
    }
    
    .section-title {
        color: var(--text-light);
        font-size: 1.1rem;
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .emergency-button {
        background: linear-gradient(135deg, var(--primary-color), var(--accent-color));
        color: white;
        border: none;
        padding: 12px 20px;
        border-radius: var(--border-radius);
        font-size: 1rem;
        font-weight: bold;
        cursor: pointer;
        transition: var(--transition);
        width: 100%;
        margin-bottom: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
    }
    
    .emergency-button:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(255, 77, 109, 0.3);
    }
    
    .emergency-button.secondary {
        background: rgba(255, 255, 255, 0.1);
    }
    
    .emergency-description {
        width: 100%;
        padding: 10px;
        margin-top: 10px;
        background: rgba(255, 255, 255, 0.1);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: var(--border-radius);
        color: var(--text-color);
        resize: vertical;
        min-height: 60px;
    }
    
    .emergency-timer {
        color: var(--primary-color);
        font-size: 1.1rem;
        text-align: center;
        margin-top: 10px;
        font-weight: bold;
    }
    
    .medical-form {
        display: none;
        background: rgba(255, 255, 255, 0.05);
        padding: 15px;
        border-radius: var(--border-radius);
        margin-top: 10px;
    }
    
    .medical-form input,
    .medical-form textarea {
        width: 100%;
        padding: 8px;
        margin-bottom: 10px;
        background: rgba(255, 255, 255, 0.1);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: var(--border-radius);
        color: var(--text-color);
    }
    
    .emergency-contacts {
        display: flex;
        flex-direction: column;
        gap: 10px;
    }
    
    .contact-item {
        display: flex;
        align-items: center;
        gap: 10px;
        background: rgba(255, 255, 255, 0.05);
        padding: 10px;
        border-radius: var(--border-radius);
    }
    
    .contact-item button {
        background: none;
        border: none;
        color: var(--text-light);
        cursor: pointer;
        padding: 5px;
    }
    
    .contact-item button:hover {
        color: var(--primary-color);
    }
    
    .hospital-list {
        max-height: 200px;
        overflow-y: auto;
    }
    
    .hospital-item {
        background: rgba(255, 255, 255, 0.05);
        padding: 10px;
        margin-bottom: 8px;
        border-radius: var(--border-radius);
        cursor: pointer;
        transition: var(--transition);
    }
    
    .hospital-item:hover {
        background: rgba(255, 255, 255, 0.1);
    }
    
    .location-request {
        position: absolute;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        background: rgba(26, 26, 46, 0.95);
        padding: 15px 25px;
        border-radius: var(--border-radius);
        z-index: 1000;
        text-align: center;
    }
    
    .location-request button {
        background: var(--primary-color);
        color: white;
        border: none;
        padding: 8px 20px;
        border-radius: var(--border-radius);
        margin-top: 10px;
        cursor: pointer;
    }
    
    .medical-records-list {
        margin-top: 10px;
        max-height: 200px;
        overflow-y: auto;
    }
    
    .medical-record-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: rgba(255, 255, 255, 0.05);
        padding: 10px;
        margin-bottom: 8px;
        border-radius: var(--border-radius);
    }
    
    .record-info {
        flex: 1;
    }
    
    .record-actions {
        display: flex;
        gap: 8px;
    }
    
    .record-actions button {
        background: none;
        border: none;
        color: var(--text-light);
        cursor: pointer;
        padding: 5px;
    }
    
    .record-actions button:hover {
        color: var(--primary-color);
    }
    
    .hospital-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 5px;
    }
    
    .hospital-details {
        font-size: 0.9em;
        color: var(--text-light);
        margin-bottom: 10px;
    }
    
    .hospital-details i {
        width: 20px;
        text-align: center;
        margin-right: 5px;
    }
    
    .select-hospital-btn {
        background: var(--primary-color);
        color: white;
        border: none;
        padding: 5px 10px;
        border-radius: var(--border-radius);
        cursor: pointer;
        font-size: 0.9em;
    }
    
    .hospital-item.selected {
        border: 2px solid var(--primary-color);
    }
    
    .directions-panel {
        max-height: 300px;
        overflow-y: auto;
    }
    
    .direction-step {
        display: flex;
        align-items: center;
        padding: 5px;
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    }
    
    .step-number {
        background: var(--primary-color);
        color: white;
        width: 24px;
        height: 24px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 10px;
    }
    
    .step-instruction {
        flex: 1;
    }
    
    .step-distance {
        color: var(--text-light);
        font-size: 0.9em;
    }

    .modal {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.7);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1000;
    }

    .modal-content {
        background: var(--bg-color);
        padding: 20px;
        border-radius: var(--border-radius);
        width: 90%;
        max-width: 500px;
    }

    .contact-form {
        display: flex;
        flex-direction: column;
        gap: 15px;
    }

    .contact-form input {
        width: 100%;
        padding: 10px;
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: var(--border-radius);
        background: rgba(255, 255, 255, 0.1);
        color: var(--text-color);
    }

    .contact-form-buttons {
        display: flex;
        gap: 10px;
        justify-content: flex-end;
    }

    .file-upload-container {
        position: relative;
        margin: 10px 0;
    }

    .file-upload-input {
        display: none;
    }

    .file-upload-label {
        display: block;
        padding: 10px;
        background: rgba(255, 255, 255, 0.1);
        border: 1px dashed rgba(255, 255, 255, 0.2);
        border-radius: var(--border-radius);
        text-align: center;
        cursor: pointer;
        transition: var(--transition);
    }

    .file-upload-label:hover {
        background: rgba(255, 255, 255, 0.15);
    }

    .file-info {
        margin-top: 5px;
        font-size: 0.9em;
        color: var(--text-light);
    }

    .ecg-analysis-section {
        margin-top: 15px;
    }

    .ecg-analysis-section h4 {
        margin-bottom: 10px;
        color: var(--text-light);
    }

    .analysis-result {
        margin-top: 15px;
        padding: 10px;
        background: rgba(255, 255, 255, 0.05);
        border-radius: var(--border-radius);
        display: none;
    }

    .analysis-result.show {
        display: block;
    }

    .analysis-result h5 {
        color: var(--text-light);
        margin-bottom: 10px;
    }

    .analysis-result pre {
        background: rgba(0, 0, 0, 0.2);
        padding: 10px;
        border-radius: var(--border-radius);
        overflow-x: auto;
        white-space: pre-wrap;
        word-wrap: break-word;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div id="emergencyMap"></div>
    
    <div class="control-panel">
        <div class="control-section">
            <div class="section-title">
                <i class="fas fa-map-marker-alt"></i> Location
            </div>
            <div id="currentLocation">Requesting location...</div>
            <button id="startJourney" class="emergency-button secondary" disabled>
                <i class="fas fa-route"></i> Start Journey to Nearest Hospital
            </button>
        </div>
        
        <div class="control-section">
            <div class="section-title">
                <i class="fas fa-hospital"></i> Nearby Hospitals
            </div>
            <div class="hospital-list" id="hospitalList">
                Loading nearby hospitals...
            </div>
        </div>
        
        <div class="control-section">
            <div class="section-title">
                <i class="fas fa-phone-alt"></i> Emergency Contacts
            </div>
            <div class="emergency-contacts" id="emergencyContacts">
                <button class="emergency-button secondary" id="addContact">
                    <i class="fas fa-plus"></i> Add Emergency Contact
                </button>
            </div>
        </div>
        
        <div class="control-section">
            <div class="section-title">
                <i class="fas fa-file-medical"></i> Medical Records
            </div>
            <div class="file-upload-container">
                <label class="file-upload-label" for="medicalRecordUpload">
                    <i class="fas fa-upload"></i> Upload Medical Records
                    <div class="file-info">Supported formats: CSV, TXT, JSON</div>
                </label>
                <input type="file" id="medicalRecordUpload" class="file-upload-input" accept=".csv,.txt,.json">
            </div>
            <div class="medical-records-list" id="medicalRecordsList">
                <!-- Medical records will be displayed here -->
            </div>
            <button class="emergency-button secondary" id="editMedicalInfo">
                <i class="fas fa-edit"></i> View Medical Information
            </button>
            <div class="medical-form" id="medicalForm">
                <input type="text" placeholder="Current Medications" id="currentMedications">
                <textarea placeholder="Allergies" id="allergies"></textarea>
                <button class="emergency-button" id="saveMedicalInfo">Save Information</button>
            </div>
        </div>
    </div>
</div>

<div class="location-request" id="locationRequest">
    <div>This app needs your location to provide emergency services</div>
    <button id="allowLocation">Allow Location Access</button>
</div>

<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
<script>
    // Make functions globally available
    window.selectHospital = function(index) {
        selectedHospital = nearbyHospitals[index];
        if (selectedHospital) {
            // Update the start journey button
            const startJourneyBtn = document.getElementById('startJourney');
            startJourneyBtn.innerHTML = `<i class="fas fa-route"></i> Start Journey to ${selectedHospital.name}`;
            startJourneyBtn.disabled = false;
            
            // Highlight selected hospital
            document.querySelectorAll('.hospital-item').forEach((item, i) => {
                item.classList.toggle('selected', i === index);
            });
            
            // Center map on selected hospital
            map.setView([selectedHospital.lat, selectedHospital.lon], 15);
        }
    };

    window.startJourneyToHospital = function(index) {
        const hospital = nearbyHospitals[index];
        if (hospital && userLocation) {
            // Clear existing route
            if (currentRoute) {
                map.removeLayer(currentRoute);
            }
            
            // Get detailed route with turn-by-turn directions
            fetch(`https://router.project-osrm.org/route/v1/driving/${userLocation.lng},${userLocation.lat};${hospital.lon},${hospital.lat}?overview=full&geometries=geojson&steps=true`)
                .then(response => response.json())
                .then(data => {
                    if (data.routes && data.routes[0]) {
                        const route = data.routes[0];
                        currentRoute = L.geoJSON(route.geometry, {
                            style: {
                                color: '#4CAF50',
                                weight: 5,
                                opacity: 0.7
                            }
                        }).addTo(map);
                        
                        // Fit map to show the entire route
                        map.fitBounds(currentRoute.getBounds());
                        
                        // Show turn-by-turn directions
                        const steps = route.legs[0].steps;
                        let directions = `
                            <div class="directions-panel">
                                <h3>Directions to ${hospital.name}</h3>
                                <div class="directions-list">
                                    ${steps.map((step, index) => `
                                        <div class="direction-step">
                                            <span class="step-number">${index + 1}</span>
                                            <span class="step-instruction">${step.maneuver.instruction}</span>
                                            <span class="step-distance">${Math.round(step.distance)}m</span>
                                        </div>
                                    `).join('')}
                                </div>
                            </div>
                        `;
                        
                        // Create a popup with directions
                        L.popup({maxWidth: 300})
                            .setLatLng([hospital.lat, hospital.lon])
                            .setContent(directions)
                            .openOn(map);
                    }
                });
        }
    };
</script>
<script type="module">
    import { initializeApp } from "https://www.gstatic.com/firebasejs/11.6.0/firebase-app.js";
    import { getAuth, onAuthStateChanged, signInWithCustomToken } from "https://www.gstatic.com/firebasejs/11.6.0/firebase-auth.js";
    import { getDatabase, ref, onValue, set, update, remove, push, get } from "https://www.gstatic.com/firebasejs/11.6.0/firebase-database.js";

    // Initialize Firebase
    const firebaseConfig = {
        apiKey: "AIzaSyBDr1xcrLxfemIRTydmgjTcG6mHgx919Rs",
        authDomain: "help-6661c.firebaseapp.com",
        projectId: "help-6661c",
        storageBucket: "help-6661c.firebasestorage.app",
        messagingSenderId: "2944311795",
        appId: "1:2944311795:web:61d2b982c75a446df7f286",
        measurementId: "G-H8RJ7C4Z3K",
        databaseURL: "https://help-6661c-default-rtdb.firebaseio.com"
    };

    const app = initializeApp(firebaseConfig);
    const auth = getAuth();
    const database = getDatabase();

    // Check authentication status and load data
    onAuthStateChanged(auth, async (user) => {
        if (user) {
            console.log('User is signed in:', user.uid);
            loadUserData(user.uid);
        } else {
            console.log('No user is signed in');
            // Redirect to login if not authenticated
            window.location.href = '/login';
        }
    });

    async function loadUserData(userId) {
        try {
            // Load emergency contacts
            const contactsRef = ref(database, `users/${userId}/emergency_contacts`);
            onValue(contactsRef, (snapshot) => {
                const contacts = snapshot.val();
                const contactsDiv = document.getElementById('emergencyContacts');
                
                // Clear existing contacts except the add button
                const addButton = document.getElementById('addContact');
                contactsDiv.innerHTML = '';
                contactsDiv.appendChild(addButton);
                
                if (contacts) {
                    Object.entries(contacts).forEach(([id, contact]) => {
                        const contactElement = document.createElement('div');
                        contactElement.className = 'contact-item';
                        contactElement.dataset.contactId = id;
                        contactElement.innerHTML = `
                            <div class="contact-info">
                                <div class="contact-name">${contact.name}</div>
                                <div class="contact-phone">${contact.phone}</div>
                            </div>
                            <div class="contact-actions">
                                <button onclick="callContact('${contact.phone}')" title="Call"><i class="fas fa-phone"></i></button>
                                <button onclick="removeContact('${id}')" title="Remove"><i class="fas fa-trash"></i></button>
                            </div>
                        `;
                        contactsDiv.insertBefore(contactElement, addButton);
                    });
                }
            });

            // Load medical information
            const medicalInfoRef = ref(database, `users/${userId}/medical_info`);
            onValue(medicalInfoRef, (snapshot) => {
                const medicalInfo = snapshot.val();
                if (medicalInfo) {
                    document.getElementById('currentMedications').value = medicalInfo.medications || '';
                    document.getElementById('allergies').value = medicalInfo.allergies || '';
                }
            });

            // Load medical records
            const recordsRef = ref(database, `users/${userId}/medical_records`);
            onValue(recordsRef, (snapshot) => {
                const records = snapshot.val();
                const recordsList = document.getElementById('medicalRecordsList');
                recordsList.innerHTML = '';
                
                if (records) {
                    Object.entries(records).forEach(([id, record]) => {
                        const recordElement = document.createElement('div');
                        recordElement.className = 'record-item';
                        recordElement.dataset.recordId = id;
                        recordElement.innerHTML = `
                            <div class="record-info">
                                <div class="record-name">${record.name}</div>
                                <div class="record-date">${new Date(record.uploaded_at).toLocaleDateString()}</div>
                            </div>
                            <div class="record-actions">
                                <button onclick="viewRecord('${id}')" title="View"><i class="fas fa-eye"></i></button>
                                <button onclick="downloadRecord('${id}')" title="Download"><i class="fas fa-download"></i></button>
                                <button onclick="removeRecord('${id}')" title="Remove"><i class="fas fa-trash"></i></button>
                            </div>
                        `;
                        recordsList.appendChild(recordElement);
                    });
                }
            });
        } catch (error) {
            console.error('Error loading user data:', error);
        }
    }

    function addEmergencyContact(name, phone) {
        const user = auth.currentUser;
        if (!user) {
            alert('You must be logged in to add contacts');
            return;
        }

        // Save to Firebase
        const contactsRef = ref(database, `users/${user.uid}/emergency_contacts`);
        const newContactRef = push(contactsRef);
        
        set(newContactRef, {
            name: name,
            phone: phone,
            added_at: new Date().toISOString()
        })
        .then(() => {
            // Remove the modal
            document.querySelector('.modal').remove();
        })
        .catch(error => {
            console.error('Error saving contact:', error);
            alert('Error saving contact. Please try again.');
        });
    }

    function removeContact(contactId) {
        if (confirm('Are you sure you want to remove this contact?')) {
            const user = auth.currentUser;
            if (user) {
                const contactRef = ref(database, `users/${user.uid}/emergency_contacts/${contactId}`);
                remove(contactRef)
                    .then(() => {
                        // Remove from UI
                        const contactElement = document.querySelector(`.contact-item[data-contact-id="${contactId}"]`);
                        if (contactElement) {
                            contactElement.remove();
                        }
                    })
                    .catch(error => {
                        console.error('Error removing contact:', error);
                        alert('Error removing contact. Please try again.');
                    });
            }
        }
    }

    // Make functions globally available
    window.addEmergencyContact = addEmergencyContact;
    window.removeContact = removeContact;
    window.callContact = function(phone) {
        if (phone) {
            window.location.href = `tel:${phone}`;
        }
    };
    window.viewRecord = viewRecord;
    window.removeRecord = removeRecord;
    window.downloadRecord = downloadRecord;

    // Make showContactForm globally available
    window.showContactForm = function() {
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.innerHTML = `
            <div class="modal-content">
                <h3>Add Emergency Contact</h3>
                <div class="contact-form">
                    <input type="text" id="contactName" placeholder="Enter contact name" required>
                    <input type="tel" id="contactPhone" placeholder="Enter contact phone number" required>
                    <div class="contact-form-buttons">
                        <button class="emergency-button secondary" onclick="this.closest('.modal').remove()">Cancel</button>
                        <button class="emergency-button" id="saveContactBtn">Save Contact</button>
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
        
        // Add event listener to the save button
        document.getElementById('saveContactBtn').addEventListener('click', function() {
            const name = document.getElementById('contactName').value;
            const phone = document.getElementById('contactPhone').value;
            
            if (name && phone) {
                addEmergencyContact(name, phone);
                document.querySelector('.modal').remove();
            } else {
                alert('Please fill in all fields');
            }
        });
    };

    // Initialize contact form handling
    document.addEventListener('DOMContentLoaded', function() {
        const addContactBtn = document.getElementById('addContact');
        if (addContactBtn) {
            addContactBtn.addEventListener('click', window.showContactForm);
        }
    });

    // Initialize the map
    window.map = L.map('emergencyMap').setView([0, 0], 15);
    
    // Create the street map layer
    const streetLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    });

    // Create the satellite layer
    const satelliteLayer = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
        attribution: '&copy; <a href="https://www.esri.com/">Esri</a>'
    });

    // Add the street layer by default
    streetLayer.addTo(window.map);

    // Add layer control to switch between street and satellite views
    const baseMaps = {
        "Street Map": streetLayer,
        "Satellite": satelliteLayer
    };
    L.control.layers(baseMaps).addTo(window.map);

    let isVolunteer = false;
    let emergencyTimeout = null;
    let currentEmergency = null;
    window.userLocation = null;
    window.nearbyHospitals = [];
    window.currentRoute = null;
    window.selectedHospital = null;

    // Socket.io connection
    const socket = io();

    socket.on('connect', () => {
        console.log('Connected to server');
    });

    socket.on('emergency_alert', (data) => {
        if (isVolunteer) {
            showEmergencyAlert(data);
        }
    });

    // Location handling
    document.getElementById('allowLocation').addEventListener('click', () => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    window.userLocation = {
                        lat: position.coords.latitude,
                        lng: position.coords.longitude
                    };
                    window.map.setView([window.userLocation.lat, window.userLocation.lng], 15);
                    document.getElementById('locationRequest').style.display = 'none';
                    updateCurrentLocation();
                    findNearbyHospitals();
                },
                (error) => {
                    console.error('Error getting location:', error);
                    alert('Please enable location access to use emergency features');
                }
            );
        }
    });

    function updateCurrentLocation() {
        if (window.userLocation) {
            document.getElementById('currentLocation').textContent = 
                `Current Location: ${window.userLocation.lat.toFixed(4)}, ${window.userLocation.lng.toFixed(4)}`;
            document.getElementById('startJourney').disabled = false;
        }
    }

    async function findNearbyHospitals() {
        try {
            const response = await fetch(`/api/nearby_hospitals?lat=${window.userLocation.lat}&lon=${window.userLocation.lng}`);
            const data = await response.json();
            
            if (data.hospitals) {
                window.nearbyHospitals = data.hospitals;
                displayHospitals(data.hospitals);
                
                // Add markers for each hospital
                data.hospitals.forEach((hospital, index) => {
                    L.marker([hospital.lat, hospital.lon], {
                        icon: L.divIcon({
                            className: 'hospital-marker',
                            html: '<i class="fas fa-hospital" style="color: #4CAF50; font-size: 20px;"></i>'
                        })
                    })
                    .bindPopup(`<b>${hospital.name}</b><br>${hospital.address}<br>Distance: ${(hospital.distance).toFixed(0)}m`)
                    .addTo(window.map);
                });
            }
        } catch (error) {
            console.error('Error finding hospitals:', error);
        }
    }

    function displayHospitals(hospitals) {
        const hospitalList = document.getElementById('hospitalList');
        hospitalList.innerHTML = hospitals.map((hospital, index) => `
            <div class="hospital-item" onclick="selectHospital(${index})">
                <div class="hospital-header">
                    <strong>${hospital.name}</strong>
                    <span class="distance">${(hospital.distance).toFixed(0)}m</span>
                </div>
                <div class="hospital-details">
                    <div>${hospital.address}</div>
                    ${hospital.phone ? `<div><i class="fas fa-phone"></i> ${hospital.phone}</div>` : ''}
                    ${hospital.website ? `<div><i class="fas fa-globe"></i> <a href="${hospital.website}" target="_blank">Website</a></div>` : ''}
                </div>
                <button class="select-hospital-btn" onclick="event.stopPropagation(); startJourneyToHospital(${index})">
                    <i class="fas fa-route"></i> Start Journey
                </button>
            </div>
        `).join('');
    }

    // Update the start journey button click handler
    document.getElementById('startJourney').addEventListener('click', function() {
        if (window.nearbyHospitals.length > 0) {
            // If no specific hospital is selected, use the first (nearest) hospital
            const hospitalIndex = window.selectedHospital ? 
                window.nearbyHospitals.findIndex(h => h.name === window.selectedHospital.name) : 0;
            window.startJourneyToHospital(hospitalIndex);
        }
    });

    // Medical records handling
    document.getElementById('medicalRecordUpload').addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
            if (file.type === 'text/csv' || file.type === 'text/plain' || file.type === 'application/json') {
                uploadMedicalRecord(file);
            } else {
                alert('Please upload a CSV, TXT, or JSON file');
            }
        }
    });

    document.getElementById('editMedicalInfo').addEventListener('click', () => {
        const form = document.getElementById('medicalForm');
        form.style.display = form.style.display === 'none' ? 'block' : 'none';
    });

    document.getElementById('saveMedicalInfo').addEventListener('click', () => {
        const medications = document.getElementById('currentMedications').value;
        const allergies = document.getElementById('allergies').value;
        saveMedicalInfo(medications, allergies);
    });

    async function saveMedicalInfo(medications, allergies) {
        try {
            const user = auth.currentUser;
            if (user) {
                const medicalInfoRef = ref(database, `users/${user.uid}/medical_info`);
                await set(medicalInfoRef, {
                    medications: medications,
                    allergies: allergies,
                    updated_at: new Date().toISOString()
                });
                alert('Medical information saved successfully');
                document.getElementById('medicalForm').style.display = 'none';
            } else {
                alert('You must be logged in to save medical information');
            }
        } catch (error) {
            console.error('Error saving medical info:', error);
            alert('Error saving medical information. Please try again.');
        }
    }

    async function uploadMedicalRecord(file) {
        try {
            const user = auth.currentUser;
            if (!user) {
                alert('You must be logged in to upload medical records');
                return;
            }

            const reader = new FileReader();
            reader.onload = async function(e) {
                const content = e.target.result;
                const recordsRef = ref(database, `users/${user.uid}/medical_records`);
                const newRecordRef = push(recordsRef);
                
                await set(newRecordRef, {
                    name: file.name,
                    content: content,
                    type: file.type,
                    uploaded_at: new Date().toISOString()
                });
                
                alert('Medical record uploaded successfully');
            };
            reader.readAsText(file);
        } catch (error) {
            console.error('Error uploading record:', error);
            alert('Error uploading medical record. Please try again.');
        }
    }

    async function viewRecord(recordId) {
        try {
            const user = auth.currentUser;
            if (user) {
                const recordRef = ref(database, `users/${user.uid}/medical_records/${recordId}`);
                const snapshot = await get(recordRef);
                const record = snapshot.val();
                
                if (record) {
                    const modal = document.createElement('div');
                    modal.className = 'modal';
                    modal.innerHTML = `
                        <div class="modal-content">
                            <h3>${record.name}</h3>
                            <div class="record-content">
                                <pre>${record.content}</pre>
                            </div>
                            <div class="modal-buttons">
                                <button class="emergency-button" onclick="this.closest('.modal').remove()">Close</button>
                            </div>
                        </div>
                    `;
                    document.body.appendChild(modal);
                }
            }
        } catch (error) {
            console.error('Error viewing record:', error);
            alert('Error viewing record. Please try again.');
        }
    }

    async function removeRecord(recordId) {
        if (confirm('Are you sure you want to remove this record?')) {
            try {
                const user = auth.currentUser;
                if (user) {
                    const recordRef = ref(database, `users/${user.uid}/medical_records/${recordId}`);
                    await remove(recordRef);
                    alert('Record removed successfully');
                }
            } catch (error) {
                console.error('Error removing record:', error);
                alert('Error removing record. Please try again.');
            }
        }
    }

    async function downloadRecord(recordId) {
        try {
            const user = auth.currentUser;
            if (user) {
                const recordRef = ref(database, `users/${user.uid}/medical_records/${recordId}`);
                const snapshot = await get(recordRef);
                const record = snapshot.val();
                
                if (record) {
                    // Create a blob from the content
                    const blob = new Blob([record.content], { type: record.type || 'text/plain' });
                    
                    // Create a download link
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = record.name;
                    
                    // Trigger the download
                    document.body.appendChild(a);
                    a.click();
                    
                    // Clean up
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                }
            }
        } catch (error) {
            console.error('Error downloading record:', error);
            alert('Error downloading record. Please try again.');
        }
    }

    // ECG data handling
    document.getElementById('ecgDataUpload').addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
            if (file.type !== 'application/json' && !file.name.endsWith('.json')) {
                alert('Please upload a JSON file');
                e.target.value = '';
                return;
            }
            uploadECGData(file);
        }
    });

    async function uploadECGData(file) {
        try {
            const user = auth.currentUser;
            if (user) {
                const timestamp = new Date().toISOString();
                const recordRef = ref(database, `users/${user.uid}/ecg_data/${timestamp}`);
                
                const reader = new FileReader();
                reader.onload = async (e) => {
                    try {
                        // Validate JSON format
                        const content = e.target.result;
                        const jsonData = JSON.parse(content);
                        
                        // Store the data
                        await set(recordRef, {
                            filename: file.name,
                            type: 'application/json',
                            content: jsonData,
                            uploaded_at: timestamp
                        });

                        // Show analysis result
                        const resultDiv = document.getElementById('ecgAnalysisResult');
                        resultDiv.innerHTML = `
                            <h5>ECG Analysis Result</h5>
                            <pre>${JSON.stringify(analyzeECGData(jsonData), null, 2)}</pre>
                        `;
                        resultDiv.classList.add('show');
                        
                        alert('ECG data uploaded and analyzed successfully');
                    } catch (error) {
                        console.error('Error parsing JSON:', error);
                        alert('Invalid JSON format. Please upload a valid JSON file.');
                    }
                };
                reader.readAsText(file);
            }
        } catch (error) {
            console.error('Error uploading ECG data:', error);
            alert('Error uploading ECG data');
        }
    }

    function analyzeECGData(data) {
        // This is a placeholder for actual ECG analysis
        // You would implement your ECG analysis logic here
        return {
            status: 'success',
            timestamp: new Date().toISOString(),
            analysis: {
                heartRate: calculateHeartRate(data),
                anomalies: detectAnomalies(data),
                recommendations: generateRecommendations(data)
            }
        };
    }

    function calculateHeartRate(data) {
        // Placeholder for heart rate calculation
        return '60-100 BPM (Normal)';
    }

    function detectAnomalies(data) {
        // Placeholder for anomaly detection
        return ['No significant anomalies detected'];
    }

    function generateRecommendations(data) {
        // Placeholder for recommendations
        return ['Continue regular monitoring'];
    }

    // Emergency button functionality
    document.getElementById('triggerEmergency').addEventListener('click', async function() {
        if (!window.userLocation) {
            alert('Please enable location access first');
            return;
        }
        
        const description = document.getElementById('emergencyDescription').value;
        
        try {
            // Call all emergency contacts
            const contacts = document.querySelectorAll('.contact-item');
            contacts.forEach(contact => {
                const phone = contact.querySelector('.contact-phone').textContent;
                callContact(phone, description);
            });
            
            // Send emergency alert to server
            const response = await fetch('/api/emergency', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    lat: window.userLocation.lat,
                    lng: window.userLocation.lng,
                    description: description
                })
            });
            
            const result = await response.json();
            if (result.status === 'success') {
                currentEmergency = result.emergency_id;
                startEmergencyTimer();
                showEmergencyMarker(window.userLocation.lat, window.userLocation.lng);
            }
        } catch (error) {
            console.error('Error sending emergency alert:', error);
        }
    });

    function startEmergencyTimer() {
        let timeLeft = 300; // 5 minutes in seconds
        const timerElement = document.getElementById('emergencyTimer');
        
        if (emergencyTimeout) {
            clearInterval(emergencyTimeout);
        }
        
        emergencyTimeout = setInterval(() => {
            timeLeft--;
            const minutes = Math.floor(timeLeft / 60);
            const seconds = timeLeft % 60;
            timerElement.textContent = `Calling emergency services in: ${minutes}:${seconds.toString().padStart(2, '0')}`;
            
            if (timeLeft <= 0) {
                clearInterval(emergencyTimeout);
                callEmergencyServices();
            }
        }, 1000);
    }

    function callEmergencyServices() {
        alert('Emergency services have been notified!');
        document.getElementById('emergencyTimer').textContent = 'Emergency services notified';
    }

    function showEmergencyMarker(lat, lng) {
        // Clear existing markers
        window.map.eachLayer((layer) => {
            if (layer instanceof L.Marker) {
                window.map.removeLayer(layer);
            }
        });
        
        // Add emergency marker
        L.marker([lat, lng], {
            icon: L.divIcon({
                className: 'emergency-marker',
                html: '<i class="fas fa-exclamation-triangle" style="color: red; font-size: 24px;"></i>'
            })
        }).addTo(window.map);
    }
</script>
{% endblock %}