-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
994 lines (879 loc) · 40.4 KB
/
app.js
File metadata and controls
994 lines (879 loc) · 40.4 KB
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
/* ════════════════════════════════════════════
MediQo+ — app.js
════════════════════════════════════════════ */
'use strict';
// ── CONSTANTS ────────────────────────────────────────────────
const OVERPASS = 'https://overpass-api.de/api/interpreter';
const NOMINATIM = 'https://nominatim.openstreetmap.org';
const OSRM_BASE = 'https://router.project-osrm.org/route/v1/driving';
const SEARCH_RADIUS_KM = 10;
// Tab configuration: OSM query tags + display metadata
const TABS = {
hospital: { label:'Hospital', icon:'plus-square', color:'#dc2626', iconClass:'red',
queries:['["amenity"="hospital"]'] },
clinic: { label:'Clinic / Doctor', icon:'user', color:'#2563eb', iconClass:'blue',
queries:['["amenity"="clinic"]','["amenity"="doctors"]'] },
diagnostic: { label:'Diagnostic', icon:'thermometer', color:'#d97706', iconClass:'amber',
queries:['["healthcare"="laboratory"]','["healthcare"="diagnostic"]','["amenity"="laboratory"]'] },
blood_bank: { label:'Blood Donation', icon:'droplet', color:'#dc2626', iconClass:'red',
queries:['["amenity"="blood_bank"]','["healthcare"="blood_bank"]','["amenity"="blood_donation"]'] },
maternity: { label:'Maternity / OB-GYN', icon:'heart', color:'#9333ea', iconClass:'',
queries:['["healthcare:speciality"="gynaecology"]','["healthcare:speciality"="obstetrics"]','["healthcare"="maternity"]'] },
cancer: { label:'Cancer Centre', icon:'shield', color:'#7c3aed', iconClass:'',
queries:['["healthcare:speciality"="oncology"]','["healthcare"="oncology"]'] },
pharmacy: { label:'Pharmacy', icon:'package', color:'#059669', iconClass:'',
queries:['["amenity"="pharmacy"]'] },
vet: { label:'Pet Vet', icon:'heart', color:'#1a9e5c', iconClass:'',
queries:['["amenity"="veterinary"]'] },
pet_store: { label:'Pet Shop', icon:'shopping-bag',color:'#1a9e5c', iconClass:'',
queries:['["shop"="pet"]','["shop"="pet_supply"]'] },
animal_clinic:{ label:'Animal Clinic', icon:'zap', color:'#1a9e5c', iconClass:'',
queries:['["amenity"="animal_shelter"]','["shop"="pet_grooming"]'] },
};
// ── STATE ────────────────────────────────────────────────────
let map, userMarker, clusterGroup, routeLine;
let userLat = null, userLng = null;
let currentTab = 'hospital';
let currentLFTab = null; // 'lost_found_human' or 'lost_found_pet'
let allPlaces = [];
let filtered = [];
let openNowOn = false;
let searchQ = '';
let unit = 'km';
let sortBy = 'distance';
let radius = 10;
let reviewPID = null;
let reviewStarVal = 0;
// localStorage keys
const LS = {
saved: 'mediqo_saved',
reviews: 'mediqo_reviews',
lfHuman: 'mediqo_lf_human',
lfPet: 'mediqo_lf_pet',
};
let saved = JSON.parse(localStorage.getItem(LS.saved) || '{}');
let reviews = JSON.parse(localStorage.getItem(LS.reviews) || '{}');
// ── INIT ─────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {
initMap();
initNav();
initControls();
initModals();
initLF();
initReviews();
updateSavedBadge();
feather.replace();
requestLocation();
});
// ── MAP ──────────────────────────────────────────────────────
function initMap() {
map = L.map('map', { center:[23.8103, 90.4125], zoom:13, zoomControl:false });
L.control.zoom({ position:'bottomright' }).addTo(map);
// CartoDB Positron — no referer restriction, works from file://
L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png', {
attribution:'© <a href="https://www.openstreetmap.org/">OSM</a> © <a href="https://carto.com/">CARTO</a>',
subdomains:'abcd', maxZoom:19,
}).addTo(map);
clusterGroup = L.markerClusterGroup({
showCoverageOnHover:false, maxClusterRadius:55,
iconCreateFunction: c => L.divIcon({
html:`<div style="width:34px;height:34px;background:#1a9e5c;color:#fff;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:12px;border:3px solid #fff;box-shadow:0 2px 8px rgba(0,0,0,.25)">${c.getChildCount()}</div>`,
className:'', iconSize:[34,34],
}),
});
map.addLayer(clusterGroup);
map.on('click', closeDetailPanel);
}
// ── LOCATION ─────────────────────────────────────────────────
function requestLocation() {
if (!navigator.geolocation) { showManualLocModal(); return; }
setLocLabel('Detecting location…');
navigator.geolocation.getCurrentPosition(
p => onLocation(p.coords.latitude, p.coords.longitude),
() => { toast('Location access denied. Set manually.', 'err'); showManualLocModal(); },
{ enableHighAccuracy:true, timeout:10000 }
);
}
function onLocation(lat, lng) {
userLat = lat; userLng = lng;
map.setView([lat, lng], 14);
placeUserPin(lat, lng);
reverseGeocode(lat, lng);
fetchPlaces();
}
function placeUserPin(lat, lng) {
if (userMarker) map.removeLayer(userMarker);
const icon = L.divIcon({
html:`<div style="width:14px;height:14px;background:#1a9e5c;border-radius:50%;border:3px solid #fff;box-shadow:0 0 0 4px rgba(26,158,92,.25)"></div>`,
className:'', iconSize:[14,14], iconAnchor:[7,7],
});
userMarker = L.marker([lat,lng],{icon,zIndexOffset:1000})
.bindPopup('<strong>You are here</strong>').addTo(map);
}
async function reverseGeocode(lat, lng) {
try {
const r = await fetch(`${NOMINATIM}/reverse?format=json&lat=${lat}&lon=${lng}`,
{ headers:{ 'Accept-Language':'en','User-Agent':'MediQo+/1.0' } });
const d = await r.json();
const label = d.display_name
? d.display_name.split(',').slice(0,3).join(',')
: `${lat.toFixed(4)}, ${lng.toFixed(4)}`;
setLocLabel(label);
} catch { setLocLabel(`${lat.toFixed(4)}, ${lng.toFixed(4)}`); }
}
function setLocLabel(t) {
document.getElementById('locLabel').textContent = t;
}
// ── NAVBAR ────────────────────────────────────────────────────
function initNav() {
// Desktop dropdown toggles
document.querySelectorAll('.nav-group-btn').forEach(btn => {
btn.addEventListener('click', e => {
e.stopPropagation();
const grp = btn.dataset.group;
const drop = document.getElementById('drop-' + grp);
const wasOpen = drop.classList.contains('open');
closeAllDropdowns();
if (!wasOpen) { drop.classList.add('open'); btn.classList.add('open'); }
});
});
document.addEventListener('click', closeAllDropdowns);
// Tab items (desktop dropdowns)
document.querySelectorAll('.drop-item').forEach(item => {
item.addEventListener('click', () => {
const tab = item.dataset.tab;
const section = item.dataset.section;
closeAllDropdowns();
if (section === 'lostandfound') {
openLFSection(tab);
} else {
switchTab(tab);
}
});
});
// Mobile drawer
document.getElementById('mobileMenuBtn').addEventListener('click', openDrawer);
document.getElementById('mobileOverlay').addEventListener('click', closeDrawer);
document.getElementById('drawerClose').addEventListener('click', closeDrawer);
document.querySelectorAll('.drawer-item').forEach(item => {
item.addEventListener('click', () => {
const tab = item.dataset.tab;
const section = item.dataset.section;
closeDrawer();
if (section === 'lostandfound') openLFSection(tab);
else if (tab) switchTab(tab);
});
});
document.getElementById('drawerEmergency').addEventListener('click', () => {
closeDrawer(); showEmergency();
});
// Emergency button
document.getElementById('emergencyBtn').addEventListener('click', showEmergency);
// Saved
document.getElementById('savedBtn').addEventListener('click', showSaved);
}
function closeAllDropdowns() {
document.querySelectorAll('.dropdown').forEach(d => d.classList.remove('open'));
document.querySelectorAll('.nav-group-btn').forEach(b => b.classList.remove('open'));
}
function openDrawer() {
document.getElementById('mobileDrawer').classList.add('open');
document.getElementById('mobileOverlay').classList.add('open');
}
function closeDrawer() {
document.getElementById('mobileDrawer').classList.remove('open');
document.getElementById('mobileOverlay').classList.remove('open');
}
function switchTab(tab) {
if (!TABS[tab]) return;
currentTab = tab;
currentLFTab = null;
// Show map section, hide LF
document.getElementById('appShell').style.display = 'flex';
document.getElementById('lfSection').style.display = 'none';
// Mark active in dropdowns
document.querySelectorAll('.drop-item, .drawer-item').forEach(el => {
el.classList.toggle('active-tab', el.dataset.tab === tab);
});
// Update hero
const cfg = TABS[tab];
document.getElementById('heroTabName').textContent = cfg.label;
document.getElementById('heroTabSub').textContent = `Nearest ${cfg.label.toLowerCase()} within ${radius} km`;
document.getElementById('heroIcon').innerHTML = `<i data-feather="${cfg.icon}"></i>`;
feather.replace();
fetchPlaces();
}
// ── CONTROLS ─────────────────────────────────────────────────
function initControls() {
// Search
const si = document.getElementById('searchInput');
const cb = document.getElementById('clearSearch');
si.addEventListener('input', () => {
searchQ = si.value.toLowerCase().trim();
cb.classList.toggle('vis', searchQ.length > 0);
applyFilters();
});
cb.addEventListener('click', () => {
si.value = ''; searchQ = '';
cb.classList.remove('vis');
applyFilters();
});
// Sort / unit / radius
document.getElementById('sortSel').addEventListener('change', e => { sortBy = e.target.value; applyFilters(); });
document.getElementById('unitSel').addEventListener('change', e => { unit = e.target.value; applyFilters(); });
document.getElementById('radiusSel').addEventListener('change', e => {
radius = parseInt(e.target.value);
document.getElementById('heroTabSub').textContent = `Nearest ${TABS[currentTab]?.label?.toLowerCase() || ''} within ${radius} km`;
if (userLat) fetchPlaces();
});
// Open now
document.getElementById('openNowChip').addEventListener('click', () => {
openNowOn = !openNowOn;
document.getElementById('openNowChip').classList.toggle('on', openNowOn);
applyFilters();
});
// FABs
document.getElementById('fabLocate').addEventListener('click', () => {
if (userLat) map.setView([userLat, userLng], 15);
else requestLocation();
});
document.getElementById('fabToggle').addEventListener('click', () => {
document.getElementById('sidebar').classList.toggle('collapsed');
});
document.getElementById('fabClearRoute').addEventListener('click', clearRoute);
document.getElementById('clearRouteBtn').addEventListener('click', clearRoute);
// Geo button in empty state
document.getElementById('geoBtn').addEventListener('click', requestLocation);
// Change location
document.getElementById('changeLocBtn').addEventListener('click', showManualLocModal);
}
// ── FETCH PLACES ──────────────────────────────────────────────
async function fetchPlaces() {
if (!userLat) return;
const cfg = TABS[currentTab];
if (!cfg) return;
showLoader(true);
allPlaces = [];
clusterGroup.clearLayers();
clearRoute();
const radM = radius * 1000;
try {
const nodeWayRel = tags => tags.map(t =>
`node${t}(around:${radM},${userLat},${userLng});
way${t}(around:${radM},${userLat},${userLng});
relation${t}(around:${radM},${userLat},${userLng});`
).join('\n');
const q = `[out:json][timeout:30];\n(\n${nodeWayRel(cfg.queries)}\n);\nout center tags;`;
const res = await fetch(OVERPASS, {
method:'POST',
body: `data=${encodeURIComponent(q)}`,
headers:{ 'Content-Type':'application/x-www-form-urlencoded' }
});
if (!res.ok) throw new Error('Overpass error');
const data = await res.json();
allPlaces = data.elements
.map(parseElement)
.filter(Boolean)
.filter(p => haversine(userLat, userLng, p.lat, p.lng) <= radius);
applyFilters();
renderMarkers();
} catch(err) {
console.error(err);
toast('Failed to load places. Check internet.', 'err');
document.getElementById('resultsList').innerHTML = `
<div class="empty-state">
<div class="empty-icon"><i data-feather="wifi-off"></i></div>
<p>Could not fetch results.<br/>Try again or check your connection.</p>
</div>`;
feather.replace();
} finally {
showLoader(false);
}
}
function parseElement(el) {
const tags = el.tags || {};
let lat, lng;
if (el.type === 'node') { lat = el.lat; lng = el.lon; }
else if (el.center) { lat = el.center.lat; lng = el.center.lon; }
else return null;
const name = tags.name || tags['name:en'] || 'Unnamed Place';
const address = buildAddr(tags);
const phone = tags.phone || tags['contact:phone'] || tags['contact:mobile'] || null;
const website = tags.website || tags['contact:website'] || null;
const hours = tags.opening_hours || null;
const emergency = (tags.emergency === 'yes') || /emergency|24h|24\/7/i.test(tags.name || '');
const dist = haversine(userLat, userLng, lat, lng);
return { id:`${el.type}-${el.id}`, osmType:el.type, osmId:el.id,
lat, lng, name, address, phone, website, hours, emergency, dist, tags };
}
function buildAddr(t) {
const parts = [];
if (t['addr:housenumber'] && t['addr:street']) parts.push(`${t['addr:housenumber']} ${t['addr:street']}`);
else if (t['addr:street']) parts.push(t['addr:street']);
if (t['addr:suburb']) parts.push(t['addr:suburb']);
if (t['addr:city'] || t['addr:town']) parts.push(t['addr:city'] || t['addr:town']);
if (!parts.length && t['addr:full']) parts.push(t['addr:full']);
return parts.join(', ') || 'Address not listed';
}
// ── FILTERS ───────────────────────────────────────────────────
function applyFilters() {
let list = [...allPlaces];
if (searchQ) list = list.filter(p =>
p.name.toLowerCase().includes(searchQ) ||
p.address.toLowerCase().includes(searchQ)
);
if (openNowOn) list = list.filter(p => openStatus(p) === 'open');
if (sortBy === 'distance') list.sort((a,b) => a.dist - b.dist);
else list.sort((a,b) => a.name.localeCompare(b.name));
filtered = list;
document.getElementById('resultsCount').textContent = `${filtered.length} result${filtered.length !== 1 ? 's' : ''}`;
renderList();
renderMarkers();
}
// ── RENDER LIST ───────────────────────────────────────────────
function renderList() {
const list = document.getElementById('resultsList');
if (!filtered.length) {
list.innerHTML = `
<div class="empty-state">
<div class="empty-icon"><i data-feather="${TABS[currentTab]?.icon || 'map-pin'}"></i></div>
<p>No results within ${radius} km.</p>
<button class="btn-primary" id="expandBtn"><i data-feather="zoom-in"></i> Expand radius</button>
</div>`;
feather.replace();
document.getElementById('expandBtn')?.addEventListener('click', () => {
const sel = document.getElementById('radiusSel');
const vals = ['2','5','10','20'];
const idx = vals.indexOf(String(radius));
if (idx < vals.length - 1) {
sel.value = vals[idx + 1];
radius = parseInt(vals[idx + 1]);
fetchPlaces();
}
});
return;
}
list.innerHTML = filtered.map(p => cardHTML(p)).join('');
feather.replace();
list.querySelectorAll('.place-card').forEach(card => {
const id = card.dataset.id;
const p = filtered.find(x => x.id === id);
if (!p) return;
// Card click → detail panel
card.addEventListener('click', e => {
if (e.target.closest('.act-btn')) return;
openDetail(p);
map.setView([p.lat, p.lng], 16);
});
// Directions
card.querySelector('.btn-dir')?.addEventListener('click', e => {
e.stopPropagation();
drawRoute(p);
});
// Save
card.querySelector('.btn-save')?.addEventListener('click', e => {
e.stopPropagation();
toggleSaved(p, card.querySelector('.btn-save'));
});
});
}
function cardHTML(p) {
const cfg = TABS[currentTab];
const dist = fmtDist(p.dist);
const st = openStatus(p);
const isSaved = !!saved[p.id];
const rv = getAvgRating(p.id);
return `
<div class="place-card" data-id="${p.id}">
<div class="pc-top">
<div class="pc-icon ${cfg.iconClass}${p.emergency ? ' red' : ''}">
<i data-feather="${p.emergency ? 'alert-circle' : cfg.icon}"></i>
</div>
<div class="pc-info">
<div class="pc-name" title="${esc(p.name)}">${esc(p.name)}</div>
<div class="pc-addr">${esc(p.address)}</div>
<div class="pc-meta">
<span class="dist-badge">${dist}</span>
${st === 'open' ? '<span class="status-badge status-open">Open</span>' : ''}
${st === 'closed' ? '<span class="status-badge status-closed">Closed</span>' : ''}
${p.emergency ? '<span class="status-badge status-open">24h</span>' : ''}
${rv ? `<div class="stars-row">${starsHTML(rv.avg)} <span class="rev-count">(${rv.count})</span></div>` : ''}
</div>
</div>
</div>
<div class="pc-actions">
<button class="act-btn btn-dir dir">
<i data-feather="navigation"></i> Directions
</button>
<button class="act-btn btn-save ${isSaved ? 'saved' : ''}">
<i data-feather="bookmark"></i> ${isSaved ? 'Saved' : 'Save'}
</button>
<button class="act-btn">
<i data-feather="info"></i> Details
</button>
</div>
</div>`;
}
// ── RENDER MARKERS ────────────────────────────────────────────
function renderMarkers() {
clusterGroup.clearLayers();
const cfg = TABS[currentTab];
filtered.forEach(p => {
const col = p.emergency ? '#dc2626' : cfg.color;
const icon = L.divIcon({
html:`<div style="width:26px;height:26px;background:${col};border-radius:50% 50% 50% 0;transform:rotate(-45deg);border:3px solid #fff;box-shadow:0 2px 8px rgba(0,0,0,.22)"></div>`,
className:'', iconSize:[26,26], iconAnchor:[13,26], popupAnchor:[0,-30],
});
const marker = L.marker([p.lat, p.lng], {icon});
marker.bindPopup(popupHTML(p), { maxWidth:260 });
marker.on('popupopen', () => {
document.getElementById(`pp-det-${p.id}`)?.addEventListener('click', () => openDetail(p));
document.getElementById(`pp-dir-${p.id}`)?.addEventListener('click', () => { map.closePopup(); drawRoute(p); });
});
marker.on('click', () => highlightCard(p.id));
clusterGroup.addLayer(marker);
});
}
function popupHTML(p) {
const dist = fmtDist(p.dist);
return `
<div class="pop-name">${esc(p.name)}</div>
<div class="pop-addr">${esc(p.address)}</div>
<div class="pop-dist">${dist} from you</div>
<div class="pop-btns">
<button class="pop-btn primary" id="pp-det-${p.id}">Details</button>
<button class="pop-btn sec" id="pp-dir-${p.id}">Directions</button>
</div>`;
}
function highlightCard(id) {
document.querySelectorAll('.place-card').forEach(c => c.classList.remove('highlighted'));
const card = document.querySelector(`.place-card[data-id="${id}"]`);
if (card) { card.classList.add('highlighted'); card.scrollIntoView({behavior:'smooth', block:'nearest'}); }
}
// ── OSRM ROUTING ──────────────────────────────────────────────
async function drawRoute(place) {
if (!userLat) { toast('Need your location for directions.','err'); return; }
clearRoute();
const url = `${OSRM_BASE}/${userLng},${userLat};${place.lng},${place.lat}?overview=full&geometries=geojson`;
try {
const res = await fetch(url);
const data = await res.json();
if (data.code !== 'Ok' || !data.routes?.length) { toast('Route not found.','err'); return; }
const route = data.routes[0];
const distKm = (route.distance / 1000).toFixed(2);
const mins = Math.ceil(route.duration / 60);
const coords = route.geometry.coordinates.map(([lng,lat]) => [lat,lng]);
routeLine = L.polyline(coords, {
color:'#1a9e5c', weight:5, opacity:.85,
dashArray:null,
}).addTo(map);
map.fitBounds(routeLine.getBounds(), {padding:[50,50]});
// Route info bar
const bar = document.getElementById('routeBar');
document.getElementById('routeInfo').innerHTML =
`To <strong>${esc(place.name)}</strong> — <span>${distKm} km</span> (~${mins} min)`;
bar.classList.add('vis');
document.getElementById('fabClearRoute').style.display = 'grid';
toast(`Route drawn: ${distKm} km, ~${mins} min`,'ok');
highlightCard(place.id);
} catch(err) {
console.error(err);
toast('Routing service unavailable.','err');
}
}
function clearRoute() {
if (routeLine) { map.removeLayer(routeLine); routeLine = null; }
document.getElementById('routeBar').classList.remove('vis');
document.getElementById('fabClearRoute').style.display = 'none';
}
// ── DETAIL PANEL ──────────────────────────────────────────────
function openDetail(p) {
const cfg = TABS[currentTab];
const dist = fmtDist(p.dist);
const st = openStatus(p);
const isSaved = !!saved[p.id];
const rv = getAvgRating(p.id);
const pReviews = (reviews[p.id] || []);
const gmLink = `https://www.google.com/maps/dir/?api=1&destination=${p.lat},${p.lng}`;
const wazeLink = `https://waze.com/ul?ll=${p.lat},${p.lng}&navigate=yes`;
const osmLink = `https://www.openstreetmap.org/${p.osmType}/${p.osmId}`;
document.getElementById('detailBody').innerHTML = `
<div class="dp-hero"><i data-feather="${p.emergency ? 'alert-circle' : cfg.icon}"></i></div>
<div class="dp-cat"><i data-feather="${cfg.icon}"></i> ${esc(cfg.label)}${p.emergency ? ' — Emergency' : ''}</div>
<div class="dp-name">${esc(p.name)}</div>
<div class="dp-meta">
<span class="dist-badge">${dist} away</span>
${st === 'open' ? '<span class="status-badge status-open">Open</span>' : ''}
${st === 'closed' ? '<span class="status-badge status-closed">Closed</span>' : ''}
${rv ? `<div class="stars-row">${starsHTML(rv.avg)}<span class="rev-count"> ${rv.avg.toFixed(1)} (${rv.count} reviews)</span></div>` : '<span style="font-size:11px;color:var(--text-3)">No reviews yet</span>'}
</div>
<div class="dp-actions">
<button class="act-btn dir" onclick="drawRouteById('${p.id}')">
<i data-feather="navigation"></i> In-App Route
</button>
<a href="${gmLink}" target="_blank" rel="noopener" class="act-btn dir">
<i data-feather="map"></i> Google Maps
</a>
<a href="${wazeLink}" target="_blank" rel="noopener" class="act-btn">
<i data-feather="navigation-2"></i> Waze
</a>
<button class="act-btn ${isSaved ? 'saved' : ''}" id="dpSaveBtn" onclick="toggleSavedById('${p.id}')">
<i data-feather="bookmark"></i> ${isSaved ? 'Saved' : 'Save'}
</button>
</div>
<div class="dp-section">
<div class="dp-sec-title"><i data-feather="info"></i> Information</div>
<div class="info-row"><i data-feather="map-pin"></i><span>${esc(p.address)}</span></div>
${p.phone ? `<div class="info-row"><i data-feather="phone"></i><a href="tel:${p.phone}">${esc(p.phone)}</a></div>` : ''}
${p.website ? `<div class="info-row"><i data-feather="globe"></i><a href="${p.website}" target="_blank" rel="noopener">${esc(p.website)}</a></div>` : ''}
${p.hours ? `<div class="info-row"><i data-feather="clock"></i><span>${esc(p.hours)}</span></div>` : ''}
<div class="info-row"><i data-feather="external-link"></i><a href="${osmLink}" target="_blank" rel="noopener">View on OpenStreetMap</a></div>
</div>
<div class="dp-section">
<div class="dp-sec-title"><i data-feather="star"></i> Reviews</div>
${pReviews.length ? pReviews.map(rv => `
<div class="review-card">
<div class="rv-head">
<div class="stars-row">${starsHTML(rv.rating)}</div>
<strong class="rv-author">${esc(rv.name || 'Anonymous')}</strong>
<span class="rv-date">${rv.date}</span>
</div>
<div class="rv-text">${esc(rv.comment)}</div>
</div>`).join('') : '<div class="rv-empty">No reviews yet. Be the first!</div>'}
<button class="act-btn" style="margin-top:8px" onclick="openReviewModal('${p.id}','${esc(p.name)}')">
<i data-feather="edit-2"></i> Write a Review
</button>
</div>
`;
feather.replace();
document.getElementById('detailPanel').classList.add('open');
document.getElementById('detailOverlay').classList.add('vis');
}
function closeDetailPanel() {
document.getElementById('detailPanel').classList.remove('open');
document.getElementById('detailOverlay').classList.remove('vis');
}
document.getElementById('detailClose').addEventListener('click', closeDetailPanel);
document.getElementById('detailOverlay').addEventListener('click', closeDetailPanel);
// Global helpers called from inline onclick
window.drawRouteById = id => {
const p = allPlaces.find(x => x.id === id);
if (p) { closeDetailPanel(); drawRoute(p); }
};
window.toggleSavedById = id => {
const p = allPlaces.find(x => x.id === id);
if (!p) return;
const btn = document.getElementById('dpSaveBtn');
if (btn) toggleSaved(p, btn);
};
window.openReviewModal = openReviewModal;
// ── SAVED ─────────────────────────────────────────────────────
function toggleSaved(place, btn) {
if (saved[place.id]) {
delete saved[place.id];
btn.classList.remove('saved');
btn.innerHTML = `<i data-feather="bookmark"></i> Save`;
toast('Removed from saved');
} else {
saved[place.id] = { ...place, tab:currentTab };
btn.classList.add('saved');
btn.innerHTML = `<i data-feather="bookmark"></i> Saved`;
toast('Saved!','ok');
}
feather.replace();
localStorage.setItem(LS.saved, JSON.stringify(saved));
updateSavedBadge();
}
function updateSavedBadge() {
document.getElementById('savedBadge').textContent = Object.keys(saved).length;
}
function showSaved() {
const entries = Object.values(saved);
const list = document.getElementById('savedList');
if (!entries.length) {
list.innerHTML = '<div class="cl-empty">No saved places yet.</div>';
} else {
list.innerHTML = entries.map(p => {
const cfg = TABS[p.tab] || TABS['hospital'];
return `
<div class="cl-item">
<div class="cl-icon ${cfg.iconClass}"><i data-feather="${cfg.icon}"></i></div>
<div class="cl-info">
<div class="cl-name">${esc(p.name)}</div>
<div class="cl-sub">${esc(cfg.label)} • ${fmtDist(p.dist)}</div>
</div>
<div class="cl-actions">
<a href="https://www.google.com/maps/dir/?api=1&destination=${p.lat},${p.lng}"
target="_blank" rel="noopener" class="act-btn dir"><i data-feather="navigation"></i></a>
<button class="act-btn" onclick="removeSaved('${p.id}')"><i data-feather="trash-2"></i></button>
</div>
</div>`;
}).join('');
}
feather.replace();
document.getElementById('savedBg').classList.add('open');
}
window.removeSaved = function(id) {
delete saved[id];
localStorage.setItem(LS.saved, JSON.stringify(saved));
updateSavedBadge();
showSaved();
};
// ── EMERGENCY ─────────────────────────────────────────────────
async function showEmergency() {
document.getElementById('emergencyBg').classList.add('open');
const list = document.getElementById('emergencyList');
list.innerHTML = '<div class="cl-empty">Searching…</div>';
if (!userLat) { list.innerHTML = '<div class="cl-empty">Enable location first.</div>'; return; }
try {
const r = 15000;
const q = `[out:json][timeout:20];
(
node["amenity"="hospital"](around:${r},${userLat},${userLng});
way["amenity"="hospital"](around:${r},${userLat},${userLng});
node["amenity"="veterinary"]["emergency"="yes"](around:${r},${userLat},${userLng});
node["amenity"="veterinary"]["opening_hours"="24/7"](around:${r},${userLat},${userLng});
node["amenity"="veterinary"](around:${r/3},${userLat},${userLng});
);
out center tags;`;
const res = await fetch(OVERPASS, {
method:'POST', body:`data=${encodeURIComponent(q)}`,
headers:{ 'Content-Type':'application/x-www-form-urlencoded' }
});
const data = await res.json();
const places = data.elements.map(parseElement).filter(Boolean);
places.sort((a,b) => a.dist - b.dist);
if (!places.length) { list.innerHTML = '<div class="cl-empty">None found within 15 km.</div>'; return; }
list.innerHTML = places.slice(0,10).map(p => {
const isHosp = p.tags?.amenity === 'hospital';
return `
<div class="cl-item">
<div class="cl-icon ${isHosp ? 'red' : ''}"><i data-feather="${isHosp ? 'plus-square' : 'heart'}"></i></div>
<div class="cl-info">
<div class="cl-name">${esc(p.name)}</div>
<div class="cl-sub">${fmtDist(p.dist)} • ${esc(p.address)}</div>
</div>
<div class="cl-actions">
<a href="https://www.google.com/maps/dir/?api=1&destination=${p.lat},${p.lng}"
target="_blank" rel="noopener" class="act-btn dir"><i data-feather="navigation"></i></a>
${p.phone ? `<a href="tel:${p.phone}" class="act-btn"><i data-feather="phone"></i></a>` : ''}
</div>
</div>`;
}).join('');
feather.replace();
} catch { list.innerHTML = '<div class="cl-empty">Failed to load. Check connection.</div>'; }
}
// ── MODALS INIT ───────────────────────────────────────────────
function initModals() {
// Location modal
mk('locModalBg','locModalClose');
document.getElementById('locSearchBtn').addEventListener('click', geocodeManual);
document.getElementById('locSearch').addEventListener('keydown', e => { if(e.key==='Enter') geocodeManual(); });
document.getElementById('applyLocBtn').addEventListener('click', applyManualLoc);
// Emergency
mk('emergencyBg','emergencyClose');
// Saved
mk('savedBg','savedClose');
// Review
mk('reviewBg','reviewClose');
// LF Form
mk('lfFormBg','lfFormClose');
document.getElementById('lfSubmitBtn').addEventListener('click', submitLF);
}
function mk(bgId, closeId) {
const bg = document.getElementById(bgId);
const cl = document.getElementById(closeId);
cl?.addEventListener('click', () => bg.classList.remove('open'));
bg?.addEventListener('click', e => { if(e.target === bg) bg.classList.remove('open'); });
}
function showManualLocModal() { document.getElementById('locModalBg').classList.add('open'); }
async function geocodeManual() {
const q = document.getElementById('locSearch').value.trim();
if (!q) return;
try {
const res = await fetch(`${NOMINATIM}/search?format=json&q=${encodeURIComponent(q)}&limit=1`,
{ headers:{ 'Accept-Language':'en','User-Agent':'MediQo+/1.0' } });
const data = await res.json();
if (data.length) {
document.getElementById('manLat').value = data[0].lat;
document.getElementById('manLng').value = data[0].lon;
toast(`Found: ${data[0].display_name.split(',').slice(0,2).join(',')}`,'ok');
} else { toast('Location not found.','err'); }
} catch { toast('Geocoding failed.','err'); }
}
function applyManualLoc() {
const lat = parseFloat(document.getElementById('manLat').value);
const lng = parseFloat(document.getElementById('manLng').value);
if (isNaN(lat)||isNaN(lng)) { toast('Enter valid coordinates or search an address.','err'); return; }
document.getElementById('locModalBg').classList.remove('open');
onLocation(lat, lng);
}
// ── REVIEWS ───────────────────────────────────────────────────
function initReviews() {
// Star picker
const stars = document.querySelectorAll('.star-btn');
stars.forEach(btn => {
btn.addEventListener('click', () => {
reviewStarVal = parseInt(btn.dataset.val);
stars.forEach(b => {
b.classList.toggle('lit', parseInt(b.dataset.val) <= reviewStarVal);
});
feather.replace();
});
});
document.getElementById('reviewSubmitBtn').addEventListener('click', submitReview);
}
function openReviewModal(placeId, placeName) {
reviewPID = placeId; reviewStarVal = 0;
document.getElementById('reviewPlaceName').textContent = placeName;
document.getElementById('reviewerName').value = '';
document.getElementById('reviewComment').value = '';
document.querySelectorAll('.star-btn').forEach(b => b.classList.remove('lit'));
feather.replace();
document.getElementById('reviewBg').classList.add('open');
}
function submitReview() {
if (!reviewPID) return;
if (!reviewStarVal) { toast('Please select a rating.','err'); return; }
const name = document.getElementById('reviewerName').value.trim() || 'Anonymous';
const comment = document.getElementById('reviewComment').value.trim();
if (!comment) { toast('Please write a comment.','err'); return; }
if (!reviews[reviewPID]) reviews[reviewPID] = [];
reviews[reviewPID].push({
rating:reviewStarVal, name, comment,
date: new Date().toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})
});
localStorage.setItem(LS.reviews, JSON.stringify(reviews));
document.getElementById('reviewBg').classList.remove('open');
toast('Review submitted!','ok');
// Re-open detail if the same place
const p = allPlaces.find(x => x.id === reviewPID);
if (p) openDetail(p);
}
function getAvgRating(id) {
const rv = reviews[id];
if (!rv?.length) return null;
const avg = rv.reduce((s,r) => s + r.rating, 0) / rv.length;
return { avg, count:rv.length };
}
// ── LOST & FOUND ──────────────────────────────────────────────
function initLF() {
document.getElementById('addLFBtn').addEventListener('click', () => {
document.getElementById('lfFormTitle').textContent =
currentLFTab === 'lost_found_pet' ? 'Add Pet L&F Post' : 'Add People L&F Post';
document.getElementById('lfFormBg').classList.add('open');
});
}
function openLFSection(tab) {
currentLFTab = tab;
currentTab = null;
document.getElementById('appShell').style.display = 'none';
const sec = document.getElementById('lfSection');
sec.style.display = 'block';
document.getElementById('lfTitle').textContent =
tab === 'lost_found_pet' ? 'Lost & Found — Pets' : 'Lost & Found — People';
document.getElementById('lfSub').textContent =
tab === 'lost_found_pet'
? 'Community posts for missing or found pets (stored locally in your browser)'
: 'Community posts for missing or found people (stored locally in your browser)';
// Active markers in nav
document.querySelectorAll('.drop-item,.drawer-item').forEach(el => {
el.classList.toggle('active-tab', el.dataset.tab === tab);
});
renderLF();
sec.scrollIntoView({ behavior:'smooth' });
}
function renderLF() {
const key = currentLFTab === 'lost_found_pet' ? LS.lfPet : LS.lfHuman;
const posts = JSON.parse(localStorage.getItem(key) || '[]');
const grid = document.getElementById('lfGrid');
if (!posts.length) {
grid.innerHTML = `<div class="lf-empty">No posts yet. Click "Add Post" to create one.</div>`;
return;
}
grid.innerHTML = posts.slice().reverse().map((post, ri) => {
const realIdx = posts.length - 1 - ri;
return `
<div class="lf-card">
<span class="lf-type ${post.type}">${post.type.toUpperCase()}</span>
<div class="lf-card-name">${esc(post.name)}</div>
<div class="lf-card-loc"><i data-feather="map-pin"></i>${esc(post.location)}</div>
${post.details ? `<div class="lf-card-details">${esc(post.details)}</div>` : ''}
${post.contact ? `<div class="lf-card-contact"><i data-feather="phone"></i>${esc(post.contact)}</div>` : ''}
<div class="lf-card-foot">
<span class="lf-card-date">${post.date}</span>
<button class="lf-card-del" onclick="deleteLF(${realIdx})"><i data-feather="trash-2"></i> Delete</button>
</div>
</div>`;
}).join('');
feather.replace();
}
function submitLF() {
const name = document.getElementById('lfName').value.trim();
const location= document.getElementById('lfLocation').value.trim();
const contact = document.getElementById('lfContact').value.trim();
const details = document.getElementById('lfDetails').value.trim();
const type = document.getElementById('lfType').value;
if (!name || !location) { toast('Name and location are required.','err'); return; }
const key = currentLFTab === 'lost_found_pet' ? LS.lfPet : LS.lfHuman;
const posts = JSON.parse(localStorage.getItem(key) || '[]');
posts.push({ name, location, contact, details, type,
date: new Date().toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'}) });
localStorage.setItem(key, JSON.stringify(posts));
// Reset form
['lfName','lfLocation','lfContact','lfDetails'].forEach(id => document.getElementById(id).value = '');
document.getElementById('lfFormBg').classList.remove('open');
toast('Post added!','ok');
renderLF();
}
window.deleteLF = function(idx) {
const key = currentLFTab === 'lost_found_pet' ? LS.lfPet : LS.lfHuman;
const posts = JSON.parse(localStorage.getItem(key) || '[]');
posts.splice(idx, 1);
localStorage.setItem(key, JSON.stringify(posts));
renderLF();
};
// ── UTILS ─────────────────────────────────────────────────────
function haversine(lat1,lon1,lat2,lon2) {
const R = 6371, d = Math.PI/180;
const a = Math.sin((lat2-lat1)*d/2)**2 +
Math.cos(lat1*d)*Math.cos(lat2*d)*Math.sin((lon2-lon1)*d/2)**2;
return R * 2 * Math.atan2(Math.sqrt(a),Math.sqrt(1-a));
}
function fmtDist(km) {
if (unit === 'mi') {
const mi = km * 0.621371;
return mi < 0.1 ? `${Math.round(mi*5280)} ft` : `${mi.toFixed(1)} mi`;
}
return km < 1 ? `${Math.round(km*1000)} m` : `${km.toFixed(1)} km`;
}
function openStatus(p) {
if (!p.hours) return 'unknown';
if (p.hours === '24/7') return 'open';
if (/off|closed/i.test(p.hours)) return 'closed';
return 'unknown';
}
function starsHTML(avg) {
let h = '';
for (let i = 1; i <= 5; i++) {
if (i <= Math.round(avg))
h += `<svg class="star-d" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>`;
else
h += `<svg class="star-e" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>`;
}
return h;
}
function showLoader(on) { document.getElementById('mapLoading').classList.toggle('vis', on); }
function toast(msg, type = '') {
const wrap = document.getElementById('toastWrap');
const t = document.createElement('div');
t.className = `toast ${type}`;
t.textContent = msg;
wrap.appendChild(t);
setTimeout(() => t.remove(), 3100);
}
function esc(s) {
return String(s||'')
.replace(/&/g,'&').replace(/</g,'<')
.replace(/>/g,'>').replace(/"/g,'"');
}