-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
763 lines (702 loc) · 43.7 KB
/
App.tsx
File metadata and controls
763 lines (702 loc) · 43.7 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
import React, { useState, useEffect, useMemo } from 'react';
import Layout from './components/Layout';
import { LoginPage } from './components/LoginPage';
import FoodCard from './components/FoodCard';
import PostingsMap from './components/PostingsMap';
import ContactUs from './components/ContactUs';
import HelpFAQ from './components/HelpFAQ';
import ProfileView from './components/ProfileView';
import SettingsView from './components/SettingsView';
import SplashScreen from './components/SplashScreen';
import ChatModal from './components/ChatModal';
import LiveTrackingModal from './components/LiveTrackingModal';
import VerificationRequestModal from './components/VerificationRequestModal';
import RoutePlannerModal from './components/RoutePlannerModal';
import AddDonationView from './components/AddDonationView';
import RatingModal from './components/RatingModal';
import AboutCreators from './components/AboutCreators';
import AppStory from './components/AppStory';
import ScrollReveal from './components/ScrollReveal';
import { User, UserRole, FoodPosting, FoodStatus, Notification, DonationType } from './types';
import { storage, calculateDistance } from './services/storageService';
import { optimizeMultiStopRoute, MultiStopRouteResult } from './services/geminiService';
import { auth, onAuthStateChanged, signOut } from './services/firebaseConfig';
import { getTranslation } from './services/translations';
import { triggerHaptic } from './services/haptics';
import { getCurrentLocation } from './services/mapLoader';
const QUOTES = [
"No one has ever become poor by giving.",
"We make a living by what we get, but we make a life by what we give.",
"The best way to find yourself is to lose yourself in the service of others.",
"Happiness doesn't result from what we get, but from what we give."
];
const App: React.FC = () => {
const [user, setUser] = useState<User | null>(null);
const [view, setView] = useState<'LOGIN' | 'DASHBOARD' | 'PROFILE' | 'SETTINGS' | 'CONTACT' | 'HELP' | 'ADD_DONATION' | 'ABOUT' | 'STORY'>('LOGIN');
const [showSplash, setShowSplash] = useState(true);
// Data State
const [postings, setPostings] = useState<FoodPosting[]>([]);
const [notifications, setNotifications] = useState<Notification[]>([]);
// UI State
const [activeTab, setActiveTab] = useState<string>('active');
const [viewMode, setViewMode] = useState<'list' | 'map'>('list');
const [userLocation, setUserLocation] = useState<{lat: number, lng: number} | undefined>(undefined);
const [selectedPostingId, setSelectedPostingId] = useState<string | null>(null);
const [activeChatPostingId, setActiveChatPostingId] = useState<string | null>(null);
const [activeTrackingPostingId, setActiveTrackingPostingId] = useState<string | null>(null);
const [isRefreshing, setIsRefreshing] = useState(false);
const [dailyQuote, setDailyQuote] = useState(QUOTES[0]);
const [initialDonationType, setInitialDonationType] = useState<DonationType>('FOOD');
const [scrollY, setScrollY] = useState(0);
// Rating State
const [activeRatingSession, setActiveRatingSession] = useState<{ postingId: string, targetId: string, targetName: string } | null>(null);
// Route Planning State
const [isOptimizingRoute, setIsOptimizingRoute] = useState(false);
const [optimizedRoute, setOptimizedRoute] = useState<MultiStopRouteResult | null>(null);
// Pending Verification State for Donors
const [pendingVerificationPosting, setPendingVerificationPosting] = useState<FoodPosting | null>(null);
// Calculate Lives Touched for Donors & Impact Metrics
const impactMetrics = useMemo(() => {
if (!user) return { lives: 0, meals: 0, co2: 0 };
// Filter relevant completed postings based on role
let completedPostings: FoodPosting[] = [];
if (user.role === UserRole.DONOR) {
completedPostings = postings.filter(p => p.donorId === user.id && p.status === FoodStatus.DELIVERED);
} else if (user.role === UserRole.VOLUNTEER) {
completedPostings = postings.filter(p => p.volunteerId === user.id && p.status === FoodStatus.DELIVERED);
} else if (user.role === UserRole.REQUESTER) {
completedPostings = postings.filter(p => p.orphanageId === user.id && p.status === FoodStatus.DELIVERED);
}
const lives = completedPostings.reduce((total, p) => {
const qtyString = p.quantity ? p.quantity.toLowerCase() : '';
const match = qtyString.match(/(\d+)/);
if (!match) return total;
const val = parseInt(match[1], 10);
// Rule: 1 kg = 2 meals (lives touched)
if (qtyString.includes('kg')) return total + (val * 2);
return total + val;
}, 0);
// Approx 2.5kg CO2 saved per kg of food waste prevented. Assuming 1 meal ~ 0.5kg
const co2 = parseFloat((lives * 0.5 * 2.5).toFixed(1));
return { lives, meals: lives, co2 };
}, [postings, user]);
// Scroll Listener for Parallax
useEffect(() => {
const handleScroll = () => setScrollY(window.scrollY);
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
// Data Fetching
const refreshData = async () => {
if (isRefreshing) return;
triggerHaptic('impactLight');
setIsRefreshing(true);
try {
const freshPostings = await storage.getPostings();
setPostings(freshPostings);
if (user) {
const freshNotifs = await storage.getNotifications(user.id);
setNotifications(freshNotifs);
}
} catch (error) {
console.error("Error refreshing data:", error);
} finally {
setTimeout(() => setIsRefreshing(false), 600);
}
};
// Auth Persistence
useEffect(() => {
if (auth) {
const unsubscribe = onAuthStateChanged(auth, async (firebaseUser: any) => {
if (firebaseUser) {
try {
let matchedUser = await storage.getUser(firebaseUser.uid);
if (!matchedUser && firebaseUser.email) {
const allUsers = await storage.getUsers();
matchedUser = allUsers.find(u => u.email === firebaseUser.email);
}
if (!matchedUser && firebaseUser.phoneNumber) {
const allUsers = await storage.getUsers();
const fPhone = firebaseUser.phoneNumber.replace(/\D/g, '');
matchedUser = allUsers.find(u => {
const uPhone = (u.contactNo || '').replace(/\D/g, '');
return uPhone && fPhone.includes(uPhone);
});
}
if (matchedUser && (!user || user.id !== matchedUser.id)) {
setUser(matchedUser);
setView('DASHBOARD');
}
} catch (e) {
console.error("Auth detection failed:", e);
}
}
});
return () => unsubscribe();
}
}, [user]);
useEffect(() => {
const timer = setTimeout(() => setShowSplash(false), 2500);
setDailyQuote(QUOTES[Math.floor(Math.random() * QUOTES.length)]);
return () => clearTimeout(timer);
}, []);
useEffect(() => {
refreshData();
if (user) {
if (user.role === UserRole.DONOR) setActiveTab('active');
else if (user.role === UserRole.VOLUNTEER) setActiveTab('opportunities');
else setActiveTab('browse');
}
const interval = setInterval(() => {
storage.getPostings().then(setPostings);
if (user) storage.getNotifications(user.id).then(setNotifications);
}, 10000);
let watchId: number;
if (user?.role === UserRole.VOLUNTEER) {
watchId = navigator.geolocation.watchPosition(
(pos) => {
const { latitude, longitude } = pos.coords;
setUserLocation({ lat: latitude, lng: longitude });
storage.getPostings().then(allPostings => {
const activePostings = allPostings.filter(p =>
(p.status === FoodStatus.IN_TRANSIT ||
p.status === FoodStatus.PICKUP_VERIFICATION_PENDING ||
p.status === FoodStatus.DELIVERY_VERIFICATION_PENDING) &&
p.volunteerId === user.id
);
if (activePostings.length > 0) {
activePostings.forEach(p => {
storage.updatePosting(p.id, { volunteerLocation: { lat: latitude, lng: longitude } });
});
}
});
},
(err) => console.log("Location tracking denied", err),
{ enableHighAccuracy: true, maximumAge: 10000, timeout: 5000 }
);
} else {
getCurrentLocation()
.then((pos) => setUserLocation({ lat: pos.lat, lng: pos.lng }))
.catch((err) => console.log("Location access denied/failed", err));
}
return () => {
clearInterval(interval);
if (watchId) navigator.geolocation.clearWatch(watchId);
};
}, [user]);
useEffect(() => {
if (!user || user.role !== UserRole.DONOR) return;
const checkPendingVerifications = async () => {
const currentPostings = await storage.getPostings();
const pending = currentPostings.find(p =>
p.donorId === user.id &&
(p.status === FoodStatus.PICKUP_VERIFICATION_PENDING || p.status === FoodStatus.DELIVERY_VERIFICATION_PENDING)
);
if (pending) {
if (!pendingVerificationPosting || pendingVerificationPosting.id !== pending.id || pendingVerificationPosting.status !== pending.status) {
setPendingVerificationPosting(pending);
triggerHaptic('impactMedium');
}
} else {
if (pendingVerificationPosting) {
setPendingVerificationPosting(null);
}
}
};
checkPendingVerifications();
const interval = setInterval(checkPendingVerifications, 5000);
return () => clearInterval(interval);
}, [user, pendingVerificationPosting]);
const handleStartDonation = (type: DonationType) => {
triggerHaptic('impactMedium');
setInitialDonationType(type);
setView('ADD_DONATION');
};
const filteredPostings = useMemo(() => {
if (!user) return [];
let filtered = [...postings];
const sortPostings = (list: FoodPosting[]) => {
const sortOption = user.sortBy || 'NEWEST';
return list.sort((a, b) => {
if (sortOption === 'EXPIRY') {
return new Date(a.expiryDate).getTime() - new Date(b.expiryDate).getTime();
}
if (sortOption === 'CLOSEST' && userLocation) {
const distA = a.location.lat && a.location.lng ? calculateDistance(userLocation.lat, userLocation.lng, a.location.lat, a.location.lng) : Infinity;
const distB = b.location.lat && b.location.lng ? calculateDistance(userLocation.lat, userLocation.lng, b.location.lat, b.location.lng) : Infinity;
return distA - distB;
}
return b.createdAt - a.createdAt;
});
};
if (user.role === UserRole.DONOR) {
if (activeTab === 'active') return filtered.filter(p => p.donorId === user.id && p.status !== FoodStatus.DELIVERED);
else if (activeTab === 'history') return filtered.filter(p => p.donorId === user.id && p.status === FoodStatus.DELIVERED);
} else if (user.role === UserRole.VOLUNTEER) {
if (activeTab === 'opportunities') {
let opportunities = filtered.filter(p => p.status === FoodStatus.REQUESTED && !p.volunteerId);
if (user.donationTypeFilter && user.donationTypeFilter !== 'ALL') {
opportunities = opportunities.filter(p => (p.donationType || 'FOOD') === user.donationTypeFilter);
}
const radius = user.searchRadius || 10;
if (userLocation) {
opportunities = opportunities.filter(p => {
if (p.location.lat && p.location.lng) {
const dist = calculateDistance(userLocation.lat, userLocation.lng, p.location.lat, p.location.lng);
return dist <= radius;
}
return true;
});
}
return sortPostings(opportunities);
}
else if (activeTab === 'mytasks') return filtered.filter(p => p.volunteerId === user.id && p.status !== FoodStatus.DELIVERED);
else if (activeTab === 'history') return filtered.filter(p => p.volunteerId === user.id && p.status === FoodStatus.DELIVERED);
} else if (user.role === UserRole.REQUESTER) {
if (activeTab === 'browse') {
let available = filtered.filter(p => p.status === FoodStatus.AVAILABLE);
if (user.donationTypeFilter && user.donationTypeFilter !== 'ALL') {
available = available.filter(p => (p.donationType || 'FOOD') === user.donationTypeFilter);
}
const radius = user.searchRadius || 10;
if (userLocation) {
available = available.filter(p => {
if (p.location.lat && p.location.lng) {
const dist = calculateDistance(userLocation.lat, userLocation.lng, p.location.lat, p.location.lng);
return dist <= radius;
}
return true;
});
}
return sortPostings(available);
} else if (activeTab === 'myrequests') return filtered.filter(p => p.orphanageId === user.id);
}
return [];
}, [postings, user, activeTab, userLocation]);
const handleRateUser = (pid: string, targetId: string, targetName: string, rating: number, _feedback: string) => {
if (rating === 0) {
triggerHaptic('selection');
setActiveRatingSession({ postingId: pid, targetId, targetName });
}
};
const submitRating = (rating: number, feedback: string) => {
if (!user || !activeRatingSession) return;
triggerHaptic('success');
storage.submitUserRating(activeRatingSession.postingId, {
raterId: user.id,
raterRole: user.role,
targetId: activeRatingSession.targetId,
rating: rating,
feedback: feedback,
createdAt: Date.now()
});
refreshData();
alert("Rating Submitted! Thank you.");
setActiveRatingSession(null);
};
const handleDeletePosting = (id: string) => { storage.deletePosting(id); refreshData(); };
const handleOptimizeRoute = async () => {
if (!userLocation || filteredPostings.length === 0) return;
triggerHaptic('impactMedium');
setIsOptimizingRoute(true);
const stops = filteredPostings
.filter(p => p.location.lat && p.location.lng)
.map(p => ({
id: p.id,
name: p.foodName,
lat: p.location.lat!,
lng: p.location.lng!,
expiry: p.expiryDate
}));
const result = await optimizeMultiStopRoute(userLocation, stops);
if (result) {
triggerHaptic('success');
setOptimizedRoute(result);
} else {
triggerHaptic('error');
alert("Could not generate optimized route. Please try again.");
}
setIsOptimizingRoute(false);
};
const handleDonorApprove = () => { if (pendingVerificationPosting) { triggerHaptic('success'); storage.updatePosting(pendingVerificationPosting.id, { status: pendingVerificationPosting.status === FoodStatus.PICKUP_VERIFICATION_PENDING ? FoodStatus.IN_TRANSIT : FoodStatus.DELIVERED }); setPendingVerificationPosting(null); refreshData(); } };
const handleDonorReject = () => {
if (pendingVerificationPosting) {
triggerHaptic('impactMedium');
storage.updatePosting(pendingVerificationPosting.id, {
status: pendingVerificationPosting.status === FoodStatus.PICKUP_VERIFICATION_PENDING ? FoodStatus.REQUESTED : FoodStatus.IN_TRANSIT,
pickupVerificationImageUrl: pendingVerificationPosting.status === FoodStatus.PICKUP_VERIFICATION_PENDING ? undefined : pendingVerificationPosting.pickupVerificationImageUrl,
verificationImageUrl: pendingVerificationPosting.status === FoodStatus.DELIVERY_VERIFICATION_PENDING ? undefined : pendingVerificationPosting.verificationImageUrl
});
setPendingVerificationPosting(null);
refreshData();
alert("Verification Rejected. The volunteer has been notified to re-upload.");
}
};
const handleDeleteAccount = () => { if (user) { storage.deleteUser(user.id); if (auth) signOut(auth); setUser(null); setView('LOGIN'); } };
const t = (key: string) => getTranslation(key, user?.language);
// --- RENDER HELPERS ---
const renderStatsCard = (label: string, value: string | number, icon: string, bgClass: string, textClass: string, delay: number) => (
<ScrollReveal delay={delay} animation="scale-up" className={`flex-1 min-w-[140px] p-5 rounded-[2rem] border shadow-sm hover:shadow-xl hover:-translate-y-1 transition-all duration-300 group cursor-default ${bgClass} border-transparent`}>
<div className="flex items-center justify-between mb-4">
<div className={`w-12 h-12 rounded-2xl flex items-center justify-center text-2xl bg-white shadow-sm transition-transform duration-500 group-hover:rotate-[360deg]`}>
{icon}
</div>
<div className="opacity-0 group-hover:opacity-100 transition-opacity">
<svg className={`w-5 h-5 ${textClass}`} fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" /></svg>
</div>
</div>
<div>
<p className={`text-3xl font-black tracking-tight mb-1 ${textClass}`}>{value}</p>
<p className="text-[11px] font-bold uppercase tracking-widest text-slate-500 opacity-80">{label}</p>
</div>
</ScrollReveal>
);
const renderDashboardHeader = () => {
if (!user) return null;
// Scrollytelling Logic
const scrollProgress = Math.min(Math.max(0, scrollY / 200), 1); // 0 to 1
// Opacity calculations for cross-fade
const greetingOpacity = Math.max(0, 1 - scrollProgress * 2.5);
const storyOpacity = Math.min(1, Math.max(0, (scrollProgress - 0.2) * 2));
return (
<div className="flex flex-col gap-8 mb-8 animate-fade-in-up">
{/* Scrollytelling Hero Section */}
<div
className="relative overflow-hidden rounded-[2.5rem] bg-slate-900 shadow-2xl transition-all duration-300 ease-out"
style={{
transform: `translateY(${scrollY * 0.1}px)`,
height: '220px', // Fixed height for smooth transitions
}}
>
{/* Dynamic Background */}
<div
className="absolute top-0 right-0 w-96 h-96 bg-emerald-500/20 rounded-full blur-3xl transition-transform duration-700 ease-out"
style={{ transform: `translate(${scrollY * 0.2}px, ${-scrollY * 0.1}px) rotate(${scrollY * 0.1}deg)` }}
></div>
<div
className="absolute bottom-0 left-0 w-64 h-64 bg-blue-500/20 rounded-full blur-3xl transition-transform duration-700 ease-out"
style={{ transform: `translate(${-scrollY * 0.2}px, ${scrollY * 0.1}px) scale(${1 + scrollProgress * 0.5})` }}
></div>
{/* Greeting Content (Fades Out) */}
<div
className="absolute inset-0 p-8 md:p-10 flex flex-col md:flex-row md:items-end justify-between gap-6 z-10 transition-opacity duration-300"
style={{ opacity: greetingOpacity, pointerEvents: greetingOpacity > 0.1 ? 'auto' : 'none' }}
>
<div>
<div className="flex items-center gap-2 mb-2">
<span className="px-3 py-1 bg-white/10 backdrop-blur-md rounded-full text-[10px] font-black uppercase tracking-widest text-emerald-300 border border-white/10">
{user.role} Dashboard
</span>
</div>
<h2 className="text-4xl md:text-5xl font-black text-white tracking-tight leading-none mb-3">
{t('greeting')}, <br/>
<span className="text-transparent bg-clip-text bg-gradient-to-r from-emerald-400 to-teal-200">{user.name?.split(' ')[0]}</span>.
</h2>
<p className="text-slate-400 font-medium text-sm md:text-base max-w-lg leading-relaxed">
"{dailyQuote}"
</p>
</div>
{user.role === UserRole.DONOR && (
<button
onClick={() => handleStartDonation('FOOD')}
className="w-full md:w-auto py-4 px-8 bg-emerald-500 hover:bg-emerald-400 text-white rounded-2xl font-bold text-xs uppercase tracking-widest shadow-lg shadow-emerald-500/20 transition-all active:scale-95 flex items-center justify-center gap-2 group"
>
<span className="text-lg group-hover:scale-110 transition-transform">➕</span>
Add Donation
</button>
)}
</div>
{/* Impact Story Content (Fades In) */}
<div
className="absolute inset-0 p-8 md:p-10 flex flex-col justify-center items-center text-center z-10 transition-opacity duration-300"
style={{
opacity: storyOpacity,
transform: `translateY(${(1 - storyOpacity) * 20}px)`,
pointerEvents: storyOpacity > 0.1 ? 'auto' : 'none'
}}
>
<div className="mb-2 inline-flex items-center gap-2 px-3 py-1 bg-white/10 backdrop-blur-md rounded-full text-[10px] font-black uppercase tracking-widest text-emerald-300 border border-white/10">
<span className="animate-pulse">✨</span> Impact Journey
</div>
<h2 className="text-3xl md:text-4xl font-black text-white tracking-tight leading-tight mb-2">
{user.role === UserRole.DONOR ? "You are a Food Hero" :
user.role === UserRole.VOLUNTEER ? "Driving Change" :
"Community Strength"}
</h2>
<div className="flex gap-6 mt-2">
{impactMetrics.lives > 0 ? (
<div className="flex flex-col items-center">
<span className="text-2xl font-black text-emerald-400">{impactMetrics.lives}</span>
<span className="text-[10px] uppercase font-bold text-slate-400 tracking-widest">Lives Touched</span>
</div>
) : (
<p className="text-slate-400 text-sm font-medium">Your journey to zero hunger starts today.</p>
)}
{impactMetrics.co2 > 0 && (
<>
<div className="w-px bg-white/20 h-8 self-center"></div>
<div className="flex flex-col items-center">
<span className="text-2xl font-black text-blue-400">{impactMetrics.co2}kg</span>
<span className="text-[10px] uppercase font-bold text-slate-400 tracking-widest">CO₂ Saved</span>
</div>
</>
)}
</div>
</div>
</div>
{/* Stats Grid */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
{user.role === UserRole.DONOR && (
<>
{renderStatsCard(t('stat_impact'), impactMetrics.lives, "✨", "bg-orange-50/50", "text-orange-600", 100)}
{renderStatsCard(t('stat_donations'), postings.filter(p => p.donorId === user.id).length, "🎁", "bg-emerald-50/50", "text-emerald-600", 200)}
{renderStatsCard("Active", postings.filter(p => p.donorId === user.id && p.status !== FoodStatus.DELIVERED).length, "⏳", "bg-blue-50/50", "text-blue-600", 300)}
{renderStatsCard("Completed", postings.filter(p => p.donorId === user.id && p.status === FoodStatus.DELIVERED).length, "✅", "bg-purple-50/50", "text-purple-600", 400)}
</>
)}
{user.role === UserRole.VOLUNTEER && (
<>
{renderStatsCard(t('stat_reputation'), user.averageRating?.toFixed(1) || "5.0", "⭐", "bg-amber-50/50", "text-amber-600", 100)}
{renderStatsCard(t('stat_missions'), postings.filter(p => p.volunteerId === user.id && p.status === FoodStatus.DELIVERED).length, "🚴", "bg-blue-50/50", "text-blue-600", 200)}
{renderStatsCard("In Progress", postings.filter(p => p.volunteerId === user.id && p.status !== FoodStatus.DELIVERED).length, "🔥", "bg-rose-50/50", "text-rose-600", 300)}
{renderStatsCard("Badges", 2, "🏅", "bg-teal-50/50", "text-teal-600", 400)}
</>
)}
{user.role === UserRole.REQUESTER && (
<>
{renderStatsCard(t('stat_requests'), postings.filter(p => p.orphanageId === user.id).length, "📝", "bg-purple-50/50", "text-purple-600", 100)}
{renderStatsCard(t('stat_received'), postings.filter(p => p.orphanageId === user.id && p.status === FoodStatus.DELIVERED).length, "🥣", "bg-teal-50/50", "text-teal-600", 200)}
{renderStatsCard("Volunteers", 5, "🤝", "bg-indigo-50/50", "text-indigo-600", 300)}
{renderStatsCard("Saved", "₹2k", "💰", "bg-emerald-50/50", "text-emerald-600", 400)}
</>
)}
</div>
</div>
);
};
const renderTabs = () => {
if (!user) return null;
const isActive = (tab: string) => activeTab === tab;
const btnClass = (active: boolean) => `flex-1 py-3 px-4 text-xs font-black uppercase tracking-widest transition-all rounded-2xl relative overflow-hidden ${active ? 'bg-slate-900 text-white shadow-lg shadow-slate-900/20 scale-105' : 'text-slate-500 hover:bg-slate-100'}`;
return (
<div className="flex items-center justify-between mb-8 sticky top-24 z-30 py-4 -mx-6 px-6 transition-all bg-gradient-to-b from-slate-50 via-slate-50/95 to-transparent">
<div className="bg-white/80 backdrop-blur-xl p-1.5 rounded-[20px] border border-white/50 shadow-lg shadow-slate-200/50 flex flex-1 max-w-lg ring-1 ring-slate-100">
{user.role === UserRole.DONOR && (
<>
<button onClick={() => { setActiveTab('active'); triggerHaptic('selection'); }} className={btnClass(isActive('active'))}>{t('tab_active')}</button>
<button onClick={() => { setActiveTab('history'); triggerHaptic('selection'); }} className={btnClass(isActive('history'))}>{t('tab_history')}</button>
</>
)}
{user.role === UserRole.VOLUNTEER && (
<>
<button onClick={() => { setActiveTab('opportunities'); triggerHaptic('selection'); }} className={btnClass(isActive('opportunities'))}>{t('tab_find')}</button>
<button onClick={() => { setActiveTab('mytasks'); triggerHaptic('selection'); }} className={btnClass(isActive('mytasks'))}>{t('tab_tasks')}</button>
<button onClick={() => { setActiveTab('history'); triggerHaptic('selection'); }} className={btnClass(isActive('history'))}>{t('tab_history')}</button>
</>
)}
{user.role === UserRole.REQUESTER && (
<>
<button onClick={() => { setActiveTab('browse'); triggerHaptic('selection'); }} className={btnClass(isActive('browse'))}>{t('tab_browse')}</button>
<button onClick={() => { setActiveTab('myrequests'); triggerHaptic('selection'); }} className={btnClass(isActive('myrequests'))}>{t('tab_myreq')}</button>
</>
)}
</div>
<div className="flex items-center gap-3 shrink-0 ml-4">
{user.role === UserRole.VOLUNTEER && activeTab === 'opportunities' && (
<button
onClick={handleOptimizeRoute}
disabled={isOptimizingRoute || filteredPostings.length === 0}
className="h-12 px-4 flex items-center justify-center bg-purple-600 hover:bg-purple-700 text-white rounded-2xl shadow-lg shadow-purple-200 transition-all active:scale-95 disabled:opacity-50 hover:-translate-y-0.5"
>
{isOptimizingRoute ? (
<svg className="animate-spin w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" /></svg>
) : (
<div className="flex items-center gap-2">
<span className="text-lg">✨</span>
<span className="text-xs font-black uppercase tracking-widest hidden md:inline">{t('btn_smart_route')}</span>
</div>
)}
</button>
)}
<button
onClick={refreshData}
disabled={isRefreshing}
className="w-12 h-12 flex items-center justify-center bg-white border border-slate-200 rounded-2xl text-slate-400 hover:text-emerald-600 hover:border-emerald-200 hover:shadow-lg transition-all active:scale-95 group"
>
<svg className={`w-5 h-5 group-hover:rotate-180 transition-transform duration-700 ${isRefreshing ? 'animate-spin' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" /></svg>
</button>
{(user.role === UserRole.VOLUNTEER && activeTab === 'opportunities') || (user.role === UserRole.REQUESTER && activeTab === 'browse') ? (
<div className="flex bg-white p-1 rounded-2xl border border-slate-200 shadow-sm">
<button onClick={() => setViewMode('list')} className={`w-10 h-10 flex items-center justify-center rounded-xl transition-all ${viewMode === 'list' ? 'bg-slate-900 text-white' : 'text-slate-400 hover:text-slate-600'}`}>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 6h16M4 12h16M4 18h16" /></svg>
</button>
<button onClick={() => setViewMode('map')} className={`w-10 h-10 flex items-center justify-center rounded-xl transition-all ${viewMode === 'map' ? 'bg-emerald-500 text-white' : 'text-slate-400 hover:text-slate-600'}`}>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7" /></svg>
</button>
</div>
) : null}
</div>
</div>
);
};
const renderContent = () => {
if (filteredPostings.length === 0) {
return (
<ScrollReveal className="flex flex-col items-center justify-center py-24 text-center bg-white rounded-[2.5rem] border border-slate-100 border-dashed shadow-sm">
<div className="w-32 h-32 bg-slate-50 rounded-full flex items-center justify-center mb-6 shadow-inner relative animate-bounce-slow">
<span className="text-6xl grayscale opacity-30 select-none">🍃</span>
<div className="absolute -bottom-2 -right-2 w-12 h-12 bg-white rounded-full flex items-center justify-center shadow-md text-2xl border border-slate-100">✨</div>
</div>
<h3 className="text-2xl font-black text-slate-800 mb-2 tracking-tight">{t('nothing_title')}</h3>
<p className="text-slate-500 font-medium max-w-xs mx-auto leading-relaxed mb-8">
{user?.role === UserRole.DONOR ? t('nothing_desc_donor') :
user?.role === UserRole.VOLUNTEER && activeTab === 'opportunities' ? "No requests pending. Wait for a beneficiary to request food!" :
t('nothing_desc_other')}
</p>
{user?.role === UserRole.DONOR && activeTab === 'active' && (
<button onClick={() => handleStartDonation('FOOD')} className="px-8 py-4 bg-slate-900 text-white font-black rounded-2xl uppercase text-xs tracking-widest shadow-xl hover:bg-slate-800 hover:scale-105 transition-all">
{t('btn_donate')}
</button>
)}
</ScrollReveal>
);
}
if (viewMode === 'map' && ((user?.role === UserRole.VOLUNTEER && activeTab === 'opportunities') || (user?.role === UserRole.REQUESTER && activeTab === 'browse'))) {
return (
<ScrollReveal animation="scale-up" className="h-[650px] w-full rounded-[2.5rem] overflow-hidden shadow-2xl border border-white ring-4 ring-slate-100 relative z-0">
<PostingsMap
postings={filteredPostings}
userLocation={userLocation}
onPostingSelect={(id) => { setSelectedPostingId(id); triggerHaptic('selection'); }}
/>
<div className="absolute bottom-0 left-0 right-0 h-24 bg-gradient-to-t from-black/50 to-transparent pointer-events-none"></div>
</ScrollReveal>
);
}
return (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 pb-20">
{filteredPostings.map((post, idx) => (
<ScrollReveal key={post.id} delay={idx * 100} animation="fade-up">
<FoodCard
posting={post}
user={user!}
onUpdate={(id, updates) => { storage.updatePosting(id, updates); refreshData(); }}
onDelete={handleDeletePosting}
currentLocation={userLocation}
onRateUser={handleRateUser}
onChatClick={(id) => { setActiveChatPostingId(id); triggerHaptic('selection'); }}
onTrackClick={(id) => { setActiveTrackingPostingId(id); triggerHaptic('selection'); }}
/>
</ScrollReveal>
))}
</div>
);
};
if (showSplash) return <SplashScreen />;
if (view === 'STORY') return <AppStory onBack={() => user ? setView('DASHBOARD') : setView('LOGIN')} />;
if (!user || view === 'LOGIN') return <LoginPage onLogin={(user) => { setUser(user); setView('DASHBOARD'); }} onShowStory={() => setView('STORY')} />;
if (view === 'PROFILE' && user) return <Layout user={user} onLogout={() => { if (auth) signOut(auth); setUser(null); setView('LOGIN'); }} onProfileClick={() => {}} onLogoClick={() => setView('DASHBOARD')} onContactClick={() => setView('CONTACT')} onHelpClick={() => setView('HELP')} onSettingsClick={() => setView('SETTINGS')} notifications={notifications}><ProfileView user={user} onUpdate={(updates) => { storage.updateUser(user.id, updates); setUser({ ...user, ...updates }); }} onBack={() => setView('DASHBOARD')} /></Layout>;
if (view === 'SETTINGS' && user) return <Layout user={user} onLogout={() => { if (auth) signOut(auth); setUser(null); setView('LOGIN'); }} onProfileClick={() => setView('PROFILE')} onLogoClick={() => setView('DASHBOARD')} onContactClick={() => setView('CONTACT')} onHelpClick={() => setView('HELP')} onSettingsClick={() => {}} notifications={notifications}><SettingsView user={user} onUpdate={(updates) => { storage.updateUser(user.id, updates); setUser({ ...user, ...updates }); }} onDelete={handleDeleteAccount} onBack={() => setView('DASHBOARD')} onAboutClick={() => setView('ABOUT')} onStoryClick={() => setView('STORY')} /></Layout>;
if (view === 'CONTACT' && user) return <Layout user={user} onLogout={() => { if (auth) signOut(auth); setUser(null); setView('LOGIN'); }} onProfileClick={() => setView('PROFILE')} onLogoClick={() => setView('DASHBOARD')} onContactClick={() => {}} onHelpClick={() => setView('HELP')} onSettingsClick={() => setView('SETTINGS')} notifications={notifications}><ContactUs user={user} onBack={() => setView('DASHBOARD')} /></Layout>;
if (view === 'HELP' && user) return <Layout user={user} onLogout={() => { if (auth) signOut(auth); setUser(null); setView('LOGIN'); }} onProfileClick={() => setView('PROFILE')} onLogoClick={() => setView('DASHBOARD')} onContactClick={() => setView('CONTACT')} onHelpClick={() => {}} onSettingsClick={() => setView('SETTINGS')} notifications={notifications}><HelpFAQ onBack={() => setView('DASHBOARD')} onContact={() => setView('CONTACT')} /></Layout>;
if (view === 'ADD_DONATION' && user) return <Layout user={user} onLogout={() => { if (auth) signOut(auth); setUser(null); setView('LOGIN'); }} onProfileClick={() => setView('PROFILE')} onLogoClick={() => setView('DASHBOARD')} onContactClick={() => setView('CONTACT')} onHelpClick={() => setView('HELP')} onSettingsClick={() => setView('SETTINGS')} notifications={notifications}><AddDonationView user={user} initialType={initialDonationType} onBack={() => setView('DASHBOARD')} onSuccess={(posting) => {
setView('DASHBOARD');
if (posting) {
setPostings(prev => [posting, ...prev]);
setSelectedPostingId(posting.id);
}
refreshData();
}} /></Layout>;
if (view === 'ABOUT' && user) return <Layout user={user} onLogout={() => { if (auth) signOut(auth); setUser(null); setView('LOGIN'); }} onProfileClick={() => setView('PROFILE')} onLogoClick={() => setView('DASHBOARD')} onContactClick={() => setView('CONTACT')} onHelpClick={() => setView('HELP')} onSettingsClick={() => setView('SETTINGS')} notifications={notifications}><AboutCreators onBack={() => setView('DASHBOARD')} /></Layout>;
return (
<Layout
user={user}
onLogout={() => { if (auth) signOut(auth); setUser(null); setView('LOGIN'); }}
onProfileClick={() => setView('PROFILE')}
onLogoClick={() => setView('DASHBOARD')}
onContactClick={() => setView('CONTACT')}
onHelpClick={() => setView('HELP')}
onSettingsClick={() => setView('SETTINGS')}
notifications={notifications}
>
{user && !selectedPostingId && (
<div className="space-y-4">
{renderDashboardHeader()}
{renderTabs()}
{renderContent()}
</div>
)}
{/* Detail Page View */}
{user && selectedPostingId && (
<div className="animate-fade-in-up pb-10">
<button
onClick={() => setSelectedPostingId(null)}
className="mb-6 flex items-center text-slate-500 font-bold text-sm hover:text-emerald-600 transition-colors"
>
<svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 19l-7-7 7-7" /></svg>
Back to Dashboard
</button>
{(() => {
const p = postings.find(p => p.id === selectedPostingId);
if (!p) return <div className="text-center py-10 text-slate-400 font-bold">Posting not found</div>;
return (
<div className="max-w-2xl mx-auto">
<FoodCard
posting={p}
user={user}
onUpdate={(id, updates) => { storage.updatePosting(id, updates); refreshData(); }}
onDelete={handleDeletePosting}
currentLocation={userLocation}
onRateUser={handleRateUser}
onChatClick={(id) => { setActiveChatPostingId(id); triggerHaptic('selection'); }}
onTrackClick={(id) => { setActiveTrackingPostingId(id); triggerHaptic('selection'); }}
/>
</div>
);
})()}
</div>
)}
{/* Floating Action Button */}
{user?.role === UserRole.DONOR && !selectedPostingId && (
<button
onClick={() => handleStartDonation('FOOD')}
className="fixed bottom-10 right-10 w-16 h-16 bg-slate-900 text-white rounded-full shadow-2xl shadow-slate-900/40 flex items-center justify-center transition-all hover:scale-110 active:scale-95 z-40 group border-4 border-white hover:rotate-90 md:hidden"
>
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.5" d="M12 6v6m0 0v6m0-6h6m-6 0H6" /></svg>
</button>
)}
{pendingVerificationPosting && <VerificationRequestModal posting={pendingVerificationPosting} onApprove={handleDonorApprove} onReject={handleDonorReject} />}
{activeChatPostingId && (
(() => {
const activePosting = postings.find(p => p.id === activeChatPostingId);
// Safe render: ensure posting and user exist
if (activePosting && user) {
return <ChatModal posting={activePosting} user={user} onClose={() => setActiveChatPostingId(null)} />;
}
return null;
})()
)}
{activeTrackingPostingId && <LiveTrackingModal posting={postings.find(p => p.id === activeTrackingPostingId)!} onClose={() => setActiveTrackingPostingId(null)} />}
{activeRatingSession && (
<RatingModal
targetName={activeRatingSession.targetName}
title={`Rate ${activeRatingSession.targetName}`}
onSubmit={submitRating}
onClose={() => setActiveRatingSession(null)}
/>
)}
{optimizedRoute && (
<RoutePlannerModal
orderedPostings={optimizedRoute.orderedStopIds.map(id => postings.find(p => p.id === id)!).filter(Boolean)}
routeOverview={optimizedRoute.overview}
totalTime={optimizedRoute.totalEstimatedTime}
stopReasoning={optimizedRoute.stopReasoning}
onClose={() => setOptimizedRoute(null)}
onSelectPosting={(id) => { setOptimizedRoute(null); setSelectedPostingId(id); triggerHaptic('selection'); }}
language={user?.language}
/>
)}
</Layout>
);
};
export default App;